@widgetic/creator 0.4.38 → 0.4.39

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.
@@ -248,6 +248,14 @@
248
248
  reportCanvasUnavailable
249
249
  } from './host/creatorHost.js';
250
250
  import { answerMayBeALimit, createLimitReporter, responseIsALimit } from './host/limitRefusal.js';
251
+ import {
252
+ createPublishStateReporter,
253
+ limitRefusalNeedsNoToast,
254
+ normalizeInitialMessage,
255
+ normalizeLimitNotices,
256
+ publishTargetOf
257
+ } from './host/hostControls.js';
258
+ import { createSerialQueue } from './utils/serialQueue.js';
251
259
 
252
260
  function resolveCreatorWorkflowStep(
253
261
  step?: CreatorAppProps['initialStep'] | 'create' | 'edit' | 'embed' | null
@@ -272,6 +280,24 @@
272
280
  export let initialPrompt: CreatorAppProps['initialPrompt'] = null;
273
281
  /** The initial prompt was put in the input; later draft restores leave the person's own text alone. */
274
282
  let appliedInitialPrompt = false;
283
+ /** Words for the chat of a new widget and whether to send them (see `CreatorAppProps.initialMessage`). Used once. */
284
+ export let initialMessage: CreatorAppProps['initialMessage'] = null;
285
+ /** The host's message was put in the input (and sent, when asked); later draft restores leave the person's text alone. */
286
+ let appliedInitialMessage = false;
287
+ /** Where the canvas's tool bar stands along the bottom edge (see `CreatorAppProps.toolbarPosition`). */
288
+ export let toolbarPosition: CreatorAppProps['toolbarPosition'] = undefined;
289
+ /** Whether the canvas shows its Save button (see `CreatorAppProps.showSaveButton`): the site and the standalone creator do. */
290
+ export let showSaveButton: CreatorAppProps['showSaveButton'] = true;
291
+ /** How a refusal because of a limit is told (see `CreatorAppProps.limitNotices`). */
292
+ export let limitNotices: CreatorAppProps['limitNotices'] = 'all';
293
+ $: limitNoticeMode = normalizeLimitNotices(limitNotices);
294
+ /** What Publish would do now, for the host that draws its own button (see `CreatorAppProps.onPublishStateChanged`). */
295
+ export let onPublishStateChanged: CreatorAppProps['onPublishStateChanged'] = undefined;
296
+ /**
297
+ * How long the person can keep changing the canvas before it is saved anyway. The canvas waits for a quiet moment
298
+ * (`autosaveDelayMs`) so the API is not asked after every stroke; this is the most that waiting may take.
299
+ */
300
+ const CANVAS_AUTOSAVE_MAX_WAIT_MS = 15000;
275
301
  export let apiUrl: CreatorAppProps['apiUrl'] = null;
276
302
  export let widgetBuilderUrl: CreatorAppProps['widgetBuilderUrl'] = null;
277
303
  export let initialDebugMode: CreatorAppProps['initialDebugMode'] = undefined;
@@ -503,11 +529,23 @@
503
529
  void applyHostWidgetName(detail.widgetId, detail.name);
504
530
  }
505
531
 
532
+ /**
533
+ * Tells the page's `onPublishStateChanged` what Publish would do, once per change (the state is worked out again on every
534
+ * change of a panel). A handler that throws does not reach the creator.
535
+ */
536
+ const publishStateReporter = createPublishStateReporter((state) => {
537
+ try {
538
+ onPublishStateChanged?.(state);
539
+ } catch (error) {
540
+ console.error(`[CreatorApp] The page's onPublishStateChanged handler threw:`, error);
541
+ }
542
+ });
543
+
506
544
  let lastAnnouncedPublishState = '';
507
545
  $: if (embedded && typeof window !== 'undefined') {
508
- const targetId = (focusedPanelWidgetId && !isDraftConvertId(focusedPanelWidgetId))
509
- ? focusedPanelWidgetId
510
- : ((canvasPrimaryWidgetId || '').trim());
546
+ // The widget the header's Publish speaks for: `publish()` below asks the same rule, so the button that looks
547
+ // ready and the publish it runs are about the same widget.
548
+ const targetId = publishTargetOf(focusedPanelWidgetId, canvasPrimaryWidgetId, isDraftConvertId);
511
549
  const generatingMark = targetId ? !!generatingWidgetIds[targetId] : false;
512
550
  const gate = targetId ? getPublishGateForPanel(targetId) : null;
513
551
  const canPublish = !!gate && !gate.disabled;
@@ -526,6 +564,14 @@
526
564
  unpublished,
527
565
  });
528
566
  }
567
+ // The page that draws its own Publish button (a partner's page has no header of the site's to hear the event).
568
+ publishStateReporter.note({
569
+ widgetId: targetId || null,
570
+ canPublish,
571
+ publishing: isPublishing && (!publishingWidgetId || publishingWidgetId === targetId),
572
+ label: unpublished ? $t('creator.publish.publishChanges') : label,
573
+ unpublished,
574
+ });
529
575
  }
530
576
 
531
577
  function handleHostRequestPublishEvent(): void {
@@ -538,6 +584,55 @@
538
584
  runPublishForPanel(targetId);
539
585
  }
540
586
 
