uncial 0.0.6 → 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 (88) hide show
  1. package/README.md +174 -11
  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 +5 -2
  6. package/dist/core/index.js +3 -1
  7. package/dist/core/issues.d.ts +7 -0
  8. package/dist/core/issues.js +9 -0
  9. package/dist/core/meta.d.ts +7 -0
  10. package/dist/core/meta.js +67 -0
  11. package/dist/core/migrations.d.ts +30 -0
  12. package/dist/core/migrations.js +43 -0
  13. package/dist/core/normalize.d.ts +12 -1
  14. package/dist/core/normalize.js +115 -20
  15. package/dist/core/registry.d.ts +7 -0
  16. package/dist/core/registry.js +25 -5
  17. package/dist/core/runtime.d.ts +7 -0
  18. package/dist/core/types.d.ts +12 -2
  19. package/dist/core/validate.js +24 -6
  20. package/dist/editor/AttributeFieldControl.svelte +141 -0
  21. package/dist/editor/AttributeFieldControl.svelte.d.ts +12 -0
  22. package/dist/editor/BlockAttributesPanel.svelte +74 -162
  23. package/dist/editor/BlockAttributesPanel.svelte.d.ts +9 -1
  24. package/dist/editor/BlockMenu.svelte +24 -35
  25. package/dist/editor/BlockMenu.svelte.d.ts +5 -19
  26. package/dist/editor/DocumentMetaPanel.svelte +69 -0
  27. package/dist/editor/DocumentMetaPanel.svelte.d.ts +10 -0
  28. package/dist/editor/Editor.svelte +131 -263
  29. package/dist/editor/Editor.svelte.d.ts +6 -2
  30. package/dist/editor/LinkAttributesPanel.svelte +32 -19
  31. package/dist/editor/RichTextAttributeEditor.svelte +81 -141
  32. package/dist/editor/RichTextAttributeEditor.svelte.d.ts +2 -1
  33. package/dist/editor/Toolbar.svelte +42 -10
  34. package/dist/editor/attributeTargets.d.ts +23 -0
  35. package/dist/editor/attributeTargets.js +21 -0
  36. package/dist/editor/attributesController.d.ts +7 -0
  37. package/dist/editor/attributesController.js +118 -229
  38. package/dist/editor/bindEditor.d.ts +2 -0
  39. package/dist/editor/bindEditor.js +108 -27
  40. package/dist/editor/chooseAttribute.d.ts +26 -0
  41. package/dist/editor/chooseAttribute.js +10 -0
  42. package/dist/editor/containerChildOps.d.ts +33 -0
  43. package/dist/editor/containerChildOps.js +94 -0
  44. package/dist/editor/dropdownDismiss.d.ts +18 -0
  45. package/dist/editor/dropdownDismiss.js +46 -0
  46. package/dist/editor/index.d.ts +7 -1
  47. package/dist/editor/index.js +5 -1
  48. package/dist/editor/linkController.d.ts +19 -0
  49. package/dist/editor/linkController.js +72 -0
  50. package/dist/editor/metaController.d.ts +19 -0
  51. package/dist/editor/metaController.js +71 -0
  52. package/dist/editor/toolbarFeatures.d.ts +12 -0
  53. package/dist/editor/toolbarFeatures.js +36 -0
  54. package/dist/render/Renderer.svelte +13 -4
  55. package/dist/render/Renderer.svelte.d.ts +2 -0
  56. package/dist/render/RichContent.svelte +2 -2
  57. package/dist/render/RichNode.svelte +18 -9
  58. package/dist/render/RichText.svelte +2 -1
  59. package/dist/render/sanitize.d.ts +6 -0
  60. package/dist/render/sanitize.js +20 -1
  61. package/dist/runtime/reactiveProps.svelte.d.ts +16 -0
  62. package/dist/runtime/reactiveProps.svelte.js +16 -0
  63. package/dist/runtime/svelte.d.ts +2 -1
  64. package/dist/runtime/svelte.js +26 -6
  65. package/dist/shared/EditorBlockFixture.svelte +24 -0
  66. package/dist/shared/EditorBlockFixture.svelte.d.ts +9 -0
  67. package/dist/shared/content.d.ts +2 -1
  68. package/dist/shared/content.js +9 -3
  69. package/dist/shared/document.d.ts +1 -0
  70. package/dist/shared/guards.d.ts +13 -0
  71. package/dist/shared/guards.js +16 -0
  72. package/dist/shared/richText.js +20 -4
  73. package/dist/shared/runtimeId.d.ts +8 -0
  74. package/dist/shared/runtimeId.js +8 -0
  75. package/dist/shared/tiptap.js +58 -23
  76. package/dist/styles/base.css +418 -0
  77. package/dist/styles/chrome.css +3 -0
  78. package/dist/styles/controls.css +306 -0
  79. package/dist/styles/index.css +2 -0
  80. package/dist/styles/prose.css +115 -0
  81. package/dist/styles/tokens.css +77 -0
  82. package/dist/web-components/UncialEditor.svelte +16 -1
  83. package/dist/web-components/UncialEditor.svelte.d.ts +5 -2
  84. package/dist/web-components/index.d.ts +39 -10
  85. package/dist/web-components/index.js +86 -36
  86. package/dist/web-components/reactiveProps.svelte.d.ts +10 -0
  87. package/dist/web-components/reactiveProps.svelte.js +13 -0
  88. package/package.json +7 -1
