@widgetic/editor 4.1.22 → 4.1.24

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 (31) hide show
  1. package/README.md +43 -0
  2. package/dist/components/editors/CompositionEditorApp.svelte +228 -206
  3. package/dist/components/editors/EmbedAssistantPanel.svelte +270 -48
  4. package/dist/components/ic/AngleInputController.svelte +18 -3
  5. package/dist/components/ic/ColorPickerInputController.svelte +81 -49
  6. package/dist/components/ic/DatePickerInputController.svelte +134 -74
  7. package/dist/components/ic/DatePickerInputController.svelte.d.ts +2 -2
  8. package/dist/components/ic/NumberInputController.svelte +16 -2
  9. package/dist/components/ic/shared/EditorFileBrowserOverlay.svelte +26 -18
  10. package/dist/composition/compositionApi.d.ts +25 -0
  11. package/dist/composition/compositionApi.js +34 -4
  12. package/dist/composition/compositionEditorController.d.ts +63 -3
  13. package/dist/composition/compositionEditorController.js +207 -10
  14. package/dist/composition/staleGuard.d.ts +111 -0
  15. package/dist/composition/staleGuard.js +279 -0
  16. package/dist/embedAssistant/embedAssistantSuggest.d.ts +20 -0
  17. package/dist/embedAssistant/embedAssistantSuggest.js +29 -0
  18. package/dist/embedAssistant/embedAssistantTurns.d.ts +73 -0
  19. package/dist/embedAssistant/embedAssistantTurns.js +56 -0
  20. package/dist/embedAssistant/types.d.ts +15 -0
  21. package/dist/i18n/language.d.ts +19 -3
  22. package/dist/i18n/messages.d.ts +9 -0
  23. package/dist/i18n/messages.js +11 -0
  24. package/dist/i18n/translate.d.ts +1 -1
  25. package/package.json +8 -3
  26. package/dist/components/ic/NumberControls.svelte +0 -505
  27. package/dist/components/ic/NumberControls.svelte.d.ts +0 -37
  28. package/dist/components/ic/numberControlsSteps.d.ts +0 -17
  29. package/dist/components/ic/numberControlsSteps.js +0 -23
  30. package/dist/components/ic/numberControlsValueArea.d.ts +0 -29
  31. package/dist/components/ic/numberControlsValueArea.js +0 -51
@@ -25,7 +25,8 @@
25
25
  export interface DatePickerInputControllerProps {
26
26
  label: string;
27
27
  value?: any;
28
- onChange: (newValue: CalendarDate) => void;
28
+ /** Widgets and compositions store the day as `YYYY-MM-DD`. */
29
+ onChange: (newValue: string) => void;
29
30
  description?: string;
30
31
  controllerId: string;
31
32
  openDropdowns: Writable<Set<string>>;
@@ -37,7 +38,7 @@
37
38
  <script lang="ts">
38
39
  // Svelte imports
39
40
  import { onMount, onDestroy } from 'svelte';
40
- import { listenForScroll } from '../../utils/shadowDom';
41
+ import { acquirePortalHost, isEventInside, listenForScroll, releasePortalHost } from '../../utils/shadowDom';
41
42
  import { useEditorLanguage } from '../../i18n/language';
42
43
  import type { EditorMessageKey } from '../../i18n/messages';
43
44
  import type { Translate } from '@widgetic/design-system/i18n';
@@ -52,7 +53,13 @@
52
53
  import { Calendar } from '@widgetic/design-system/components';
53
54
 
54
55
  // Internationalized date imports
55
- import { CalendarDate, getLocalTimeZone, today, DateFormatter } from '@internationalized/date';
56
+ import {
57
+ CalendarDate,
58
+ DateFormatter,
59
+ getLocalTimeZone,
60
+ parseDate,
61
+ today
62
+ } from '@internationalized/date';
56
63
  import type { DateValue } from '@internationalized/date';
57
64
 
58
65
  // Lucide Icons
@@ -86,10 +93,16 @@
86
93
  label: monthFmt.format(new Date(2021, monthIndex, 1))
87
94
  }));
88
95
 