587
+ // ===================== Controls the host can call on the component =====================
588
+ //
589
+ // A page that draws its own header around the creator (the Shopify app: a Back arrow, the name of the widget, a Publish
590
+ // button) calls these on the component (`bind:this`, or the module's methods). The Widgetic site does the same things
591
+ // through the `widgetic:host-*` events above, which a partner's page never gets (see `mayListenToSiteEvents`).
592
+
593
+ /**
594
+ * Presses Publish for the widget the header's Publish speaks for (the rule that works out the state the page is told, see
595
+ * `publishTargetOf`). Resolves when the request is over. The page learns how it went from `onPublishComplete` and
596
+ * `onPublishStateChanged`; a refusal is the creator's own toast, never a throw into the page.
597
+ */
598
+ export async function publish(): Promise<void> {
599
+ const targetId = publishTargetOf(focusedPanelWidgetId, canvasPrimaryWidgetId, isDraftConvertId);
600
+ if (!targetId) {
601
+ console.warn('[CreatorApp] Host publish ignored: there is no widget to publish yet');
602
+ showToast('error', $t('creator.publish.cannotPublish'), { description: $t('creator.widget.noWidgetSelected') });
603
+ return;
604
+ }
605
+ try {
606
+ await runPublishForPanel(targetId);
607
+ } catch (error) {
608
+ console.error('[CreatorApp] Host publish failed:', error);
609
+ }
610
+ }
611
+
612
+ /**
613
+ * Saves what the person changed on the canvas now, without waiting for the quiet moment, and resolves once the server has
614
+ * it (the saves already on their way are waited for too). A page that is about to take the person away from the creator
615
+ * (its Back arrow) calls this first. Never rejects: a save that fails stays unsaved on the canvas, and the copy kept in the
616
+ * browser is not lost (see `handleCanvasAutoSave`).
617
+ */
618
+ export async function flush(): Promise<void> {
619
+ try {
620
+ await canvasRef?.flushAutosave?.();
621
+ await canvasSaveQueue.whenIdle();
622
+ } catch (error) {
623
+ console.warn('[CreatorApp] Host flush failed:', error);
624
+ }
625
+ }
626
+
627
+ /**
628
+ * Renames a widget the way the site's header does: the name changes on the canvas and in the creator's panels at once,
629
+ * and is saved to the API. `widgetId` names the widget (the page knows it from `onWidgetRenamed`); without it the widget
630
+ * of the panel the person is on is renamed.
631
+ */
632
+ export async function setWidgetName(name: string, widgetId?: string | null): Promise<void> {
633
+ await applyHostWidgetName(widgetId, name);
634
+ }
635
+
541
636
  let className = '';
542
637
  export { className as class };
543
638
  export let style = '';
@@ -9986,6 +10081,16 @@
9986
10081
  if (chatDraftRestoredForWidgetId === selectedWidgetId) return;
9987
10082
  chatDraftRestoredForWidgetId = selectedWidgetId;
9988
10083
 
10084
+ // The host's own message (`initialMessage`), when it has one that can be used and has not been used yet.
10085
+ const hostInitialMessage = appliedInitialMessage ? null : normalizeInitialMessage(initialMessage);
10086
+ if (initialMessage && !appliedInitialMessage && !hostInitialMessage) {
10087
+ console.warn('[CreatorApp] The host\'s initialMessage is ignored: it needs `text` that is not empty and not over 4000 characters, and `attachments`, when it has any, must be at most 5 PNG, JPEG, WebP or GIF files of at most 10 MB each');
10088
+ }
10089
+ /** Words to send once the draft is restored (the host asked for `send`); sending inside the restore would be undone by it. */
10090
+ let messageToSendAfterRestore: string | null = null;
10091
+ /** The pictures of the host's message: sent with its words, or put in the input beside them (the host did not ask for `send`). */
10092
+ let hostPictures: File[] = [];
10093
+
9989
10094
  suppressChatDraftSync = true;
9990
10095
  try {
9991
10096
  if (pendingChatDraftText) {
@@ -9993,6 +10098,13 @@
9993
10098
  if (promptImages.length > 0) {
9994
10099
  chatMethods.restoreAttachmentsFromDataUrls?.(promptImages);
9995
10100
  }
10101
+ } else if (hostInitialMessage && !appliedInitialMessage) {
10102
+ // The host opened a new widget with a message for it (a link to replicate): it goes into the input first, so
10103
+ // a person whose message could not be sent still has it, and is sent after the restore when the host asked.
10104
+ appliedInitialMessage = true;
10105
+ chatMethods.setDraftText?.(hostInitialMessage.text);
10106
+ hostPictures = hostInitialMessage.attachments;
10107
+ if (hostInitialMessage.send) messageToSendAfterRestore = hostInitialMessage.text;
9996
10108
  } else if (!appliedInitialPrompt && typeof initialPrompt === 'string' && initialPrompt.trim()) {
9997
10109
  // The host opened a new widget with words already in the chat (a Figma link from the Design page):
9998
10110
  // put them in the input once, for the person to read and send. Never sent by the creator itself.
@@ -10007,6 +10119,59 @@
10007
10119
  } finally {
10008
10120
  suppressChatDraftSync = false;
10009
10121
  }
10122
+
10123
+ if (messageToSendAfterRestore) {
10124
+ // A turn later: the restore above is finished and the chat has its input in place, as it has when a person sends.
10125
+ // The chat that is ready now is the one that sends, whichever panel the person is on by then.
10126
+ const wordsToSend = messageToSendAfterRestore;
10127
+ const picturesToSend = hostPictures;
10128
+ const chatToSendFrom = chatMethods;
10129
+ setTimeout(() => void sendInitialMessageFromHost(wordsToSend, picturesToSend, chatToSendFrom), 0);
10130
+ } else if (hostPictures.length > 0) {
10131
+ // Not sent: the pictures wait in the input beside the words, for the person to look at and send.
10132
+ void putHostPicturesInInput(hostPictures, chatMethods);
10133
+ }
10134
+ }
10135
+
10136
+ /**
10137
+ * Sends the host's `initialMessage` through the chat's own `sendMessage`, the function the chat's Enter key calls, so the
10138
+ * message goes the way a typed one does (the widget is made, the generation starts). The pictures go as the files the
10139
+ * person would have attached: the chat shows them in the message and the builder looks at them. A failure is logged and
10140
+ * leaves the words in the input, where the person can send them.
10141
+ */
10142
+ async function sendInitialMessageFromHost(text: string, pictures: File[], methods: typeof chatMethods): Promise<void> {
10143
+ if (!methods?.sendMessage) {
10144
+ console.warn('[CreatorApp] The host\'s first message stays in the input: the chat cannot send yet');
10145
+ return;
10146
+ }
10147
+ try {
10148
+ if (pictures.length > 0) {
10149
+ await methods.sendMessage(text, pictures);
10150
+ } else {
10151
+ await methods.sendMessage(text);
10152
+ }
10153
+ } catch (error) {
10154
+ console.error('[CreatorApp] The host\'s first message could not be sent; it stays in the input:', error);
10155
+ }
10156
+ }
10157
+
10158
+ /**
10159
+ * Puts the pictures of the host's `initialMessage` in the chat's input, beside its words, as if the person had attached
10160
+ * them: each is read as an image and handed to the chat's own `addImageAttachment`. A picture that cannot be read is
10161
+ * logged and left out; the others still go in.
10162
+ */
10163
+ async function putHostPicturesInInput(pictures: File[], methods: typeof chatMethods): Promise<void> {
10164
+ if (!methods?.addImageAttachment) {
10165
+ console.warn('[CreatorApp] The host\'s pictures are left out: the chat cannot take an attachment yet');
10166
+ return;
10167
+ }
10168
+ for (const picture of pictures) {
10169
+ try {
10170
+ methods.addImageAttachment(await fileToBase64(picture), picture.name || 'attached-image.png');
10171
+ } catch (error) {
10172
+ console.error('[CreatorApp] A picture of the host\'s message could not be read; it is left out:', error);
10173
+ }
10174
+ }
10010
10175
  }