@@ -1,5 +1,16 @@
1
1
  import type { PMDoc } from '../shared/document.js';
2
2
  import type { ContentSchema } from './types.js';
3
3
  import { resolveRegistry } from './registry.js';
4
- export declare const CURRENT_DOCUMENT_VERSION = 1;
4
+ export { CURRENT_DOCUMENT_VERSION } from './migrations.js';
5
+ /**
6
+ * Sanitizes the structural shape of a raw document (object nodes with string
7
+ * types, valid text nodes, array content/marks, object attrs — no schema or
8
+ * block-attribute normalization) and runs the registered migrations on the
9
+ * result, so migration callbacks never receive hostile shapes. A throwing
10
+ * migration never propagates: on throw the sanitized-but-unmigrated document
11
+ * is returned so normalization can proceed.
12
+ *
13
+ * Exported for tests; hosts run migrations via `normalizeDocument`.
14
+ */
15
+ export declare function migrateDocument(source: Partial<PMDoc>, fromVersion: number, toVersion?: number): PMDoc;
5
16
  export declare function normalizeDocument(document: Partial<PMDoc> | null | undefined, blocks: Parameters<typeof resolveRegistry>[0], schema?: ContentSchema): PMDoc;
@@ -1,38 +1,133 @@
1
- import { resolveRegistry } from './registry.js';
1
+ import { createSchema, resolveRegistry } from './registry.js';
2
2
  import { normalizeBlockAttributes } from './attributes.js';
3
- export const CURRENT_DOCUMENT_VERSION = 1;
3
+ import { normalizeMeta } from './meta.js';
4
+ import { CURRENT_DOCUMENT_VERSION, runDocumentMigrations } from './migrations.js';
5
+ import { isPlainObject } from '../shared/guards.js';
6
+ export { CURRENT_DOCUMENT_VERSION } from './migrations.js';
7
+ function hasStringType(value) {
8
+ return isPlainObject(value) && typeof value.type === 'string';
9
+ }
4
10
  function normalizeMarks(marks, schema) {
5
- if (!marks)
11
+ if (!Array.isArray(marks))
6
12
  return undefined;
7
- const normalized = marks.filter((mark) => Boolean(mark?.type) && (!schema || schema.allowedMarks.has(mark.type)));
13
+ const normalized = [];
14
+ for (const mark of marks) {
15
+ if (!hasStringType(mark))
16
+ continue;
17
+ if (schema && !schema.allowedMarks.has(mark.type))
18
+ continue;
19
+ const candidate = mark;
20
+ if (candidate.attrs !== undefined && !isPlainObject(candidate.attrs)) {
21
+ const { attrs: _attrs, ...rest } = candidate;
22
+ void _attrs;
23
+ normalized.push(rest);
24
+ continue;
25
+ }
26
+ normalized.push(candidate);
27
+ }
8
28
  return normalized.length ? normalized : undefined;
9
29
  }