89
- const yearOptions = Array.from({ length: 100 }, (_, i) => {
90
- const year = String(new Date().getFullYear() - i);
91
- return { label: year, value: year };
92
- });
96
+ const YEAR_PAST_COUNT = 80;
97
+ const YEAR_FUTURE_COUNT = 50;
98
+ const yearNow = new Date().getFullYear();
99
+ const calendarMinValue = new CalendarDate(yearNow - YEAR_PAST_COUNT, 1, 1);
100
+ const calendarMaxValue = new CalendarDate(yearNow + YEAR_FUTURE_COUNT, 12, 31);
101
+ const yearOptions = [
102
+ yearNow,
103
+ ...Array.from({ length: YEAR_FUTURE_COUNT }, (_, i) => yearNow + 1 + i),
104
+ ...Array.from({ length: YEAR_PAST_COUNT }, (_, i) => yearNow - 1 - i)
105
+ ].map((year) => ({ label: String(year), value: String(year) }));
93
106
 
94
107
  $: defaultYear = placeholder
95
108
  ? {
@@ -105,48 +118,67 @@
105
118
  }
106
119
  : undefined;
107
120
 
121
+ /**
122
+ * Reads a stored day into a CalendarDate this file constructed.
123
+ * Widgets keep `YYYY-MM-DD`; bits-ui may hand over a date from another copy of
124
+ * `@internationalized/date`, so `instanceof CalendarDate` is not enough.
125
+ */
126
+ function calendarDateFromUnknown(raw: unknown): CalendarDate | undefined {
127
+ if (raw == null || raw === '') return undefined;
128
+ try {
129
+ if (typeof raw === 'string') {
130
+ const isoDay = raw.match(/^(\d{4}-\d{2}-\d{2})/);
131
+ if (isoDay) return parseDate(isoDay[1]);
132
+ const asDate = new Date(raw);
133
+ if (!Number.isNaN(asDate.getTime())) {
134
+ return new CalendarDate(asDate.getFullYear(), asDate.getMonth() + 1, asDate.getDate());
135
+ }
136
+ return undefined;
137
+ }
138
+ if (raw instanceof Date && !Number.isNaN(raw.getTime())) {
139
+ return new CalendarDate(raw.getFullYear(), raw.getMonth() + 1, raw.getDate());
140
+ }
141
+ if (typeof raw === 'object') {
142
+ const record = raw as Record<string, unknown>;
143
+ if (typeof record.date === 'string') return calendarDateFromUnknown(record.date);
144
+ if ('year' in record && 'month' in record && 'day' in record) {
145
+ return new CalendarDate(Number(record.year), Number(record.month), Number(record.day));
146
+ }
147
+ }
148
+ } catch (error) {
149
+ console.warn('[DatePicker] Could not read date value:', raw, error);
150
+ }
151
+ return undefined;
152
+ }
153
+
154
+ function commitSelectedDate(date: CalendarDate) {
155
+ currentValue = date;
156
+ placeholder = date;
157
+ onChange(date.toString());
158
+ }
159
+
108
160
  /**
109
161
  * Updates the current value when the external value changes
110
162
  * Handles initialization and updates of the date state
111
163
  * Creates a new CalendarDate instance to prevent reference issues
112
164
  */