10011
10176
 
10012
10177
  function handleChatReady(methods: NonNullable<typeof chatMethods>, widgetId?: string | null) {
@@ -11980,7 +12145,10 @@ Requirements:
11980
12145
  lastGenerationFailed: true,
11981
12146
  lastGenerationError: limitMessage,
11982
12147
  });
11983
- showToast('warning', $t('creator.general.limitReached'), { description: limitMessage, duration: 8000 });
12148
+ // The page may want the reason in the chat alone (`limitNotices: 'chat'`): a budget that is used up is a limit.
12149
+ if (!limitRefusalNeedsNoToast(limitNoticeMode, true)) {
12150
+ showToast('warning', $t('creator.general.limitReached'), { description: limitMessage, duration: 8000 });
12151
+ }
11984
12152
  pushCodegenFailureToChat(generationWidgetId, limitMessage);
11985
12153
  return;
11986
12154
  }
@@ -12031,7 +12199,12 @@ Requirements:
12031
12199
  lastGenerationError: message,
12032
12200
  });
12033
12201
  clearActiveOperationId(generationWidgetId); // Clear persisted operationId on error
12034
- showToast('error', $t('creator.codegen.codeGenerationError'), { description: message, duration: 6000 });
12202
+ // A refusal because of a limit (credits used up) is told in the chat alone when the page asked for that
12203
+ // (`limitNotices: 'chat'`): the toast would say the same thing a second time. Any other failure keeps its toast.
12204
+ const refusedForALimit = await responseIsALimit(error?.response);
12205
+ if (!limitRefusalNeedsNoToast(limitNoticeMode, refusedForALimit)) {
12206
+ showToast('error', $t('creator.codegen.codeGenerationError'), { description: message, duration: 6000 });
12207
+ }
12035
12208
  pushCodegenFailureToChat(generationWidgetId, message);