30
+ function normalizeContent(content, registryBlocks, schema) {
31
+ if (!Array.isArray(content))
32
+ return undefined;
33
+ const normalized = [];
34
+ for (const child of content) {
35
+ const node = normalizeNode(child, registryBlocks, schema);
36
+ if (node)
37
+ normalized.push(node);
38
+ }
39
+ return normalized;
40
+ }
10
41
  function normalizeNode(node, registryBlocks, schema) {
11
- const block = registryBlocks.get(node.type);
12
- const normalizedContent = Array.isArray(node.content)
13
- ? node.content.map((child) => normalizeNode(child, registryBlocks, schema))
14
- : undefined;
42
+ if (!hasStringType(node)) {
43
+ return undefined;
44
+ }
45
+ const candidate = node;
46
+ // ProseMirror rejects text nodes whose `text` is missing or non-string
47
+ // ("Invalid text node in JSON") and empty-string text nodes ("Empty text
48
+ // nodes are not allowed"); either error makes Tiptap silently replace the
49
+ // entire document with empty content, so drop such nodes here.
50
+ if (candidate.type === 'text' &&
51
+ (typeof candidate.text !== 'string' || candidate.text.length === 0)) {
52
+ return undefined;
53
+ }
54
+ const attrs = isPlainObject(candidate.attrs) ? candidate.attrs : undefined;
55
+ const marks = normalizeMarks(candidate.marks, schema);
56
+ const content = normalizeContent(candidate.content, registryBlocks, schema);
57
+ const block = registryBlocks.get(candidate.type);
15
58
  if (block) {
16
59
  return {
17
- type: node.type,
18
- attrs: normalizeBlockAttributes(block, node.attrs ?? {}),
19
- marks: normalizeMarks(node.marks, schema),
20
- content: block.content ? normalizedContent : undefined
60
+ type: candidate.type,
61
+ attrs: normalizeBlockAttributes(block, attrs ?? {}),
62
+ marks,
63
+ content: block.content ? content : undefined
21
64
  };
22
65
  }
23
66
  return {
24
- ...node,
25
- marks: normalizeMarks(node.marks, schema),
26
- content: normalizedContent
67
+ ...candidate,
68
+ attrs,
69
+ marks,
70
+ content
27
71
  };
28
72
  }
