uncial 4.0.0 → 5.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.
@@ -8,4 +8,4 @@ export { normalizeDocument } from './normalize.js';
8
8
  export { validateDocument } from './validate.js';
9
9
  export type { BlockEditorMountHandle, BlockEditorMountOptions, BlockRuntimePlugin, NormalizedBlockComponentDefinition } from './runtime.js';
10
10
  export { coerceRichTextDocument, emptyRichTextDocument, hasRichTextContent, isRichTextDocument, richTextDocument, resolveRichTextFeatures } from '../shared/richText.js';
11
- export type { AttributeConfig, AttributeInputKind, AttributeOption, AttrParser, AttrSerializer, AttributeSpec, BlockAttributes, BlockBehavior, BlockComponentProps, BlockConfig, BlockContentDefinition, BlockContentKind, BlockDefinition, BlockIcon, BlockMetadata, BlockRegistry, ContentDocument, ContentSchema, CreateSchemaOptions, DocumentMetaSchema, MarkComponentProps, MarkDefinition, MarkRegistry, MetaFieldSpec, RichTextFeature, RichTextFeatureSelection, RuntimeBlockConfig, ValidateDocumentOptions, ValidationCode, ValidationIssue, ValidationResult } from './types.js';
11
+ export type { AttributeConfig, AttributeInputKind, AttributeOption, AttrParser, AttrSerializer, AttributeSpec, BlockAttributes, BlockBehavior, BlockComponentProps, BlockConfig, BlockContentDefinition, BlockContentKind, BlockDefinition, BlockIcon, BlockMetadata, BlockRegistry, ContentDocument, ContentSchema, CreateSchemaOptions, DocumentMetaSchema, MarkComponentProps, MarkDefinition, MarkRegistry, MetaFieldSpec, MetaValues, RichTextFeature, RichTextFeatureSelection, RuntimeBlockConfig, ValidateDocumentOptions, ValidationCode, ValidationIssue, ValidationResult } from './types.js';
package/dist/core/meta.js CHANGED
@@ -1,4 +1,4 @@
1
- import { coerceAttributeValue, serializeAttributeValue, toAttributeDraftValue } from './attributes.js';
1
+ import { attributeListFields, attributeListValueSpec, coerceAttributeValue, serializeAttributeValue, toAttributeDraftValue } from './attributes.js';
2
2
  import { pushIssue } from './issues.js';
3
3
  import { isPlainObject as isRecord } from '../shared/guards.js';
4
4
  export function normalizeMeta(meta, metaFields) {
@@ -28,29 +28,51 @@ export function validateMeta(meta, metaFields, issues, options, path = ['meta'])
28
28
  });
29
29
  }
30
30
  }