12036
12209
  } finally {
12037
12210
  noteCodegenActive(false);
@@ -12356,6 +12529,9 @@ Requirements:
12356
12529
  ?? publishEnvelope?.commitTitle
12357
12530
  ?? null;
12358
12531
  applyPublishSuccessToWidgetState(capturedWidgetId, version, artifactUrl, commitSha, commitTitle);
12532
+ // The site hears of a finished publish from the realtime socket (see the `widgetPublishStatus` block). A partner's
12533
+ // creator opens no socket, so the answer of this request is what tells its page.
12534
+ if (partnerMode) notifyPublishComplete(capturedWidgetId, version);
12359
12535
 
12360
12536
  if (!publishOpts.silent) {
12361
12537
  showToast('success', $t('creator.publish.widgetPublished'), {
@@ -15858,13 +16034,41 @@ Requirements:
15858
16034
  );
15859
16035
  }
15860
16036
 
16037
+ /**
16038
+ * Tells the page (`onPublishComplete`) that a widget was published. The widget's thumbnail is refreshed first, for at most
16039
+ * two and a half seconds, so a page that leaves the canvas at once (the host's Publish goes back to its dashboard) shows
16040
+ * the published widget and not the old picture. On the Widgetic site the realtime socket says a publish is done; a
16041
+ * partner's creator has no socket, so it goes by the answer of the publish request (see `executePublishWidget`). A
16042
+ * handler that throws does not reach the creator.
16043
+ */
16044
+ function notifyPublishComplete(publishedWidgetId: string, publishedVersion: number | undefined): void {
16045
+ if (!embedded || !onPublishComplete) return;
16046
+ void (async () => {
16047
+ await Promise.race([
16048
+ handleRefreshScreenshot(publishedWidgetId, { quiet: true }).catch((error) => {
16049
+ console.warn('[Publish] Thumbnail before leaving the canvas failed', error);
16050
+ }),
16051
+ new Promise((resolve) => setTimeout(resolve, 2500)),
16052
+ ]);
16053
+ try {
16054
+ onPublishComplete({
16055
+ widgetId: publishedWidgetId,
16056
+ version: publishedVersion
16057
+ });
16058
+ } catch (error) {
16059
+ console.error(`[CreatorApp] The page's onPublishComplete handler threw:`, error);
16060
+ }
16061
+ })();
16062
+ }
16063
+
15861
16064
  /**
15862
16065
  * Publish for a panel. Pass `targetVersion` to publish a specific Draft the
15863
16066
  * user selected in the version list (built from that version's own commit);
15864
- * omit it to publish the newest generated code.
16067
+ * omit it to publish the newest generated code. The promise ends when the request is over; the buttons that start it do
16068
+ * not wait for it, and `publish()` (the host's control) does.
15865
16069
  */
15866
- function runPublishForPanel(panelWidgetId: string, targetVersion?: number | null): void {
15867
- void (async () => {
16070
+ function runPublishForPanel(panelWidgetId: string, targetVersion?: number | null): Promise<void> {
16071
+ return (async () => {
15868
16072
  if (isPublishing && !publishingWidgetId) {
15869
16073
  console.warn('[Publish] Clearing stuck global isPublishing flag');
15870
16074
  isPublishing = false;
@@ -15940,20 +16144,7 @@ $: if ($widgetPublishStatus.timestamp && $widgetPublishStatus.widgetId) {
15940
16144
  void getWidgetDetailsRef(publishWidgetId)?.refreshPreview({ withRetry: true });
15941
16145
  }
15942
16146
  if (embedded && onPublishComplete && publishWidgetId) {
15943
- const publishedWidgetId = publishWidgetId;
15944
- const publishedVersion = publishResult.version;
15945
- void (async () => {
15946
- await Promise.race([
15947
- handleRefreshScreenshot(publishedWidgetId, { quiet: true }).catch((error) => {
15948
- console.warn('[Publish] Thumbnail before leaving the canvas failed', error);
15949
- }),
15950
- new Promise((resolve) => setTimeout(resolve, 2500)),
15951
- ]);
15952
- onPublishComplete({
15953
- widgetId: publishedWidgetId,
15954
- version: publishedVersion
15955
- });
15956
- })();
16147
+ notifyPublishComplete(publishWidgetId, publishResult.version);
15957
16148
  } else if (publishWidgetId) {
15958
16149
  scheduleQuietScreenshot(publishWidgetId, 2000);
15959
16150
  }
@@ -17624,6 +17815,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17624
17815
  */
17625
17816
  let autosaveSequence = 0;
17626
17817
  let lastResolvedAutosaveSequence = 0;
17818
+ /** The requests that write the canvas to the API, one at a time and in the order they were made (see `handleCanvasAutoSave`). */
17819
+ const canvasSaveQueue = createSerialQueue();
17627
17820
  /**
17628
17821
  * Trailing save deferred while `isLoadCooldownActive` is set.
17629
17822
  * See {@link handleCanvasAutoSave}: dropping cooldown saves lost user edits.
@@ -17743,14 +17936,21 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17743
17936
  // Save to API via SDK with sequence race protection
17744
17937
  if (canvasId && canvasesClient) {
17745
17938
  const currentSeq = ++autosaveSequence;
17939
+ // The canvas this save is for, read now: the request waits its turn in the queue, and the person may switch canvas meanwhile.
17940
+ const saveCanvasId = canvasId;
17941
+ const saveClient = canvasesClient;
17746
17942
  try {
17747
- await canvasesClient.updateCanvas({
17748
- id: canvasId,
17749
- updateCanvasRequest: {
17750
- canvasContent: parsedCanvas ?? JSON.parse(json)
17751
- }
17752
- });
17753
- canvasRecordReads.delete(canvasId);
17943
+ // One request at a time, in the order the canvas was changed: two in flight can reach the server in either
17944
+ // order, and the older canvas would overwrite the newer one.
17945
+ await canvasSaveQueue.run(() =>
17946
+ saveClient.updateCanvas({
17947
+ id: saveCanvasId,
17948
+ updateCanvasRequest: {
17949
+ canvasContent: parsedCanvas ?? JSON.parse(json)
17950
+ }
17951
+ })
17952
+ );
17953
+ canvasRecordReads.delete(saveCanvasId);
17754
17954
  if (currentSeq < lastResolvedAutosaveSequence) {
17755
17955
  // console.log(
17756
17956
  // `[CanvasDebug] Dropped out-of-order autosave response (${currentSeq} < ${lastResolvedAutosaveSequence})`
@@ -18959,8 +19159,10 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18959
19159
  widgetDetails?.closeWidgetDetails();
18960
19160
  }}
18961
19161
  panZoomPosition="TL"
18962
- showSaveButton={true}
19162
+ toolbarPosition={toolbarPosition}
19163
+ showSaveButton={showSaveButton}
18963
19164
  autosaveDelayMs={import.meta.env.DEV ? 15000 : 5000}
19165
+ autosaveMaxWaitMs={CANVAS_AUTOSAVE_MAX_WAIT_MS}
18964
19166
  suspendAutosave={suspendCanvasAutosave}
18965
19167
  isExternalDataLoading={!isCanvasStateLoaded}
18966
19168
  />
@@ -24,6 +24,11 @@ declare const CreatorApp: $$__sveltets_2_IsomorphicComponent<{
24
24
  forceCreateNewWidget?: CreatorAppProps["forceCreateNewWidget"];
25
25
  initialSketchName?: CreatorAppProps["initialSketchName"];
26
26
  /** Words to put in the chat input of a new widget, once (never sent by the creator itself). */ initialPrompt?: CreatorAppProps["initialPrompt"];
27
+ /** Words for the chat of a new widget and whether to send them (see `CreatorAppProps.initialMessage`). Used once. */ initialMessage?: CreatorAppProps["initialMessage"];
28
+ /** Where the canvas's tool bar stands along the bottom edge (see `CreatorAppProps.toolbarPosition`). */ toolbarPosition?: CreatorAppProps["toolbarPosition"];
29
+ /** Whether the canvas shows its Save button (see `CreatorAppProps.showSaveButton`): the site and the standalone creator do. */ showSaveButton?: CreatorAppProps["showSaveButton"];
30
+ /** How a refusal because of a limit is told (see `CreatorAppProps.limitNotices`). */ limitNotices?: CreatorAppProps["limitNotices"];
31
+ /** What Publish would do now, for the host that draws its own button (see `CreatorAppProps.onPublishStateChanged`). */ onPublishStateChanged?: CreatorAppProps["onPublishStateChanged"];
27
32
  apiUrl?: CreatorAppProps["apiUrl"];
28
33
  widgetBuilderUrl?: CreatorAppProps["widgetBuilderUrl"];
29
34
  initialDebugMode?: CreatorAppProps["initialDebugMode"];
@@ -60,12 +65,18 @@ declare const CreatorApp: $$__sveltets_2_IsomorphicComponent<{
60
65
  * its File Browser and rich text editor) reads it from Svelte's context and follows when the page changes `dir`;
61
66
  * `textDirection` is the answer, for the creator's own decisions (where a pop-up opens from, which way a divider drags).
62
67
  */ dir?: CreatorAppProps["dir"];
68
+ publish?: () => Promise<void>;
69
+ flush?: () => Promise<void>;
70
+ setWidgetName?: (name: string, widgetId?: string | null) => Promise<void>;
63
71
  class?: string;
64
72
  style?: string;
65
73
  }, {
66
74
  [evt: string]: CustomEvent<any>;
67
75
  }, {}, {
68
76
  onBack: CreatorAppProps["onBack"];
77
+ publish: () => Promise<void>;
78
+ flush: () => Promise<void>;
79
+ setWidgetName: (name: string, widgetId?: string | null) => Promise<void>;
69
80
  }, string>;
70
81
  type CreatorApp = InstanceType<typeof CreatorApp>;
71
82
  export default CreatorApp;
@@ -1,5 +1,8 @@
1
1
  import type { MediaLibraryProvider } from '@widgetic/file-browser';
2
2
  import type { TextDirection } from '@widgetic/design-system/components/textDirection';
3
+ import type { ToolbarPosition } from '@widgetic/canvas';
4
+ import type { LimitNotices, PublishState } from './host/hostControls.js';
5
+ export type { LimitNotices, PublishState };
3
6
  /** Why the creator asks the page for a token. */
4
7
  export type CreatorTokenReason =
5
8
  /** It wants the token to use now (the page keeps it fresh), or is starting. */
@@ -139,6 +142,46 @@ export interface CreatorAppProps {
139
142
  * a widget with a pasted Figma link this way). Ignored when the widget has a draft of its own.
140
143
  */
141
144
  initialPrompt?: string | null;
145
+ /**
146
+ * Words for the chat of a new widget, and whether to send them: `{ text, send?, attachments? }`. With `send: true` the
147
+ * creator sends them as the first message, once the chat is ready, exactly as if the person had typed them and pressed
148
+ * Enter (the generation starts); without it they wait in the input, like `initialPrompt`. A Shopify merchant who pastes a
149
+ * Figma link to replicate gets a widget whose first message is that link. `attachments` are pictures that go with the
150
+ * words (a photo to replicate): at most five `File`s of the host's own, each a PNG, JPEG, WebP or GIF of at most 10 MB.
151
+ * They are sent with the message, as if the person had attached them, or (without `send`) wait in the input beside the
152
+ * words. Used once per creator; ignored when the widget has a draft of its own; empty words, words that are not text,
153
+ * words longer than 4000 characters and pictures that cannot be used (one that fails fails the message) are ignored.
154
+ */
155
+ initialMessage?: {
156
+ text: string;
157
+ send?: boolean;
158
+ attachments?: File[];
159
+ } | null;
160
+ /**
161
+ * Where the canvas's tool bar (the drawing tools and the element selector) stands along the bottom edge: `'BL'`
162
+ * (bottom left), `'BC'` (bottom centre, the default) or `'BR'` (bottom right). A host whose own page puts something
163
+ * over the centre of the bottom edge (Shopify's Sidekick) moves it.
164
+ */
165
+ toolbarPosition?: ToolbarPosition;
166
+ /**
167
+ * Whether the canvas shows its Save button and the dot that says the board has changes the server does not have.
168
+ * Default `true`. The canvas saves on its own either way (a moment after the last change, at the latest every fifteen
169
+ * seconds of work, and when the page is hidden or closed); a host that wants no save control on its page passes `false`.
170
+ */
171
+ showSaveButton?: boolean;
172
+ /**
173
+ * How a refusal because of a limit (credits used up, a plan that does not include it) is told on the creator's own
174
+ * screen. `'all'` (the default) shows a toast and puts the reason in the chat. `'chat'` puts it in the chat only: the page
175
+ * shows no second notice, or draws its own. Only refusals the API marks as a limit are affected; every other failure
176
+ * keeps its toast.
177
+ */
178
+ limitNotices?: LimitNotices;
179
+ /**
180
+ * The host's Publish button follows this: what Publish would do now (`canPublish`, `publishing`, `label`,
181
+ * `unpublished`) for the widget it would publish (`widgetId`). Called with the first state once the creator knows it,
182
+ * then on every change, and never twice with the same state. The host presses Publish with `publish()` on the component.
183
+ */
184
+ onPublishStateChanged?: (state: PublishState) => void;
142
185
  /** When true, hides auth screen + top bar; syncs session from site localStorage */
143
186
  embedded?: boolean;
144
187
  /**
@@ -185,6 +228,11 @@ export interface CreatorAppProps {
185
228
  enableLocalCache?: boolean;
186
229
  class?: string;
187
230
  style?: string;
231
+ /**
232
+ * A widget was published (its new version is live). Called once per publish, a moment after the answer (the creator
233
+ * first refreshes the widget's thumbnail, for at most two and a half seconds). On the Widgetic site the realtime socket
234
+ * says it; in a partner's page, which has no socket, the answer of the publish request does.
235
+ */
188
236
  onPublishComplete?: (detail: {
189
237
  widgetId: string;
190
238
  version?: number;
@@ -0,0 +1,94 @@
1
+ /**
2
+ * What a page that mounts the creator can ask of it besides its props, and the small rules behind it.
3
+ *
4
+ * A host that draws its own header around the creator (the Shopify app does: a Back arrow, the widget's name, a Publish
5
+ * button) needs four things from it, none of which are a prop:
6
+ *
7
+ * - to know whether Publish is possible right now, and what it would say (`PublishState`, told with
8
+ * `onPublishStateChanged`);
9
+ * - to press Publish for the person (`publish()`);
10
+ * - to put what the person changed on the server before it leaves the page (`flush()`);
11
+ * - to rename the widget the creator shows (`setWidgetName()`).
12
+ *
13
+ * It also lets the host choose how a refusal because of a limit (credits used up) is told (`limitNotices`), and put a
14
+ * message in the chat of a new widget and send it (`initialMessage`: a link to replicate, or a photo to replicate, for one).
15
+ *
16
+ * This file is plain TypeScript with no Svelte in it, so a test can hold it to every one of those rules.
17
+ */
18
+ /** How a refusal because of a limit is told on the creator's own screen. */
19
+ export type LimitNotices =
20
+ /** A toast and a line in the chat: what the creator always did, and what the site and a partner's page get. */
21
+ 'all'
22
+ /** The line in the chat only. The page tells the person anything more itself, or nothing. */
23
+ | 'chat';
24
+ /** What a page that says nothing about it gets. */
25
+ export declare const DEFAULT_LIMIT_NOTICES: LimitNotices;
26
+ /** The notices a page asked for; anything the creator does not know is the default. */
27
+ export declare function normalizeLimitNotices(value: unknown): LimitNotices;
28
+ /**
29
+ * Whether a refusal leaves out its toast. Only a refusal because of a limit can: every other failure keeps its toast,
30
+ * whatever the page asked for, because the chat line alone does not say that something went wrong with the request.
31
+ */
32
+ export declare function limitRefusalNeedsNoToast(notices: LimitNotices, refusalIsALimit: boolean): boolean;
33
+ /** The longest message a host can hand the creator: a link and a sentence or two, not a document. */
34
+ export declare const INITIAL_MESSAGE_MAX_CHARS = 4000;
35
+ /** The most pictures a host can send with its message: what one request to the builder takes, and what the chat's input holds. */
36
+ export declare const INITIAL_MESSAGE_MAX_ATTACHMENTS = 5;
37
+ /** The biggest picture a host can send, in bytes: the limit of the creator's own image upload (10 MB). */
38
+ export declare const INITIAL_MESSAGE_MAX_ATTACHMENT_BYTES: number;
39
+ /** The kinds of picture a host can send: the ones the builder looks at and every browser can draw. (Not SVG, not HEIC.) */
40
+ export declare const INITIAL_MESSAGE_ATTACHMENT_TYPES: readonly string[];
41
+ /** A message the host puts in the chat of a new widget. */
42
+ export interface InitialMessage {
43
+ /** The words, trimmed. */
44
+ text: string;
45
+ /** Whether the creator sends it as the first message, as if the person had typed it and pressed Enter. */
46
+ send: boolean;
47
+ /** The pictures that go with the words (a photo to replicate): sent with them, or put in the input beside them. Often none. */
48
+ attachments: File[];
49
+ }
50
+ /**
51
+ * The pictures a host handed over, or null when they cannot be used. Nothing given (undefined, null) is no pictures. Anything
52
+ * else must be a list of the host's own `File`s: no more than five, each a PNG, JPEG, WebP or GIF, not empty and not over
53
+ * 10 MB. One picture that fails makes all of them unusable, because the message then says something ("replicate this photo")
54
+ * about a picture that is not there. The list returned is a copy; the files are the host's own.
55
+ */
56
+ export declare function normalizeInitialMessageAttachments(value: unknown): File[] | null;
57
+ /**
58
+ * The message a host handed over, or null when there is none to use: nothing given, no words, words that are not text
59
+ * or too many of them, or pictures that cannot be used (see `normalizeInitialMessageAttachments`). `send` is on only when
60
+ * the host said `true`, never for a value that merely looks true.
61
+ */
62
+ export declare function normalizeInitialMessage(value: unknown): InitialMessage | null;
63
+ /**
64
+ * The widget the host's Publish speaks for: the widget of the panel the person is on (a draft that is not a widget yet
65
+ * does not count), else the primary widget of the canvas. The Publish button the host draws and the publish the creator
66
+ * runs when it is pressed must be about the same widget, so both ask here.
67
+ */
68
+ export declare function publishTargetOf(focusedPanelWidgetId: string | null | undefined, canvasPrimaryWidgetId: string | null | undefined, isDraftId: (widgetId: string) => boolean): string;
69
+ /** What the host needs to draw its Publish button. */
70
+ export interface PublishState {
71
+ /** The widget Publish would publish; null when there is none yet. */
72
+ widgetId: string | null;
73
+ /** Publish can be pressed now. */
74
+ canPublish: boolean;
75
+ /** A publish of that widget is running. */
76
+ publishing: boolean;
77
+ /** The words the creator's own Publish button would carry ("Publish", "Publish changes"). */
78
+ label: string;
79
+ /** The widget has changes no published version has. */
80
+ unpublished: boolean;
81
+ }
82
+ /** One line that is the same for two states that say the same thing. */
83
+ export declare function publishStateSignature(state: PublishState): string;
84
+ export interface PublishStateReporter {
85
+ /** Takes the state as it is now; tells the host only when it differs from what the host was told last. Returns whether it told. */
86
+ note(state: PublishState): boolean;
87
+ /** What the host was told last, or null when it was told nothing. */
88
+ readonly last: PublishState | null;
89
+ }
90
+ /**
91
+ * Tells the host the publish state when it changes, and only then: the creator works the state out again on every
92
+ * change of its panels, and a host that redraws a button must not be told the same thing a hundred times.
93
+ */
94
+ export declare function createPublishStateReporter(report: (state: PublishState) => void): PublishStateReporter;
@@ -0,0 +1,121 @@
1
+ /**
2
+ * What a page that mounts the creator can ask of it besides its props, and the small rules behind it.
3
+ *
4
+ * A host that draws its own header around the creator (the Shopify app does: a Back arrow, the widget's name, a Publish
5
+ * button) needs four things from it, none of which are a prop:
6
+ *
7
+ * - to know whether Publish is possible right now, and what it would say (`PublishState`, told with
8
+ * `onPublishStateChanged`);
9
+ * - to press Publish for the person (`publish()`);
10
+ * - to put what the person changed on the server before it leaves the page (`flush()`);
11
+ * - to rename the widget the creator shows (`setWidgetName()`).
12
+ *
13
+ * It also lets the host choose how a refusal because of a limit (credits used up) is told (`limitNotices`), and put a
14
+ * message in the chat of a new widget and send it (`initialMessage`: a link to replicate, or a photo to replicate, for one).
15
+ *
16
+ * This file is plain TypeScript with no Svelte in it, so a test can hold it to every one of those rules.
17
+ */
18
+ /** What a page that says nothing about it gets. */
19
+ export const DEFAULT_LIMIT_NOTICES = 'all';
20
+ /** The notices a page asked for; anything the creator does not know is the default. */
21
+ export function normalizeLimitNotices(value) {
22
+ return value === 'chat' ? 'chat' : DEFAULT_LIMIT_NOTICES;
23
+ }
24
+ /**
25
+ * Whether a refusal leaves out its toast. Only a refusal because of a limit can: every other failure keeps its toast,
26
+ * whatever the page asked for, because the chat line alone does not say that something went wrong with the request.
27
+ */
28
+ export function limitRefusalNeedsNoToast(notices, refusalIsALimit) {
29
+ return notices === 'chat' && refusalIsALimit;
30
+ }
31
+ /** The longest message a host can hand the creator: a link and a sentence or two, not a document. */
32
+ export const INITIAL_MESSAGE_MAX_CHARS = 4000;
33
+ /** The most pictures a host can send with its message: what one request to the builder takes, and what the chat's input holds. */
34
+ export const INITIAL_MESSAGE_MAX_ATTACHMENTS = 5;
35
+ /** The biggest picture a host can send, in bytes: the limit of the creator's own image upload (10 MB). */
36
+ export const INITIAL_MESSAGE_MAX_ATTACHMENT_BYTES = 10 * 1024 * 1024;
37
+ /** The kinds of picture a host can send: the ones the builder looks at and every browser can draw. (Not SVG, not HEIC.) */
38
+ export const INITIAL_MESSAGE_ATTACHMENT_TYPES = ['image/png', 'image/jpeg', 'image/webp', 'image/gif'];
39
+ /**
40
+ * The pictures a host handed over, or null when they cannot be used. Nothing given (undefined, null) is no pictures. Anything
41
+ * else must be a list of the host's own `File`s: no more than five, each a PNG, JPEG, WebP or GIF, not empty and not over
42
+ * 10 MB. One picture that fails makes all of them unusable, because the message then says something ("replicate this photo")
43
+ * about a picture that is not there. The list returned is a copy; the files are the host's own.
44
+ */
45
+ export function normalizeInitialMessageAttachments(value) {
46
+ if (value === undefined || value === null)
47
+ return [];
48
+ if (!Array.isArray(value))
49
+ return null;
50
+ if (value.length > INITIAL_MESSAGE_MAX_ATTACHMENTS)
51
+ return null;
52
+ // A server render has no `File`: nothing can be a picture there, and the host that handed one is not in a server render.
53
+ if (typeof File === 'undefined')
54
+ return value.length === 0 ? [] : null;
55
+ const pictures = [];
56
+ for (const item of value) {
57
+ if (!(item instanceof File))
58
+ return null;
59
+ if (!INITIAL_MESSAGE_ATTACHMENT_TYPES.includes(item.type.toLowerCase()))
60
+ return null;
61
+ if (item.size <= 0 || item.size > INITIAL_MESSAGE_MAX_ATTACHMENT_BYTES)
62
+ return null;
63
+ pictures.push(item);
64
+ }
65
+ return pictures;
66
+ }
67
+ /**
68
+ * The message a host handed over, or null when there is none to use: nothing given, no words, words that are not text
69
+ * or too many of them, or pictures that cannot be used (see `normalizeInitialMessageAttachments`). `send` is on only when
70
+ * the host said `true`, never for a value that merely looks true.
71
+ */
72
+ export function normalizeInitialMessage(value) {
73
+ if (!value || typeof value !== 'object')
74
+ return null;
75
+ const { text, send, attachments } = value;
76
+ if (typeof text !== 'string')
77
+ return null;
78
+ const trimmed = text.trim();
79
+ if (!trimmed || trimmed.length > INITIAL_MESSAGE_MAX_CHARS)
80
+ return null;
81
+ const pictures = normalizeInitialMessageAttachments(attachments);
82
+ if (pictures === null)
83
+ return null;
84
+ return { text: trimmed, send: send === true, attachments: pictures };
85
+ }
86
+ /**
87
+ * The widget the host's Publish speaks for: the widget of the panel the person is on (a draft that is not a widget yet
88
+ * does not count), else the primary widget of the canvas. The Publish button the host draws and the publish the creator
89
+ * runs when it is pressed must be about the same widget, so both ask here.
90
+ */
91
+ export function publishTargetOf(focusedPanelWidgetId, canvasPrimaryWidgetId, isDraftId) {
92
+ if (focusedPanelWidgetId && !isDraftId(focusedPanelWidgetId))
93
+ return focusedPanelWidgetId;
94
+ return (canvasPrimaryWidgetId || '').trim();
95
+ }
96
+ /** One line that is the same for two states that say the same thing. */
97
+ export function publishStateSignature(state) {
98
+ return JSON.stringify([state.widgetId, state.canPublish, state.publishing, state.label, state.unpublished]);
99
+ }
100
+ /**
101
+ * Tells the host the publish state when it changes, and only then: the creator works the state out again on every
102
+ * change of its panels, and a host that redraws a button must not be told the same thing a hundred times.
103
+ */
104
+ export function createPublishStateReporter(report) {
105
+ let lastSignature = null;
106
+ let lastState = null;
107
+ return {
108
+ note(state) {
109
+ const signature = publishStateSignature(state);
110
+ if (signature === lastSignature)
111
+ return false;
112
+ lastSignature = signature;
113
+ lastState = { ...state };
114
+ report({ ...state });
115
+ return true;
116
+ },
117
+ get last() {
118
+ return lastState;
119
+ },
120
+ };
121
+ }
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { default as CreatorApp } from './CreatorApp.svelte';
2
- export type { CreatorAppProps } from './creator-types.js';
2
+ export type { CreatorAppProps, LimitNotices, PublishState } from './creator-types.js';
3
3
  export { syncSessionFromSiteAuth } from './syncSiteAuth.js';
4
4
  export { ALL_CREATOR_MESSAGES, CREATOR_MESSAGES, checkCreatorMessages, type CreatorMessageKey } from './i18n/index.js';
5
5
  export { mount, unmount } from 'svelte';
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Runs asynchronous jobs one at a time, in the order they were handed in.
3
+ *
4
+ * The creator saves the canvas to the API whenever the person has changed it, and the saves can overlap: the canvas
5
+ * saves on its own timer, the creator saves once more when it is taken off the page, a Save pressed by hand goes through
6
+ * the same function. Two requests in flight at once can reach the server in either order, and the older canvas
7
+ * overwrites the newer one. Handing every save through one queue makes the server see them in the order they were made,
8
+ * so the last save the creator made is the one that stays.
9
+ *
10
+ * A job that fails does not stop the ones behind it: each is its own request, and the person's next change must still
11
+ * be saved. The failure is the caller's, through the promise `run` gave it.
12
+ */
13
+ export interface SerialQueue {
14
+ /**
15
+ * Runs `job` once every job handed in before it has finished (done or failed). Resolves or rejects as `job` does.
16
+ * `job` is called when its turn comes, not when it is handed in, so it reads the world as it is then.
17
+ */
18
+ run<T>(job: () => Promise<T>): Promise<T>;
19
+ /** Resolves once every job handed in so far, and any handed in while waiting, has finished. Never rejects. */
20
+ whenIdle(): Promise<void>;
21
+ /** How many jobs are waiting or running. */
22
+ readonly pendingCount: number;
23
+ }
24
+ export declare function createSerialQueue(): SerialQueue;
@@ -0,0 +1,25 @@
1
+ export function createSerialQueue() {
2
+ /** Settles when the last job handed in has finished, however it ended. */
3
+ let tail = Promise.resolve();
4
+ let pendingCount = 0;
5
+ return {
6
+ run(job) {
7
+ pendingCount += 1;
8
+ // `then` turns a job that throws before it returns a promise into a rejection, like any other failure.
9
+ const result = tail.then(() => job());
10
+ const finished = () => {
11
+ pendingCount -= 1;
12
+ };
13
+ tail = result.then(finished, finished);
14
+ return result;
15
+ },
16
+ async whenIdle() {
17
+ // A job handed in while this waits moves `tail`, and the loop waits for that one too.
18
+ while (pendingCount > 0)
19
+ await tail;
20
+ },
21
+ get pendingCount() {
22
+ return pendingCount;
23
+ },
24
+ };
25
+ }
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@widgetic/creator",
3
- "version": "0.4.38",
3
+ "version": "0.4.39",
4
4
  "license": "SEE LICENSE IN LICENSE",
5
5
  "type": "module",
6
6
  "peerDependencies": {
7
7
  "@sveltejs/kit": "^2.20.0",
8
8
  "@widgetic/api-sdk": "^2.0.0",
9
9
  "@widgetic/cache-layer": "^0.1.2",
10
- "@widgetic/canvas": "^0.5.27",
10
+ "@widgetic/canvas": "^0.5.35",
11
11
  "@widgetic/chat": "^0.1.34",
12
12
  "@widgetic/design-system": "^0.5.15",
13
13
  "@widgetic/editor": "^4.0.10",
@@ -74,7 +74,7 @@
74
74
  "@types/node": "26.4.0",
75
75
  "@widgetic/api-sdk": "^2.0.0",
76
76
  "@widgetic/cache-layer": "^0.1.2",
77
- "@widgetic/canvas": "^0.5.27",
77
+ "@widgetic/canvas": "^0.5.35",
78
78
  "@widgetic/chat": "^0.1.34",
79
79
  "@widgetic/design-system": "^0.5.15",
80
80
  "@widgetic/dev-tools": "^0.3.0",