73
+ const NO_REGISTRY_BLOCKS = new Map();
74
+ /**
75
+ * Sanitizes the structural shape of a raw document (object nodes with string
76
+ * types, valid text nodes, array content/marks, object attrs — no schema or
77
+ * block-attribute normalization) and runs the registered migrations on the
78
+ * result, so migration callbacks never receive hostile shapes. A throwing
79
+ * migration never propagates: on throw the sanitized-but-unmigrated document
80
+ * is returned so normalization can proceed.
81
+ *
82
+ * Exported for tests; hosts run migrations via `normalizeDocument`.
83
+ */
84
+ export function migrateDocument(source, fromVersion, toVersion) {
85
+ const sanitized = {
86
+ type: 'doc',
87
+ content: normalizeContent(source.content, NO_REGISTRY_BLOCKS) ?? []
88
+ };
89
+ if (isPlainObject(source.meta)) {
90
+ sanitized.meta = source.meta;
91
+ }
92
+ try {
93
+ return runDocumentMigrations(sanitized, fromVersion, toVersion);
94
+ }
95
+ catch {
96
+ return sanitized;
97
+ }
98
+ }
29
99
  export function normalizeDocument(document, blocks, schema) {
30
100
  const registry = resolveRegistry(blocks);
31
- const registryBlocks = new Map(registry.blocks.map((block) => [block.id, block]));
32
- const content = Array.isArray(document?.content) ? document.content : [];
33
- return {
101
+ const registryBlocks = registry.byId;
102
+ // When the host passes no schema, fall back to the registry's default
103
+ // schema (default allowed-mark set) so arbitrary mark types are still
104
+ // filtered out — unknown marks crash ProseMirror's nodeFromJSON, which
105
+ // makes Tiptap replace the whole document with empty content.
106
+ const effectiveSchema = schema ?? createSchema(registry);
107
+ const source = isPlainObject(document) ? document : {};
108
+ const rawVersion = source.version;
109
+ // Only treat the stored version as meaningful when it is a positive safe
110
+ // integer; hostile or bogus values (negative, zero, fractional, NaN,
111
+ // Infinity, beyond MAX_SAFE_INTEGER) are handled like a missing version.
112
+ // This also keeps attacker-supplied versions from producing huge
113
+ // migration ranges.
114
+ const sourceVersion = typeof rawVersion === 'number' && Number.isSafeInteger(rawVersion) && rawVersion >= 1
115
+ ? rawVersion
116
+ : 1;
117
+ let working = source;
118
+ if (sourceVersion < CURRENT_DOCUMENT_VERSION) {
119
+ working = migrateDocument(source, sourceVersion);
120
+ }
121
+ const metaFields = effectiveSchema.metaFields;
122
+ const normalized = {
34
123
  type: 'doc',
35
- version: CURRENT_DOCUMENT_VERSION,
36
- content: content.map((node) => normalizeNode(node, registryBlocks, schema))
124
+ // Never silently downgrade documents from a newer version; hosts are
125
+ // notified via validateDocument's UNSUPPORTED_VERSION issue.
126
+ version: sourceVersion > CURRENT_DOCUMENT_VERSION ? sourceVersion : CURRENT_DOCUMENT_VERSION,
127
+ content: normalizeContent(working.content, registryBlocks, effectiveSchema) ?? []
37
128
  };
129
+ if (metaFields.size > 0) {
130
+ normalized.meta = normalizeMeta(working.meta, metaFields);
131
+ }
132
+ return normalized;
38
133
  }
@@ -1,4 +1,11 @@
1
1
  import type { BlockDefinition, BlockRegistry, ContentSchema, CreateSchemaOptions } from './types.js';
2
+ /**
3
+ * The default mark universe a schema allows when the host does not pass an
4
+ * explicit `allowedMarks`. This is the single source of truth for the default
5
+ * marks — the editor's base extensions (`shared/tiptap.ts`) consume it too, so
6
+ * the fallback schema and the fallback extension set never drift apart.
7
+ */
8
+ export declare const DEFAULT_MARKS: readonly ["bold", "italic", "strike", "code", "link"];
2
9
  export declare function createBlockRegistry(blocks: BlockDefinition[]): BlockRegistry;
3
10
  export declare function createSchema(registry: BlockRegistry, options?: CreateSchemaOptions): ContentSchema;
4
11
  export declare function resolveRegistry(blocks: BlockRegistry | BlockDefinition[]): BlockRegistry;
@@ -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,13 +38,27 @@ 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);
57
+ const metaFields = new Map(Object.entries(options.metaFields ?? {}));
39
58
  return {
40
59
  allowedBlocks,
41
- allowedMarks
60
+ allowedMarks,
61
+ metaFields
42
62
  };
43
63
  }
44
64
  export function resolveRegistry(blocks) {
@@ -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;
@@ -26,8 +27,15 @@ export interface AttributeSpec<T> {
26
27
  };
27
28
  }
28
29
  export type AttributeConfig<T> = AttributeSpec<T> | T;
30
+ export type MetaFieldSpec<T> = AttributeSpec<T>;
31
+ export type DocumentMetaSchema = Record<string, MetaFieldSpec<unknown>>;
29
32
  export type BlockAttributes = Record<string, unknown>;
30
- 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;
31
39
  export type HtmlSpecValue = string | number | boolean | null | undefined;
32
40
  export type HtmlSpec = [string, Record<string, unknown>?, ...(HtmlSpec | HtmlSpecValue)[]];
33
41
  export type BlockHtmlRenderer = (attrs: BlockAttributes) => HtmlSpec;