113
165
  function updateCurrentValue() {
114
- // console.log('🔄 [DatePicker] updateCurrentValue called with:', { value, type: typeof value });
115
-
116
166
  if (!value) {
117
167
  currentValue = undefined;
118
168
  placeholder = today(getLocalTimeZone());
119
- // console.log('✅ [DatePicker] Set to undefined, placeholder:', placeholder);
120
169
  return;
121
170
  }
122
171
 
123
- if (value instanceof CalendarDate) {
124
- currentValue = value;
125
- // console.log('✅ [DatePicker] Already CalendarDate:', currentValue);
126
- } else if (
127
- typeof value === 'object' &&
128
- value !== null &&
129
- 'year' in value &&
130
- 'month' in value &&
131
- 'day' in value
132
- ) {
133
- try {
134
- currentValue = new CalendarDate(value.year, value.month, value.day);
135
- // console.log('✅ [DatePicker] Created CalendarDate from object:', { original: value, created: currentValue });
136
- } catch (error) {
137
- console.error('❌ [DatePicker] Failed to create CalendarDate from object:', {
138
- value,
139
- error
140
- });
141
- currentValue = undefined;
142
- }
143
- } else {
144
- console.warn('⚠️ [DatePicker] Invalid date value provided:', value);
172
+ const parsed = calendarDateFromUnknown(value);
173
+ if (!parsed) {
174
+ console.warn('[DatePicker] Invalid date value provided:', value);
145
175
  currentValue = undefined;
176
+ placeholder = today(getLocalTimeZone());
177
+ return;
146
178
  }
147
179
 
148
- placeholder = currentValue ?? today(getLocalTimeZone());
149
- // console.log('🎯 [DatePicker] Final state:', { currentValue, placeholder });
180
+ currentValue = parsed;
181
+ placeholder = parsed;
150
182
  }
151
183
 
152
184
  // Track dropdown state through store subscription
@@ -165,7 +197,9 @@
165
197
  languageTag: string,
166
198
  translate: Translate<EditorMessageKey>
167
199
  ): string {
168
- if (!date || !(date instanceof CalendarDate)) return translate('editor.date.pick');
200
+ if (!date || typeof date.year !== 'number' || typeof date.month !== 'number' || typeof date.day !== 'number') {
201
+ return translate('editor.date.pick');
202
+ }
169
203
  try {
170
204
  // Convert to JavaScript Date for localized formatting
171
205
  const jsDate = new Date(date.year, date.month - 1, date.day);
@@ -183,10 +217,10 @@
183
217
  * @param newValue - The newly selected date
184
218
  */
185
219
  function handleSelect(newValue: DateValue | undefined) {
186
- if (newValue instanceof CalendarDate) {
187
- onChange(newValue);
188
- toggleDropdown(controllerId);
189
- }
220
+ const selected = calendarDateFromUnknown(newValue);
221
+ if (!selected) return;
222
+ commitSelectedDate(selected);
223
+ toggleDropdown(controllerId);
190
224
  }
191
225
 
192
226
  /**
@@ -219,40 +253,63 @@
219
253
  * Closes the dropdown when scrolling occurs outside the dropdowns
220
254
  */
221
255
  function handleScroll(event: Event) {
222
- // Ensure target is an HTMLElement
223
- if (!(event.target instanceof HTMLElement)) {
224
- return;
225
- }
226
-
227
- const target = event.target;
228
-
229
- // Check if scroll happened inside our dropdowns
230
- const isInsideDropdown = target.closest('.month-year-dropdown-content');
256
+ if (isEventInside(event, datePickerPortalHost)) return;
257
+ if (open) closeDropdown();
258
+ }
231
259
 
232
- // If scrolling is inside our dropdowns, don't close
233
- if (isInsideDropdown) {
234
- return;
260
+ function handlePopoverInteractOutside(event: Event) {
261
+ if (isEventInside(event, datePickerPortalHost) || isEventInside(event, controllerElement)) {
262
+ event.preventDefault();
235
263
  }
264
+ }
236
265
 
237
- // If scrolling outside our dropdowns, close
238
- if (open) {
266
+ function handlePointerDownOutside(event: PointerEvent) {
267
+ if (!open) return;
268
+ if (isEventInside(event, datePickerPortalHost) || isEventInside(event, controllerElement)) return;
269
+ closeDropdown();
270
+ }
271
+
272
+ /**
273
+ * Shopify's module loads `@internationalized/date` twice, so bits-ui's calendar throws
274
+ * `Unknown date type` on a day click and never calls `onValueChange`. The day cell still
275
+ * has `data-value="YYYY-MM-DD"`: read that here, before bits-ui handles the pointer.
276
+ */
277
+ function handleCalendarDayPointerDown(event: PointerEvent) {
278
+ const path = typeof event.composedPath === 'function' ? event.composedPath() : [event.target];
279
+ for (const node of path) {
280
+ if (!(node instanceof Element)) continue;
281
+ if (node.hasAttribute('data-disabled') || node.hasAttribute('data-unavailable')) continue;
282
+ const iso = node.getAttribute('data-value');
283
+ if (!iso || !/^\d{4}-\d{2}-\d{2}$/.test(iso)) continue;
284
+ const selected = calendarDateFromUnknown(iso);
285
+ if (!selected) return;
286
+ event.preventDefault();
287
+ event.stopPropagation();
288
+ commitSelectedDate(selected);
239
289
  closeDropdown();
290
+ return;
240
291
  }
241
292
  }
242
293
 
243
294
  // The control's own element, which says which tree (the page or a module's shadow root) to listen for scrolling in
244
295
  let controllerElement: HTMLDivElement | undefined;
245
296
  let stopListeningForScroll: () => void = () => {};
297
+ let datePickerPortalHost: HTMLElement | undefined = undefined;
246
298
 
247
299
  // Setup scroll event listener on mount (the page and, inside a module, the module's own panels: a scroll never
248
300
  // leaves a shadow root, so a listener on the window alone does not hear about those)
249
301
  onMount(() => {
302
+ datePickerPortalHost = acquirePortalHost(controllerElement, 'widgetic-date-picker-portal') ?? undefined;
250
303
  stopListeningForScroll = listenForScroll(controllerElement, handleScroll);
304
+ window.addEventListener('pointerdown', handlePointerDownOutside, true);
251
305
  });
252
306
 
253
307
  // Cleanup scroll event listener on destroy
254
308
  onDestroy(() => {
255
309
  stopListeningForScroll();
310
+ window.removeEventListener('pointerdown', handlePointerDownOutside, true);
311
+ releasePortalHost(datePickerPortalHost);
312
+ datePickerPortalHost = undefined;
256
313
  });
257
314
  </script>
258
315
 
@@ -283,6 +340,11 @@
283
340
  class="date-picker-popover z-50 w-[15.625rem] border border-border p-3 shadow-none"
284
341
  align="end"
285
342
  sideOffset={8}
343
+ portalProps={datePickerPortalHost ? { to: datePickerPortalHost } : undefined}
344
+ interactOutsideBehavior="ignore"
345
+ trapFocus={false}
346
+ onInteractOutside={handlePopoverInteractOutside}
347
+ onFocusOutside={handlePopoverInteractOutside}
286
348
  >
287
349
  <div class="flex w-full flex-col gap-3">
288
350
  <div class="flex w-full items-center gap-2">
@@ -297,13 +359,9 @@
297
359
  // we pass a plain CalendarDate instance that the Calendar component can recognise.
298
360
  placeholder = new CalendarDate(placeholder.year, monthValue, placeholder.day);
299
361
  if (currentValue) {
300
- const newValue = new CalendarDate(
301
- currentValue.year,
302
- monthValue,
303
- currentValue.day
362
+ commitSelectedDate(
363
+ new CalendarDate(currentValue.year, monthValue, currentValue.day)
304
364
  );
305
- currentValue = newValue;
306
- onChange(newValue);
307
365
  }
308
366
  }}
309
367
  >
@@ -314,7 +372,10 @@
314
372
  <span class="truncate">{defaultMonth?.label || $t('editor.date.selectMonth')}</span>
315
373
  </Select.Trigger>
316
374
  <!-- No overflow-y-auto of its own (round 26): the list scrolls inside its viewport with the arrow buttons, which show the hand cursor; a second scroller here could only add a double scrollbar -->
317
- <Select.Content class="month-year-dropdown-content max-h-[200px]">
375
+ <Select.Content
376
+ class="month-year-dropdown-content max-h-[200px]"
377
+ portalProps={datePickerPortalHost ? { to: datePickerPortalHost } : undefined}
378
+ >
318
379
  {#each monthOptions as { value, label }}
319
380
  <Select.Item {value} {label}>
320
381
  {label}
@@ -332,13 +393,9 @@
332
393
  // Same fix as above – ensure a clean CalendarDate instance.
333
394
  placeholder = new CalendarDate(yearValue, placeholder.month, placeholder.day);
334
395
  if (currentValue) {
335
- const newValue = new CalendarDate(
336
- yearValue,
337
- currentValue.month,
338
- currentValue.day
396
+ commitSelectedDate(
397
+ new CalendarDate(yearValue, currentValue.month, currentValue.day)
339
398
  );
340
- currentValue = newValue;
341
- onChange(newValue);
342
399
  }
343
400
  }}
344
401
  >
@@ -349,7 +406,10 @@
349
406
  <span class="truncate">{defaultYear?.label || $t('editor.date.selectYear')}</span>
350
407
  </Select.Trigger>
351
408
  <!-- Same as the month list: the viewport scrolls, with the arrow buttons (round 26) -->
352
- <Select.Content class="month-year-dropdown-content max-h-[200px]">
409
+ <Select.Content
410
+ class="month-year-dropdown-content max-h-[200px]"
411
+ portalProps={datePickerPortalHost ? { to: datePickerPortalHost } : undefined}
412
+ >
353
413
  {#each yearOptions as { value, label }}
354
414
  <Select.Item {value} {label}>
355
415
  {label}
@@ -359,22 +419,22 @@
359
419
  </Select.Root>
360
420
  </div>
361
421
  <!-- Style the calendar content -->
362
- <div class="calendar-no-header">
422
+ <div class="calendar-no-header" onpointerdowncapture={handleCalendarDayPointerDown}>
363
423
  <Calendar
364
424
  mode="single"
365
425
  locale={$locale}
366
426
  bind:placeholder
367
427
  value={currentValue}
428
+ minValue={calendarMinValue}
429
+ maxValue={calendarMaxValue}
368
430
  calendarLabel={$t('editor.date.calendarLabel')}
369
431
  previousLabel={$t('editor.date.previousMonth')}
370
432
  nextLabel={$t('editor.date.nextMonth')}
371
433
  onValueChange={(date: DateValue | undefined) => {
372
- if (date instanceof CalendarDate) {
373
- currentValue = date;
374
- placeholder = date;
375
- onChange(date);
376
- closeDropdown();
377
- }
434
+ const selected = calendarDateFromUnknown(date);
435
+ if (!selected) return;
436
+ commitSelectedDate(selected);
437
+ closeDropdown();
378
438
  }}
379
439
  fixedWeeks
380
440
  class="calendar-editor-fit p-0"
@@ -4,14 +4,14 @@ import type { Writable } from 'svelte/store';
4
4
  export interface DatePickerInputControllerProps {
5
5
  label: string;
6
6
  value?: any;
7
- onChange: (newValue: CalendarDate) => void;
7
+ /** Widgets and compositions store the day as `YYYY-MM-DD`. */
8
+ onChange: (newValue: string) => void;
8
9
  description?: string;
9
10
  controllerId: string;
10
11
  openDropdowns: Writable<Set<string>>;
11
12
  toggleDropdown: (id: string) => void;
12
13
  onFocus?: () => void;
13
14
  }
14
- import { CalendarDate } from '@internationalized/date';
15
15
  interface $$__sveltets_2_IsomorphicComponent<Props extends Record<string, any> = any, Events extends Record<string, any> = any, Slots extends Record<string, any> = any, Exports = {}, Bindings = string> {
16
16
  new (options: import('svelte').ComponentConstructorOptions<Props>): import('svelte').SvelteComponent<Props, Events, Slots> & {
17
17
  $$bindings?: Bindings;
@@ -40,8 +40,12 @@
40
40
  // Svelte imports
41
41
  import { onDestroy } from 'svelte';
42
42
 
43
+ // The number control is the design system's: the one component the editor and the canvas panel draw
44
+ import { NumberControls } from '@widgetic/design-system/components';
43
45
  import InputControllerRow from './InputControllerRow.svelte';
44
- import NumberControls from './NumberControls.svelte';
46
+ import { useEditorLanguage } from '../../i18n/language';
47
+
48
+ const { t } = useEditorLanguage();
45
49
 
46
50
  /**
47
51
  * Component Props
@@ -469,5 +473,15 @@
469
473
  </script>
470
474
 
471
475
  <InputControllerRow {label} {helpText} {description}>
472
- <NumberControls {value} {onChange} {min} {max} {step} {isLocked} {onFocus} />
476
+ <NumberControls
477
+ {value}
478
+ {onChange}
479
+ {min}
480
+ {max}
481
+ {step}
482
+ {isLocked}
483
+ {onFocus}
484
+ decreaseLabel={$t('editor.stepper.decrease')}
485
+ increaseLabel={$t('editor.stepper.increase')}
486
+ />
473
487
  </InputControllerRow>
@@ -1,9 +1,11 @@
1
1
  <script lang="ts">
2
2
  /**
3
- * The File Browser of the editor, laid over the props panel: the white surface of the panel, a header with the title
4
- * and the X that closes it (at the end, centred in the height of the header, as in Figma), and the File Browser under
5
- * it. Every control that picks a file (a file, an image, a vector) opens its browser through this, so they look and
6
- * behave the same.
3
+ * The File Browser of the editor, laid over the props panel: the white surface of the panel and the File Browser on it. There is
4
+ * no title bar and no line above it (owner, 20 Nov 2026: "we don't have to have that area at the top that says select image. We
5
+ * could actually move the breadcrumbs there"): the browser draws the crumbs as the first row (`dialogHeader`), and the X that
6
+ * closes the overlay is laid over the end of that row, 16px from the top and from the end, as the X of the design system dialogs.
7
+ * The title stays for a screen reader. Every control that picks a file (a file, an image, a vector) opens its browser through
8
+ * this, so they look and behave the same.
7
9
  *
8
10
  * The control fixes the type of file (`fileFilter`): the browser then draws no "Filter by" (the user cannot change the
9
11
  * type) and the upload takes only that type. `fileFilter="all"` (any file) keeps the filter.
@@ -49,6 +51,13 @@
49
51
  /** Flat host libraries have no folders; partner pages must not use our localStorage keys. */
50
52
  const rememberEditorFolder = getEditorMediaLibrary() == null;
51
53
 
54
+ /**
55
+ * What a File Browser release that is newer than the installed one knows: `dialogHeader`, the browser draws the top of the overlay
56
+ * itself (the crumbs up to the X, the search as an icon so that the filter fits, no title bar and no line). Spread from a plain
57
+ * object, so the editor also builds with the older release (which ignores it).
58
+ */
59
+ const newerFileBrowserProps = { dialogHeader: true };
60
+
52
61
  /** The top-most dialog when this overlay opened: a dialog with a higher generation was opened inside the browser. */
53
62
  const generationWhenOverlayOpened = get(modalState).generation ?? 0;
54
63
 
@@ -112,20 +121,8 @@
112
121
  class:rounded-xl={!fillEditorPanel}
113
122
  class:shadow-md={!fillEditorPanel}
114
123
  >
115
- <div
116
- class="editor-file-browser-header relative flex h-[47px] shrink-0 items-center border-b border-border ps-4 pe-12"
117
- >
118
- <span class="text-body-medium text-foreground">{$t('editor.file.dialogTitle')}</span>
119
- <!-- Figma: the X is a 24px button 12px from the end, centred in the height of the header -->
120
- <button
121
- type="button"
122
- class="editor-file-browser-close press-feedback absolute top-1/2 end-3 flex size-6 -translate-y-1/2 items-center justify-center rounded-lg p-0 transition-colors duration-fast hover:bg-accent focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
123
- on:click={onClose}
124
- aria-label={$t('editor.file.closeDialog')}
125
- >
126
- <IconX class="size-4 stroke-2" />
127
- </button>
128
- </div>
124
+ <!-- No title bar and no line: the File Browser draws the top row (`dialogHeader`). The title stays for a screen reader. -->
125
+ <h2 class="sr-only">{$t('editor.file.dialogTitle')}</h2>
129
126
 
130
127
  <div class="editor-file-browser-body flex min-h-0 flex-1 flex-col overflow-hidden">
131
128
  <!-- With a host media library (flat list) we remember nothing in localStorage. With Widgetic folders we
@@ -148,9 +145,20 @@
148
145
  {addToEditorLabel}
149
146
  locale={$fileBrowserLanguage.locale ?? undefined}
150
147
  messages={$fileBrowserLanguage.messages ?? null}
148
+ {...newerFileBrowserProps}
151
149
  on:select
152
150
  />
153
151
  </div>
152
+
153
+ <!-- The X is laid over the end of the first row of the browser: 32px, 16px from the top and the end (the X of the design system dialogs), on the line of the crumbs. -->
154
+ <button
155
+ type="button"
156
+ class="editor-file-browser-close press-feedback text-foreground absolute end-4 top-4 z-[70] inline-flex size-8 items-center justify-center rounded-lg p-0 transition-colors duration-fast hover:bg-accent focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
157
+ on:click={onClose}
158
+ aria-label={$t('editor.file.closeDialog')}
159
+ >
160
+ <IconX class="size-4 stroke-2" />
161
+ </button>
154
162
  </div>
155
163
  </div>
156
164
  </Portal>
@@ -14,6 +14,9 @@
14
14
  * - a save can name the content version it was made from (`ifMatchVersion`, sent as `If-Match`). When somebody
15
15
  * else saved the content since, the API refuses it (412 `CONTENT_VERSION_MISMATCH`, with the version it holds
16
16
  * now in `details`) instead of replacing their work, and the error says so (`versionConflict`);
17
+ * - a read can name the content version the editor shows (`getCompositionIfChanged`, sent as `If-None-Match`). The API
18
+ * answers 304 with no body when it holds the same version, so a tab that comes back can ask "is this still the latest?"
19
+ * for the price of a header, and is given the composition only when somebody saved a newer one;
17
20
  * - every failure is a `CompositionApiError` with the API's own code, so the host can tell an ended session
18
21
  * (`EDITOR_SESSION_EXPIRED`...) from a missing composition (`NOT_FOUND`) from a widget that was never
19
22
  * published (`WIDGET_NOT_PUBLISHED`);
@@ -154,9 +157,31 @@ export declare class CompositionApiError extends Error {
154
157
  /** True when sending the same request again later may work: nothing was refused, the network or the server failed. */
155
158
  get retryable(): boolean;
156
159
  }
160
+ /** Options of a read that is asked only to answer when the composition changed. */
161
+ export interface GetCompositionIfChangedOptions extends CompositionRequestOptions {
162
+ /**
163
+ * The content version the caller shows. It goes in the `If-None-Match` header, so the API answers `notModified` (304, no
164
+ * body) when it holds that same version. Left out, the composition is always given.
165
+ */
166
+ ifNoneMatchVersion?: number;
167
+ }
168
+ /** What a read that is asked only to answer when the composition changed came to. */
169
+ export type CompositionConditionalAnswer = {
170
+ status: 'notModified';
171
+ } | {
172
+ status: 'changed';
173
+ composition: JsonRecord;
174
+ };
157
175
  /** What a client of the composition routes can do. */
158
176
  export interface CompositionApi {
159
177
  getComposition(compositionId: string, options?: CompositionRequestOptions): Promise<JsonRecord>;
178
+ /**
179
+ * Reads the composition only when its content version is not `ifNoneMatchVersion` (a conditional GET): the answer is
180
+ * `notModified` when nothing newer was saved, and carries the composition when it was. It is what a tab that comes back
181
+ * asks, to learn whether the copy it shows is out of date. Optional for a client made by hand (a test's, a host's):
182
+ * whoever uses it falls back on `getComposition` and compares the versions itself.
183
+ */
184
+ getCompositionIfChanged?(compositionId: string, options?: GetCompositionIfChangedOptions): Promise<CompositionConditionalAnswer>;
160
185
  getPreview(compositionId: string, options?: CompositionRequestOptions): Promise<CompositionPreviewInfo>;
161
186
  getContentSchema(compositionId: string, options?: CompositionRequestOptions): Promise<unknown>;
162
187
  getDesignSchema(compositionId: string, options?: CompositionRequestOptions): Promise<unknown>;
@@ -14,6 +14,9 @@
14
14
  * - a save can name the content version it was made from (`ifMatchVersion`, sent as `If-Match`). When somebody
15
15
  * else saved the content since, the API refuses it (412 `CONTENT_VERSION_MISMATCH`, with the version it holds
16
16
  * now in `details`) instead of replacing their work, and the error says so (`versionConflict`);
17
+ * - a read can name the content version the editor shows (`getCompositionIfChanged`, sent as `If-None-Match`). The API
18
+ * answers 304 with no body when it holds the same version, so a tab that comes back can ask "is this still the latest?"
19
+ * for the price of a header, and is given the composition only when somebody saved a newer one;
17
20
  * - every failure is a `CompositionApiError` with the API's own code, so the host can tell an ended session
18
21
  * (`EDITOR_SESSION_EXPIRED`...) from a missing composition (`NOT_FOUND`) from a widget that was never
19
22
  * published (`WIDGET_NOT_PUBLISHED`);
@@ -229,6 +232,8 @@ export function createCompositionApi(options) {
229
232
  headers['Idempotency-Key'] = extras.idempotencyKey;
230
233
  if (extras.ifMatch)
231
234
  headers['If-Match'] = extras.ifMatch;
235
+ if (extras.ifNoneMatch)
236
+ headers['If-None-Match'] = extras.ifNoneMatch;
232
237
  try {
233
238
  const response = await fetchImplementation(url, {
234
239
  method,
@@ -302,10 +307,11 @@ export function createCompositionApi(options) {
302
307
  return unwrapApiData(parsed);
303
308
  }
304
309
  /**
305
- * A request with the page's token. When the API refuses the token (401) the page is asked for another, and the
306
- * request is sent again once with it, unless the page gives the same one back: that would only be refused again.
310
+ * A request with the page's token, answered as it came. When the API refuses the token (401) the page is asked for
311
+ * another, and the request is sent again once with it, unless the page gives the same one back: that would only be
312
+ * refused again.
307
313
  */
308
- async function request(method, path, extras = {}) {
314
+ async function send(method, path, extras = {}) {
309
315
  const url = `${apiBasePath}${path}`;
310
316
  throwIfAborted(extras.signal);
311
317
  const firstToken = await tokenFor('initial');
@@ -317,7 +323,11 @@ export function createCompositionApi(options) {
317
323
  if (newToken !== firstToken)
318
324
  answer = await attempt(method, url, newToken, extras);
319
325
  }
320
- return interpret(answer);
326
+ return answer;
327
+ }
328
+ /** A request whose answer is read: the payload of a good one, or the error the API described. */
329
+ async function request(method, path, extras = {}) {
330
+ return interpret(await send(method, path, extras));
321
331
  }
322
332
  function compositionPath(compositionId, suffix = '') {
323
333
  if (typeof compositionId !== 'string' || compositionId.trim() === '') {
@@ -360,6 +370,26 @@ export function createCompositionApi(options) {
360
370
  throw invalidResponse('The API gave no composition.');
361
371
  return record;
362
372
  },
373
+ async getCompositionIfChanged(compositionId, requestOptions = {}) {
374
+ const { ifNoneMatchVersion, signal } = requestOptions;
375
+ if (ifNoneMatchVersion !== undefined &&
376
+ !(Number.isSafeInteger(ifNoneMatchVersion) && ifNoneMatchVersion >= 0)) {
377
+ throw new TypeError('A content version is a whole number of zero or more');
378
+ }
379
+ const answer = await send('GET', compositionPath(compositionId), {
380
+ signal,
381
+ // Quoted, the way the API writes the ETag of a composition.
382
+ ifNoneMatch: ifNoneMatchVersion === undefined ? undefined : `"${ifNoneMatchVersion}"`
383
+ });
384
+ // 304 has no body: the API holds the version that was named, so there is nothing newer to read.
385
+ if (answer.status === 304 && ifNoneMatchVersion !== undefined) {
386
+ return { status: 'notModified' };
387
+ }
388
+ const record = interpret(answer);
389
+ if (!isRecord(record) || typeof record.id !== 'string')
390
+ throw invalidResponse('The API gave no composition.');
391
+ return { status: 'changed', composition: record };
392
+ },
363
393
  async getPreview(compositionId, requestOptions = {}) {
364
394
  const preview = await request('GET', compositionPath(compositionId, '/preview'), requestOptions);
365
395
  if (!isRecord(preview) || typeof preview.previewUrl !== 'string') {