31
- for (const [name, spec] of metaFields) {
32
- const value = source[name];
33
- const missing = value === undefined || value === null || value === '';
34
- if (missing && spec.required) {
31
+ function validateValue(spec, value, label, valuePath) {
32
+ if (spec.validate && !spec.validate(value)) {
35
33
  pushIssue(issues, options, {
36
34
  code: 'INVALID_META',
37
- path: [...path, name],
38
- message: `Required metadata field "${name}" is missing`,
39
- severity: 'error'
35
+ path: valuePath,
36
+ message: `Metadata field "${label}" is invalid`,
37
+ severity: 'error',
38
+ details: { value }
40
39
  });
41
- continue;
42
40
  }
43
- if (missing)
44
- continue;
45
- if (spec.validate && !spec.validate(value)) {
41
+ if (!spec.list || !Array.isArray(value))
42
+ return;
43
+ const valueSpec = attributeListValueSpec(spec.list);
44
+ const fields = attributeListFields(spec.list);
45
+ value.forEach((item, index) => {
46
+ if (valueSpec) {
47
+ validateValue(valueSpec, item, `${label}.${index}`, [...valuePath, index]);
48
+ return;
49
+ }
50
+ const record = isRecord(item) ? item : {};
51
+ for (const [name, fieldSpec] of fields) {
52
+ validateField(fieldSpec, record[name], `${label}.${index}.${name}`, [
53
+ ...valuePath,
54
+ index,
55
+ name
56
+ ]);
57
+ }
58
+ });
59
+ }
60
+ function validateField(spec, value, label, fieldPath) {
61
+ const missing = value === undefined || value === null || value === '';
62
+ if (missing && spec.required) {
46
63
  pushIssue(issues, options, {
47
64
  code: 'INVALID_META',
48
- path: [...path, name],
49
- message: `Metadata field "${name}" is invalid`,
50
- severity: 'error',
51
- details: { value }
65
+ path: fieldPath,
66
+ message: `Required metadata field "${label}" is missing`,
67
+ severity: 'error'
52
68
  });
69
+ return;
53
70
  }
71
+ if (!missing)
72
+ validateValue(spec, value, label, fieldPath);
73
+ }
74
+ for (const [name, spec] of metaFields) {
75
+ validateField(spec, source[name], name, [...path, name]);
54
76
  }
55
77
  }
56
78
  export function toMetaDraftValues(metaFields, meta = {}) {
@@ -1,4 +1,4 @@
1
- import type { BlockDefinition, BlockRegistry, ContentSchema, CreateSchemaOptions, MarkDefinition, MarkRegistry } from './types.js';
1
+ import type { BlockDefinition, BlockRegistry, ContentSchema, CreateSchemaOptions, DocumentMetaSchema, MarkDefinition, MarkRegistry, MetaValues } from './types.js';
2
2
  /**
3
3
  * The default mark universe a schema allows when the host does not pass an
4
4
  * explicit `allowedMarks`. This is the single source of truth for the default
@@ -13,6 +13,6 @@ export declare function createBlockRegistry(blocks: BlockDefinition[]): BlockReg
13
13
  * through normalization, and permitting one does not give it a wrapper element.
14
14
  */
15
15
  export declare function createMarkRegistry(marks: MarkDefinition[]): MarkRegistry;
16
- export declare function createSchema(registry: BlockRegistry, options?: CreateSchemaOptions): ContentSchema;
16
+ export declare function createSchema<Fields extends DocumentMetaSchema = DocumentMetaSchema>(registry: BlockRegistry, options?: CreateSchemaOptions<Fields>): ContentSchema<MetaValues<Fields>>;
17
17
  export declare function resolveRegistry(blocks: BlockRegistry | BlockDefinition[]): BlockRegistry;
18
18
  export declare function resolveMarkRegistry(marks: MarkRegistry | MarkDefinition[]): MarkRegistry;
@@ -92,6 +92,12 @@ export function createSchema(registry, options = {}) {
92
92
  }
93
93
  const allowedMarks = new Set(options.allowedMarks ?? DEFAULT_MARKS);
94
94
  const metaFields = new Map(Object.entries(options.metaFields ?? {}));
95
+ for (const [name, spec] of metaFields) {
96
+ if (spec.list && !spec.list.fields && spec.list.value === undefined) {
97
+ throw new Error(`Metadata field "${name}" declares "list" but neither ` +
98
+ `"list.fields" nor "list.value", so the editor has no item shape to render.`);
99
+ }
100
+ }
95
101
  return {
96
102
  allowedBlocks,
97
103
  allowedMarks,
@@ -4,7 +4,7 @@ import type { NormalizedBlockComponentDefinition } from './runtime.js';
4
4
  export type AttrValidator<T> = (value: unknown) => value is T;
5
5
  export type AttrParser<T> = (value: unknown) => T | undefined;
6
6
  export type AttrSerializer = (value: unknown) => unknown;
7
- export type AttributeInputKind = 'text' | 'textarea' | 'number' | 'checkbox' | 'json' | 'list' | 'richtext' | 'select' | 'hidden' | 'image' | (string & {});
7
+ export type AttributeInputKind = 'text' | 'textarea' | 'number' | 'date' | 'datetime' | 'checkbox' | 'json' | 'list' | 'richtext' | 'select' | 'hidden' | 'image' | (string & {});
8
8
  export interface AttributeOption<T> {
9
9
  value: T;
10
10
  label?: string;
@@ -16,7 +16,7 @@ export type RichTextFeatureSelection = '*' | '__all__' | RichTextFeature[];
16
16
  * The shape of one item in a list-valued attribute, which the editor renders as
17
17
  * a stack of real fields with add/remove/reorder instead of raw JSON. Declare
18
18
  * `fields` for items that are records and `value` for items that are single
19
- * values; `defineBlock` rejects a list that declares neither.
19
+ * values; `defineBlock` and `createSchema` reject a list that declares neither.
20
20
  */
21
21
  export interface AttributeListSpec {
22
22
  fields?: Record<string, AttributeConfig<unknown>>;
@@ -32,6 +32,10 @@ export interface AttributeSpec<T> {
32
32
  serialize?: AttrSerializer;
33
33
  input?: AttributeInputKind;
34
34
  placeholder?: string;
35
+ /** Advice shown under the field for a value that is valid but unwise; it never blocks a save. */
36
+ warn?: (value: unknown) => string | null | undefined;
37
+ /** IANA zone in which a `datetime` input shows and writes its wall clock; the browser's own by default. */
38
+ timeZone?: string;
35
39
  options?: ReadonlyArray<T | AttributeOption<T>>;
36
40
  /** Item shape for an array-valued attribute; implies `input: 'list'`. */
37
41
  list?: AttributeListSpec;
@@ -43,6 +47,9 @@ export interface AttributeSpec<T> {
43
47
  export type AttributeConfig<T> = AttributeSpec<T> | T;
44
48
  export type MetaFieldSpec<T> = AttributeSpec<T>;
45
49
  export type DocumentMetaSchema = Record<string, MetaFieldSpec<unknown>>;
50
+ export type MetaValues<Fields extends DocumentMetaSchema> = {
51
+ [Name in keyof Fields]: Fields[Name]['default'];
52
+ };
46
53
  export type BlockAttributes = Record<string, unknown>;
47
54
  /**
48
55
  * A block's icon for editor UI (toolbar / insert menu). Either an icon name or
@@ -152,10 +159,13 @@ export interface MarkRegistry {
152
159
  get(id: string): MarkDefinition | undefined;
153
160
  has(id: string): boolean;
154
161
  }
155
- export interface ContentSchema {
162
+ declare const metaValues: unique symbol;
163
+ export interface ContentSchema<Meta extends Record<string, unknown> = Record<string, unknown>> {
156
164
  allowedBlocks: ReadonlySet<string>;
157
165
  allowedMarks: ReadonlySet<string>;
158
166
  metaFields: ReadonlyMap<string, AttributeSpec<unknown>>;
167
+ /** Never set: carries the meta type `createSchema` infers from `metaFields`. */
168
+ readonly [metaValues]?: Meta;
159
169
  }
160
170
  export type ValidationCode = 'UNKNOWN_BLOCK' | 'INVALID_ATTR' | 'INVALID_META' | 'UNKNOWN_META' | 'INVALID_CONTENT' | 'DISALLOWED_BLOCK' | 'DISALLOWED_MARK' | 'MALFORMED_NODE' | 'UNSUPPORTED_VERSION';
161
171
  export interface ValidationIssue {
@@ -169,10 +179,10 @@ export interface ValidationResult {
169
179
  ok: boolean;
170
180
  issues: ValidationIssue[];
171
181
  }
172
- export interface CreateSchemaOptions {
182
+ export interface CreateSchemaOptions<Fields extends DocumentMetaSchema = DocumentMetaSchema> {
173
183
  allowedBlocks?: string[];
174
184
  allowedMarks?: string[];
175
- metaFields?: DocumentMetaSchema;
185
+ metaFields?: Fields;
176
186
  }
177
187
  export interface ValidateDocumentOptions {
178
188
  onIssue?: (issue: ValidationIssue) => void;
@@ -186,3 +196,4 @@ export interface EditorOptions {
186
196
  onIssue?: (issue: ValidationIssue) => void;
187
197
  }
188
198
  export type ContentDocument = PMDoc;
199
+ export {};
@@ -22,6 +22,7 @@
22
22
  import PlusIcon from 'phosphor-svelte/lib/PlusIcon';
23
23
  import TrashIcon from 'phosphor-svelte/lib/TrashIcon';
24
24
  import ImagePicker from './ImagePicker.svelte';
25
+ import { fromWallClock, toWallClock } from './zonedDateTime.js';
25
26
  import RichTextAttributeEditor from './RichTextAttributeEditor.svelte';
26
27
  // A list item's fields are ordinary attributes, edited by this same control.
27
28
  import AttributeFieldControl from './AttributeFieldControl.svelte';
@@ -31,6 +32,8 @@
31
32
  spec: AttributeSpec<unknown>;
32
33
  value?: unknown;
33
34
  error?: string;
35
+ path?: string;
36
+ errors?: Record<string, string>;
34
37
  onChange: (value: unknown) => void;
35
38
  onCustom?: (name: string, inputKind: string) => void;
36
39
  imageSource?: ImageSource;
@@ -42,6 +45,8 @@
42
45
  spec,
43
46
  value = undefined,
44
47
  error = '',
48
+ path,
49
+ errors = {},
45
50
  onChange,
46
51
  onCustom,
47
52
  imageSource,
@@ -60,6 +65,7 @@
60
65
  inputKind !== 'image'
61
66
  );
62
67
  const options = $derived(normalizeAttributeOptions(spec) ?? []);
68
+ const warning = $derived(spec.warn?.(value) ?? '');
63
69
  const stringValue = $derived.by(() => {
64
70
  if (typeof value === 'string') return value;
65
71
  if (value === undefined || value === null) return '';
@@ -80,6 +86,7 @@
80
86
  const listValueSpec = $derived(attributeListValueSpec(list));
81
87
  const itemLabel = $derived(list.itemLabel ?? 'item');
82
88
  const items = $derived(Array.isArray(value) ? (value as unknown[]) : []);
89
+ const fieldPath = $derived(path ?? name);
83
90
 
84
91
  let fileInput = $state<HTMLInputElement>();
85
92
  let picker = $state<ImagePicker>();
@@ -119,6 +126,8 @@
119
126
  return [
120
127
  'checkbox',
121
128
  'number',
129
+ 'date',
130
+ 'datetime',
122
131
  'richtext',
123
132
  'select',
124
133
  'textarea',
@@ -194,6 +203,28 @@
194
203
  onChange(target.value === '' ? '' : target.valueAsNumber);
195
204
  }}
196
205
  />
206
+ {:else if inputKind === 'date'}
207
+ <input
208
+ id={fieldId}
209
+ class="uncial-input uncial-input--sm"
210
+ type="date"
211
+ value={stringValue}
212
+ onchange={(event) => {
213
+ const target = event.currentTarget as HTMLInputElement;
214
+ onChange(target.value);
215
+ }}
216
+ />
217
+ {:else if inputKind === 'datetime'}
218
+ <input
219
+ id={fieldId}
220
+ class="uncial-input uncial-input--sm"
221
+ type="datetime-local"
222
+ value={toWallClock(stringValue, spec.timeZone)}
223
+ onchange={(event) => {
224
+ const target = event.currentTarget as HTMLInputElement;
225
+ onChange(fromWallClock(target.value, spec.timeZone));
226
+ }}
227
+ />
197
228
  {:else if inputKind === 'richtext'}
198
229
  <RichTextAttributeEditor
199
230
  {value}
@@ -218,6 +249,7 @@
218
249
  {:else if inputKind === 'list'}
219
250
  <div class="uncial-list-field">
220
251
  {#each items as item, index (index)}
252
+ {@const itemPath = `${fieldPath}.${index}`}
221
253
  <div class="uncial-list-item">
222
254
  <div class="uncial-list-item__head">
223
255
  <span class="uncial-section-label">{itemLabel} {index + 1}</span>
@@ -229,7 +261,7 @@
229
261
  disabled={index === 0}
230
262
  onclick={() => moveItem(index, index - 1)}
231
263
  >
232
- <ArrowUpIcon size={12} weight="bold" />
264
+ <ArrowUpIcon size={12} weight="bold" aria-hidden="true" />
233
265
  </button>
234
266
  <button
235
267
  type="button"
@@ -238,7 +270,7 @@
238
270
  disabled={index === items.length - 1}
239
271
  onclick={() => moveItem(index, index + 1)}
240
272
  >
241
- <ArrowDownIcon size={12} weight="bold" />
273
+ <ArrowDownIcon size={12} weight="bold" aria-hidden="true" />
242
274
  </button>
243
275
  <button
244
276
  type="button"
@@ -246,7 +278,7 @@
246
278
  aria-label={`Remove ${itemLabel}`}
247
279
  onclick={() => removeItem(index)}
248
280
  >
249
- <TrashIcon size={12} weight="bold" />
281
+ <TrashIcon size={12} weight="bold" aria-hidden="true" />
250
282
  </button>
251
283
  </div>
252
284
  </div>
@@ -255,6 +287,9 @@
255
287
  name={itemLabel}
256
288
  spec={listValueSpec}
257
289
  value={item}
290
+ path={itemPath}
291
+ error={errors[itemPath]}
292
+ {errors}
258
293
  onChange={(next) => replaceItem(index, next)}
259
294
  {onCustom}
260
295
  {imageSource}
@@ -262,10 +297,14 @@
262
297
  />
263
298
  {:else}
264
299
  {#each listFields as [fieldName, fieldSpec] (fieldName)}
300
+ {@const subPath = `${itemPath}.${fieldName}`}
265
301
  <AttributeFieldControl
266
302
  name={fieldName}
267
303
  spec={fieldSpec}
268
304
  value={(item as Record<string, unknown>)?.[fieldName]}
305
+ path={subPath}
306
+ error={errors[subPath]}
307
+ {errors}
269
308
  onChange={(next) => setItemField(index, fieldName, next)}
270
309
  {onCustom}
271
310
  {imageSource}
@@ -282,7 +321,7 @@
282
321
  class="uncial-btn uncial-btn--primary uncial-btn--xs uncial-btn--start"
283
322
  onclick={addItem}
284
323
  >
285
- <PlusIcon size={12} weight="bold" />
324
+ <PlusIcon size={12} weight="bold" aria-hidden="true" />
286
325
  <span>Add {itemLabel}</span>
287
326
  </button>
288
327
  </div>
@@ -378,6 +417,9 @@
378
417
  }}
379
418
  />
380
419
  {/if}
420
+ {#if warning}
421
+ <span class="uncial-field__warning" role="status">{warning}</span>
422
+ {/if}
381
423
  {#if error}
382
424
  <span class="uncial-field__error">{error}</span>
383
425
  {/if}
@@ -7,6 +7,8 @@ interface Props {
7
7
  spec: AttributeSpec<unknown>;
8
8
  value?: unknown;
9
9
  error?: string;
10
+ path?: string;
11
+ errors?: Record<string, string>;
10
12
  onChange: (value: unknown) => void;
11
13
  onCustom?: (name: string, inputKind: string) => void;
12
14
  imageSource?: ImageSource;
@@ -1,15 +1,19 @@
1
1
  <script lang="ts">
2
2
  import type { AttributeSpec } from '../core/types.js';
3
+ import type { ImagePreviews } from '../shared/imagePreviews.js';
3
4
  import AttributeFieldControl from './AttributeFieldControl.svelte';
5
+ import type { ImageSource } from './imageSource.js';
4
6
  import type { DocumentMetaController, DocumentMetaState } from './metaController.js';
5
7
 
6
8
  interface Props {
7
9
  controller: DocumentMetaController;
8
10
  fields?: ReadonlyMap<string, AttributeSpec<unknown>>;
9
11
  onCommit?: (meta: Record<string, unknown>) => void;
12
+ imageSource?: ImageSource;
13
+ imagePreviews?: ImagePreviews;
10
14
  }
11
15
 
12
- let { controller, fields = new Map(), onCommit }: Props = $props();
16
+ let { controller, fields = new Map(), onCommit, imageSource, imagePreviews }: Props = $props();
13
17
 
14
18
  let controllerState = $state<DocumentMetaState>({
15
19
  draft: {},
@@ -46,7 +50,10 @@
46
50
  {spec}
47
51
  value={controllerState.draft[name]}
48
52
  error={controllerState.errors[name]}
53
+ errors={controllerState.errors}
49
54
  onChange={(value) => controller.setDraft(name, value)}
55
+ {imageSource}
56
+ {imagePreviews}
50
57
  />
51
58
  {:else}
52
59
  <p class="uncial-help-text">No metadata fields configured.</p>
@@ -1,9 +1,13 @@
1
1
  import type { AttributeSpec } from '../core/types.js';
2
+ import type { ImagePreviews } from '../shared/imagePreviews.js';
3
+ import type { ImageSource } from './imageSource.js';
2
4
  import type { DocumentMetaController } from './metaController.js';
3
5
  interface Props {
4
6
  controller: DocumentMetaController;
5
7
  fields?: ReadonlyMap<string, AttributeSpec<unknown>>;
6
8
  onCommit?: (meta: Record<string, unknown>) => void;
9
+ imageSource?: ImageSource;
10
+ imagePreviews?: ImagePreviews;
7
11
  }
8
12
  declare const DocumentMetaPanel: import("svelte").Component<Props, {}, "">;
9
13
  type DocumentMetaPanel = ReturnType<typeof DocumentMetaPanel>;
@@ -27,10 +27,11 @@
27
27
  } from './metaController.js';
28
28
  import BlockAttributesPanel from './BlockAttributesPanel.svelte';
29
29
  import DocumentMetaPanel from './DocumentMetaPanel.svelte';
30
+ import { dropdownFloat } from './dropdownFloat.js';
30
31
  import Toolbar from './Toolbar.svelte';
31
32
  import type { ChooseAttributeRequest } from './chooseAttribute.js';
32
33
  import type { ImageSource } from './imageSource.js';
33
- import { createImagePreviews } from '../shared/imagePreviews.js';
34
+ import { createImagePreviews, missingImagePlaceholder } from '../shared/imagePreviews.js';
34
35
  import { dropdownDismiss } from './dropdownDismiss.js';
35
36
  import type { ToolbarFeature, ToolbarFeatureSelection } from './toolbarFeatures.js';
36
37
 
@@ -115,7 +116,9 @@
115
116
  const internalController = createBlockAttributesController();
116
117
  const internalMetaController = createDocumentMetaController();
117
118
  // Per instance: two editors on one page must not see each other's uploads.
118
- const imagePreviews = createImagePreviews();
119
+ const imagePreviews = createImagePreviews((src) =>
120
+ imageSource?.missing?.(src) ? missingImagePlaceholder(src) : undefined
121
+ );
119
122
  let metaState = $state<DocumentMetaState>({
120
123
  draft: {},
121
124
  errors: {},
@@ -384,7 +387,7 @@
384
387
  {#if hasMetaFields || activeBlocks.length > 0}
385
388
  <div class="uncial-toolbar__actions">
386
389
  {#if hasMetaFields}
387
- <details class="uncial-dropdown uncial-dropdown--end" use:dropdownDismiss>
390
+ <details class="uncial-dropdown uncial-dropdown--end" use:dropdownDismiss use:dropdownFloat>
388
391
  <summary
389
392
  bind:this={metaTriggerEl}
390
393
  aria-label="Edit document metadata"
@@ -398,6 +401,8 @@
398
401
  controller={documentMetaController}
399
402
  fields={resolvedMetaFields}
400
403
  onCommit={commitMeta}
404
+ {imageSource}
405
+ {imagePreviews}
401
406
  />
402
407
  </div>
403
408
  </details>
@@ -9,4 +9,6 @@ export interface ImageSource {
9
9
  browse?: () => Promise<string[]>;
10
10
  /** A displayable URL for a stored value; identity when absent. */
11
11
  thumbnail?: (src: string) => string;
12
+ /** Whether a stored value names an image that no longer exists; the canvas shows a placeholder for it. */
13
+ missing?: (src: string) => boolean;
12
14
  }
@@ -5,7 +5,7 @@ function errorsFromIssues(issues) {
5
5
  for (const issue of issues) {
6
6
  if (issue.severity !== 'error')
7
7
  continue;
8
- const field = issue.path[0] === 'meta' ? String(issue.path[1] ?? '') : '';
8
+ const field = issue.path[0] === 'meta' ? issue.path.slice(1).join('.') : '';
9
9
  if (field)
10
10
  errors[field] = issue.message;
11
11
  }
@@ -28,7 +28,10 @@ export function createDocumentMetaController(fields = new Map(), meta = {}) {
28
28
  state.update((current) => ({
29
29
  ...current,
30
30
  draft: { ...current.draft, [name]: value },
31
- errors: { ...current.errors, [name]: '' },
31
+ errors: Object.fromEntries(Object.entries({ ...current.errors, [name]: '' }).map(([key, message]) => [
32
+ key,
33
+ key.startsWith(`${name}.`) ? '' : message
34
+ ])),
32
35
  dirty: true
33
36
  }));
34
37
  },
@@ -0,0 +1,4 @@
1
+ /** The wall-clock `YYYY-MM-DDTHH:mm` of an ISO instant in `timeZone`, or '' if it is not one. */
2
+ export declare function toWallClock(iso: string, timeZone?: string): string;
3
+ /** The ISO instant, with `timeZone`'s offset, of a `YYYY-MM-DDTHH:mm` wall clock there. */
4
+ export declare function fromWallClock(wallClock: string, timeZone?: string): string;
@@ -0,0 +1,38 @@
1
+ function offsetMinutes(instant, timeZone) {
2
+ const parts = Object.fromEntries(new Intl.DateTimeFormat('en-US', {
3
+ timeZone,
4
+ hourCycle: 'h23',
5
+ year: 'numeric',
6
+ month: '2-digit',
7
+ day: '2-digit',
8
+ hour: '2-digit',
9
+ minute: '2-digit',
10
+ second: '2-digit'
11
+ })
12
+ .formatToParts(instant)
13
+ .map(({ type, value }) => [type, Number(value)]));
14
+ const wall = Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour, parts.minute, parts.second);
15
+ return Math.round((wall - Math.floor(instant / 1000) * 1000) / 60_000);
16
+ }
17
+ function pad(n) {
18
+ return String(n).padStart(2, '0');
19
+ }
20
+ /** The wall-clock `YYYY-MM-DDTHH:mm` of an ISO instant in `timeZone`, or '' if it is not one. */
21
+ export function toWallClock(iso, timeZone) {
22
+ const instant = Date.parse(iso);
23
+ if (!iso || Number.isNaN(instant))
24
+ return '';
25
+ return new Date(instant + offsetMinutes(instant, timeZone) * 60_000).toISOString().slice(0, 16);
26
+ }
27
+ /** The ISO instant, with `timeZone`'s offset, of a `YYYY-MM-DDTHH:mm` wall clock there. */
28
+ export function fromWallClock(wallClock, timeZone) {
29
+ const wall = Date.parse(`${wallClock}Z`);
30
+ if (!wallClock || Number.isNaN(wall))
31
+ return '';
32
+ let instant = wall - offsetMinutes(wall, timeZone) * 60_000;
33
+ instant = wall - offsetMinutes(instant, timeZone) * 60_000;
34
+ const offset = offsetMinutes(instant, timeZone);
35
+ const sign = offset < 0 ? '-' : '+';
36
+ const zone = `${sign}${pad(Math.floor(Math.abs(offset) / 60))}:${pad(Math.abs(offset) % 60)}`;
37
+ return `${toWallClock(new Date(instant).toISOString(), timeZone)}:00${zone}`;
38
+ }
@@ -11,7 +11,10 @@ export interface ImagePreviews {
11
11
  register(src: string, file: Blob): void;
12
12
  revokeAll(): void;
13
13
  }
14
- export declare function createImagePreviews(): ImagePreviews;
14
+ /** Unique per value, so {@link ImagePreviews.sourceOf} can map a placeholder back. */
15
+ export declare function missingImagePlaceholder(src: string): string;
16
+ /** `placeholder` answers a stand-in URL for a value with no preview, e.g. a missing image. */
17
+ export declare function createImagePreviews(placeholder?: (src: string) => string | undefined): ImagePreviews;
15
18
  /** The attrs a Block component renders on the canvas, with previews in place of image values. */
16
19
  export declare function withImagePreviews(block: BlockDefinition, attrs: Record<string, unknown>, previews: ImagePreviews): Record<string, unknown>;
17
20
  /**
@@ -1,9 +1,25 @@
1
1
  import { attributeListFields, attributeListValueSpec, inferAttributeInputKind } from '../core/attributes.js';
2
- export function createImagePreviews() {
2
+ const MISSING_IMAGE_SVG = `<svg xmlns="http://www.w3.org/2000/svg" width="320" height="200" viewBox="0 0 320 200"><rect width="320" height="200" fill="#f4f4f5" stroke="#d4d4d8" stroke-dasharray="6 4"/><text x="160" y="106" font-family="system-ui, sans-serif" font-size="16" fill="#71717a" text-anchor="middle">Missing image</text></svg>`;
3
+ /** Unique per value, so {@link ImagePreviews.sourceOf} can map a placeholder back. */
4
+ export function missingImagePlaceholder(src) {
5
+ return `data:image/svg+xml,${encodeURIComponent(MISSING_IMAGE_SVG)}#${encodeURIComponent(src)}`;
6
+ }
7
+ /** `placeholder` answers a stand-in URL for a value with no preview, e.g. a missing image. */
8
+ export function createImagePreviews(placeholder = () => undefined) {
3
9
  const previews = new Map();
4
10
  const sources = new Map();
5
11
  return {
6
- get: (src) => previews.get(src),
12
+ get(src) {
13
+ const known = previews.get(src);
14
+ if (known)
15
+ return known;
16
+ const url = placeholder(src);
17
+ if (url) {
18
+ previews.set(src, url);
19
+ sources.set(url, src);
20
+ }
21
+ return url;
22
+ },
7
23
  sourceOf: (url) => sources.get(url),
8
24
  register(src, file) {
9
25
  // A re-upload answers the same src, so nothing re-renders and the canvas
@@ -13,7 +29,10 @@ export function createImagePreviews() {
13
29
  previews.set(src, url);
14
30
  },
15
31
  revokeAll() {
16
- sources.forEach((_src, url) => URL.revokeObjectURL(url));
32
+ sources.forEach((_src, url) => {
33
+ if (url.startsWith('blob:'))
34
+ URL.revokeObjectURL(url);
35
+ });
17
36
  sources.clear();
18
37
  previews.clear();
19
38
  }
@@ -135,10 +135,15 @@
135
135
  color: var(--uncial-color-text-muted);
136
136
  }
137
137
 
138
- .uncial-field__error {
138
+ .uncial-field__error,
139
+ .uncial-field__warning {
139
140
  font-size: 0.75rem;
140
141
  }
141
142
 
143
+ .uncial-field__warning {
144
+ color: var(--uncial-color-accent);
145
+ }
146
+
142
147
  .uncial-input,
143
148
  .uncial-select,
144
149
  .uncial-textarea {
@@ -97,4 +97,4 @@ declare class UncialRendererElement extends UncialElement<RendererHostProps> {
97
97
  set schema(value: RendererProps['schema']);
98
98
  protected mountComponent(target: ShadowRoot): Record<string, unknown>;
99
99
  }
100
- export { UncialEditor, UncialEditorElement, UncialRenderer, UncialRendererElement };
100
+ export { UncialEditor, UncialEditorElement, UncialElement, UncialRenderer, UncialRendererElement };
@@ -194,4 +194,4 @@ if (typeof customElements !== 'undefined') {
194
194
  customElements.define('uncial-renderer', UncialRendererElement);
195
195
  }
196
196
  }
197
- export { UncialEditor, UncialEditorElement, UncialRenderer, UncialRendererElement };
197
+ export { UncialEditor, UncialEditorElement, UncialElement, UncialRenderer, UncialRendererElement };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "uncial",
3
- "version": "4.0.0",
3
+ "version": "5.1.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",