@@ -105,8 +113,9 @@ export interface BlockRegistry {
105
113
  export interface ContentSchema {
106
114
  allowedBlocks: ReadonlySet<string>;
107
115
  allowedMarks: ReadonlySet<string>;
116
+ metaFields: ReadonlyMap<string, AttributeSpec<unknown>>;
108
117
  }
109
- export type ValidationCode = 'UNKNOWN_BLOCK' | 'INVALID_ATTR' | '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';
110
119
  export interface ValidationIssue {
111
120
  code: ValidationCode;
112
121
  path: PMPath;
@@ -121,6 +130,7 @@ export interface ValidationResult {
121
130
  export interface CreateSchemaOptions {
122
131
  allowedBlocks?: string[];
123
132
  allowedMarks?: string[];
133
+ metaFields?: DocumentMetaSchema;
124
134
  }
125
135
  export interface ValidateDocumentOptions {
126
136
  onIssue?: (issue: ValidationIssue) => void;
@@ -1,4 +1,7 @@
1
1
  import { resolveRegistry } from './registry.js';
2
+ import { validateMeta } from './meta.js';
3
+ import { pushIssue } from './issues.js';
4
+ import { CURRENT_DOCUMENT_VERSION } from './migrations.js';
2
5
  const BUILTIN_NODE_TYPES = new Set([
3
6
  'doc',
4
7
  'paragraph',
@@ -12,13 +15,18 @@ const BUILTIN_NODE_TYPES = new Set([
12
15
  'orderedList',
13
16
  'listItem'
14
17
  ]);
15
- function pushIssue(issues, options, issue) {
16
- issues.push(issue);
17
- options?.onIssue?.(issue);
18
- }
19
18
  function validateMarks(marks, path, schema, issues, options) {
20
- 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
+ });
21
28
  return;
29
+ }
22
30
  marks.forEach((mark, markIndex) => {
23
31
  if (!mark?.type || typeof mark.type !== 'string') {
24
32
  pushIssue(issues, options, {
@@ -161,6 +169,15 @@ export function validateDocument(document, blocks, schema, options) {
161
169
  });
162
170
  return { ok: false, issues };
163
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
+ }
164
181
  if (document.content && !Array.isArray(document.content)) {
165
182
  pushIssue(issues, options, {
166
183
  code: 'MALFORMED_NODE',
@@ -170,7 +187,8 @@ export function validateDocument(document, blocks, schema, options) {
170
187
  });
171
188
  return { ok: false, issues };
172
189
  }
173
- const registryBlocks = new Map(registry.blocks.map((block) => [block.id, block]));
190
+ validateMeta(document.meta, schema.metaFields, issues, options);
191
+ const registryBlocks = registry.byId;
174
192
  document.content?.forEach((node, index) => {
175
193
  validateNode(node, ['content', index], registryBlocks, schema, issues, options);
176
194
  });
@@ -0,0 +1,141 @@
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
+
8
+ <script lang="ts">
9
+ import { inferAttributeInputKind, normalizeAttributeOptions } from '../core/attributes.js';
10
+ import type { AttributeSpec } from '../core/types.js';
11
+ import RichTextAttributeEditor from './RichTextAttributeEditor.svelte';
12
+
13
+ interface Props {
14
+ name: string;
15
+ spec: AttributeSpec<unknown>;
16
+ value?: unknown;
17
+ error?: string;
18
+ onChange: (value: unknown) => void;
19
+ onCustom?: (name: string, inputKind: string) => void;
20
+ }
21
+
22
+ let { name, spec, value = undefined, error = '', onChange, onCustom }: Props = $props();
23
+
24
+ const fieldId = `uncial-field-${nextFieldId++}`;
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');
30
+ const options = $derived(normalizeAttributeOptions(spec) ?? []);
31
+ const stringValue = $derived.by(() => {
32
+ if (typeof value === 'string') return value;
33
+ if (value === undefined || value === null) return '';
34
+ return String(value);
35
+ });
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
+ });
45
+
46
+ function isBuiltInInputKind(kind: string): boolean {
47
+ return ['checkbox', 'number', 'richtext', 'select', 'textarea', 'json', 'text', 'hidden'].includes(
48
+ kind
49
+ );
50
+ }
51
+ </script>
52
+
53
+ {#if inputKind !== 'hidden'}
54
+ <div class="uncial-field">
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}
60
+ {#if !isBuiltInInputKind(inputKind)}
61
+ <button
62
+ type="button"
63
+ class="uncial-btn uncial-btn--outline uncial-btn--sm uncial-btn--start"
64
+ onclick={() => onCustom?.(name, inputKind)}
65
+ >
66
+ {customLabel}
67
+ </button>
68
+ {:else if inputKind === 'checkbox'}
69
+ <input
70
+ id={fieldId}
71
+ class="uncial-checkbox uncial-checkbox--sm"
72
+ type="checkbox"
73
+ checked={Boolean(value)}
74
+ onchange={(event) => {
75
+ const target = event.currentTarget as HTMLInputElement;
76
+ onChange(target.checked);
77
+ }}
78
+ />
79
+ {:else if inputKind === 'number'}
80
+ <input
81
+ id={fieldId}
82
+ class="uncial-input uncial-input--sm"
83
+ type="number"
84
+ placeholder={spec.placeholder ?? name}
85
+ value={value ?? ''}
86
+ oninput={(event) => {
87
+ const target = event.currentTarget as HTMLInputElement;
88
+ onChange(target.value === '' ? '' : target.valueAsNumber);
89
+ }}
90
+ />
91
+ {:else if inputKind === 'richtext'}
92
+ <RichTextAttributeEditor
93
+ {value}
94
+ features={spec.richText?.features}
95
+ placeholder={spec.richText?.placeholder ?? spec.placeholder ?? name}
96
+ {onChange}
97
+ />
98
+ {:else if inputKind === 'select'}
99
+ <select
100
+ id={fieldId}
101
+ class="uncial-select uncial-select--sm"
102
+ value={stringValue}
103
+ onchange={(event) => {
104
+ const target = event.currentTarget as HTMLSelectElement;
105
+ onChange(target.value);
106
+ }}
107
+ >
108
+ {#each selectOptions as option (String(option.value))}
109
+ <option value={String(option.value)}>{option.label ?? String(option.value)}</option>
110
+ {/each}
111
+ </select>
112
+ {:else if inputKind === 'textarea' || inputKind === 'json'}
113
+ <textarea
114
+ id={fieldId}
115
+ class="uncial-textarea uncial-textarea--tall"
116
+ placeholder={spec.placeholder ?? name}
117
+ spellcheck={inputKind !== 'json'}
118
+ value={stringValue}
119
+ oninput={(event) => {
120
+ const target = event.currentTarget as HTMLTextAreaElement;
121
+ onChange(target.value);
122
+ }}
123
+ ></textarea>
124
+ {:else}
125
+ <input
126
+ id={fieldId}
127
+ class="uncial-input uncial-input--sm"
128
+ type="text"
129
+ placeholder={spec.placeholder ?? name}
130
+ value={stringValue}
131
+ oninput={(event) => {
132
+ const target = event.currentTarget as HTMLInputElement;
133
+ onChange(target.value);
134
+ }}
135
+ />
136
+ {/if}
137
+ {#if error}
138
+ <span class="uncial-field__error">{error}</span>
139
+ {/if}
140
+ </div>
141
+ {/if}
@@ -0,0 +1,12 @@
1
+ import type { AttributeSpec } from '../core/types.js';
2
+ interface Props {
3
+ name: string;
4
+ spec: AttributeSpec<unknown>;
5
+ value?: unknown;
6
+ error?: string;
7
+ onChange: (value: unknown) => void;
8
+ onCustom?: (name: string, inputKind: string) => void;
9
+ }
10
+ declare const AttributeFieldControl: import("svelte").Component<Props, {}, "">;
11
+ type AttributeFieldControl = ReturnType<typeof AttributeFieldControl>;
12
+ export default AttributeFieldControl;