@widgetic/creator 0.4.40 → 0.4.42

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.
@@ -256,6 +256,7 @@
256
256
  publishTargetOf
257
257
  } from './host/hostControls.js';
258
258
  import { createSerialQueue } from './utils/serialQueue.js';
259
+ import { createHeldAutosave } from './utils/heldAutosave.js';
259
260
  import { widgetsToRestore } from './utils/widgetsToRestore.js';
260
261
 
261
262
  function resolveCreatorWorkflowStep(
@@ -615,10 +616,15 @@
615
616
  * it (the saves already on their way are waited for too). A page that is about to take the person away from the creator
616
617
  * (its Back arrow) calls this first. Never rejects: a save that fails stays unsaved on the canvas, and the copy kept in the
617
618
  * browser is not lost (see `handleCanvasAutoSave`).
619
+ *
620
+ * A change made in the first seconds after a canvas has loaded is held back by `handleCanvasAutoSave`, and the canvas's
621
+ * own flush resolves with it still held: it is waited out and sent here (at most a few seconds, the length of that hold),
622
+ * so "saved" is true when this resolves.
618
623
  */
619
624
  export async function flush(): Promise<void> {
620
625
  try {
621
626
  await canvasRef?.flushAutosave?.();
627
+ await heldCooldownAutosave.sendNow();
622
628
  await canvasSaveQueue.whenIdle();
623
629
  } catch (error) {
624
630
  console.warn('[CreatorApp] Host flush failed:', error);
@@ -869,6 +875,31 @@
869
875
  return partnerMode && err instanceof ResponseError && err.response?.status === 404;
870
876
  }
871
877
 
878
+ function canvasReadStatus(err: unknown): number | null {
879
+ return err instanceof ResponseError ? (err.response?.status ?? null) : null;
880
+ }
881
+
882
+ /** 401 and 403 are the answer. Asking again only delays the message on screen. */
883
+ function canvasReadWillNotChange(err: unknown): boolean {
884
+ const status = canvasReadStatus(err);
885
+ return status === 401 || status === 403 || saysCanvasIsMissing(err);
886
+ }
887
+
888
+ /** Stops the load retries and shows the API's own sentence. */
889
+ function stopAskingForCanvas(err: unknown, message: string): void {
890
+ if (canvasUnavailable) return;
891
+ canvasUnavailable = true;
892
+ clearCanvasLoadFailsafe();
893
+ clearCanvasHydrateRetry();
894
+ canvasApiLoadError = message;
895
+ const status = canvasReadStatus(err);
896
+ reportCanvasUnavailable({
897
+ canvasId: canvasId || null,
898
+ message,
899
+ code: status === 403 ? 'FORBIDDEN' : status === 401 ? 'UNAUTHORIZED' : 'NOT_FOUND',
900
+ });
901
+ }
902
+
872
903
  /** Credits left and days left, from the same billing status the publish gate uses. */
873
904
  async function refreshTrialCounter() {
874
905
  // An account matter: a visitor of a partner has no trial and no balance of their own to show.
@@ -967,7 +998,7 @@
967
998
  import type { DropdownItem } from './components/SelectorDropdown.svelte';
968
999
  import WidgetShapeLivePreviews from './components/WidgetShapeLivePreviews.svelte';
969
1000
  import HoverTooltip from './components/HoverTooltip.svelte';
970
- import VersionDropdownRow from './components/VersionDropdownRow.svelte';
1001
+ import VersionDropdownRow, { revealSelectedVersion } from './components/VersionDropdownRow.svelte';
971
1002
  // Type-only: erased at compile time, so the component's code is still
972
1003
  // dynamically imported below — this line exists so the ref types below can
973
1004
  // derive from the component's REAL class instead of the `any` a dynamic
@@ -3752,6 +3783,9 @@
3752
3783
  : $t('creator.codegen.widgetCodeAtCommitRefreshing', { commit: formatCommitShaShort(historicalSha) }),
3753
3784
  duration: 6000,
3754
3785
  });
3786
+ const alreadyCurrent = gitRollback?.alreadyCurrent === true || gitRollback?.already_current === true;
3787
+ const rebuiltFromFiles = gitRollback?.rebuilt === true;
3788
+ const previewWithoutGitlab = alreadyCurrent || rebuiltFromFiles;
3755
3789
  liveDesignValues = {};
3756
3790
  liveContentValues = {};
3757
3791
  liveContentItems = [];
@@ -3761,13 +3795,15 @@
3761
3795
  _isRestoringCheckpoint = true;
3762
3796
  const panelRef = panelWidgetId ? getWidgetDetailsRef(panelWidgetId) : widgetDetails;
3763
3797
  const scheduleBuildRetry = async () => {
3764
- const delays = [400, 2500, 5000, 8000];
3798
+ const delays = previewWithoutGitlab ? [400] : [400, 2500, 5000, 8000];
3765
3799
  for (let i = 0; i < delays.length; i++) {
3766
3800
  if (i > 0) await new Promise((r) => setTimeout(r, delays[i]));
3767
3801
  if (i === 0) suppressNextBuildFromRepoChatMessage = true;
3768
3802
  try {
3769
3803
  const activeRef = panelWidgetId ? getWidgetDetailsRef(panelWidgetId) : panelRef;
3770
- await activeRef?.triggerBuildFromRepo({ force: true });
3804
+ // The server already built from the files it read, or the branch was already
3805
+ // that version. Reloading the preview must not read GitLab again.
3806
+ await activeRef?.triggerBuildFromRepo(previewWithoutGitlab ? undefined : { force: true });
3771
3807
  const err = activeRef?.getPreviewError?.() ?? null;
3772
3808
  if (!err) {
3773
3809
  _isRestoringCheckpoint = false;
@@ -3797,8 +3833,14 @@
3797
3833
  console.warn('[Restore] The code was not rolled back', { widgetId: panelWidgetId, rollbackError });
3798
3834
  showToast('warning', gitlabLimited ? $t('creator.general.rateLimited') : $t('creator.version.failedToRestoreCheckpoint'), {
3799
3835
  description: rollbackError || $t('creator.version.codeWasNotRolledBack'),
3800
- duration: 9000,
3836
+ duration: gitlabLimited ? 20000 : 9000,
3801
3837
  });
3838
+ if (gitlabLimited && panelWidgetId) {
3839
+ getChatMethodsForWidget(panelWidgetId)?.addAssistantMessage?.(
3840
+ codegenFailureChatLine(rollbackError || 'GitLab rate limit reached (429), so nothing was changed. Wait a minute and try again.'),
3841
+ true,
3842
+ );
3843
+ }
3802
3844
  return null;
3803
3845
  } else {
3804
3846
  console.warn('[Chat→Backend] Git rollback not detected in response, refreshing preview anyway...');
@@ -5413,6 +5455,7 @@
5413
5455
  }
5414
5456
  }
5415
5457
  }
5458
+ if (selectedWidgetId) void postVisitorEntriesHost(selectedWidgetId);
5416
5459
  } catch (err: any) {
5417
5460
  console.error('[Compositions] Failed to load:', err);
5418
5461
  } finally {
@@ -5490,6 +5533,86 @@
5490
5533
  resolveLiveWidgetShapeIframe(widgetId)?.contentWindow?.postMessage(message, '*');
5491
5534
  }
5492
5535
 
5536
+ /** One lookup per composition. A failed lookup is dropped so the next preview can ask again. */
5537
+ const entriesHostByCompositionId = new Map<string, Promise<{ url: string; writeToken?: string } | null>>();
5538
+
5539
+ function entriesHostForComposition(compositionId: string): Promise<{ url: string; writeToken?: string } | null> {
5540
+ const cached = entriesHostByCompositionId.get(compositionId);
5541
+ if (cached) return cached;
5542
+ const root = (apiRoot || '').replace(/\/+$/, '');
5543
+ if (!root) return Promise.resolve(null);
5544
+ const pending = (async () => {
5545
+ try {
5546
+ const response = await fetch(`${root}/embed/compositions/${compositionId}`, { cache: 'reload' });
5547
+ if (!response.ok) {
5548
+ console.warn('[CreatorApp] Visitor entries address was not available', response.status);
5549
+ entriesHostByCompositionId.delete(compositionId);
5550
+ return null;
5551
+ }
5552
+ const body = await response.json();
5553
+ const data = body?.data ?? body;
5554
+ const writeToken = data?.entries?.writeToken || data?.entryWriteToken;
5555
+ return {
5556
+ url: `${root}/embed/compositions/${compositionId}/entries`,
5557
+ ...(typeof writeToken === 'string' && writeToken ? { writeToken } : {}),
5558
+ };
5559
+ } catch (error) {
5560
+ console.warn('[CreatorApp] Visitor entries address failed', error);
5561
+ entriesHostByCompositionId.delete(compositionId);
5562
+ return null;
5563
+ }
5564
+ })();
5565
+ entriesHostByCompositionId.set(compositionId, pending);
5566
+ return pending;
5567
+ }
5568
+
5569
+ /** The composition whose table a vote from this preview should fill. The open one, else the first. */
5570
+ async function compositionIdForVisitorEntries(widgetId: string): Promise<string | null> {
5571
+ const panel = getPanelDisplayState(widgetId);
5572
+ const openId = panel?.selectedComposition?.id;
5573
+ if (typeof openId === 'string' && openId) return openId;
5574
+ if (widgetId === selectedWidgetId && typeof selectedComposition?.id === 'string' && selectedComposition.id) {
5575
+ return selectedComposition.id;
5576
+ }
5577
+ if (!compositionsClient) return null;
5578
+ try {
5579
+ const res = await compositionsClient.getAllCompositions({ widgetId });
5580
+ const rows = ((res as { data?: unknown[] })?.data ?? []) as Array<Record<string, unknown>>;
5581
+ const mine = rows.filter((row) => (row.widget_id || row.widgetId) === widgetId);
5582
+ mine.sort((a, b) => {
5583
+ const aTime = new Date(String(a.createdAt ?? a.created_at ?? 0)).getTime();
5584
+ const bTime = new Date(String(b.createdAt ?? b.created_at ?? 0)).getTime();
5585
+ return aTime - bTime;
5586
+ });
5587
+ const id = mine[0]?.id;
5588
+ return typeof id === 'string' ? id : null;
5589
+ } catch (error) {
5590
+ console.warn('[CreatorApp] Could not read the composition for visitor entries', error);
5591
+ return null;
5592
+ }
5593
+ }
5594
+
5595
+ /** Tell the canvas preview, and the side preview, where a visitor entry is saved. */
5596
+ async function postVisitorEntriesHost(widgetId: string): Promise<void> {
5597
+ if (!widgetId) return;
5598
+ const compositionId = await compositionIdForVisitorEntries(widgetId);
5599
+ if (!compositionId) return;
5600
+ const entries = await entriesHostForComposition(compositionId);
5601
+ if (!entries) return;
5602
+ const message = {
5603
+ type: 'widgetic:host',
5604
+ version: 1,
5605
+ compositionId,
5606
+ context: null,
5607
+ values: null,
5608
+ mediaResolver: null,
5609
+ entries,
5610
+ };
5611
+ getWidgetDetailsRef(widgetId)?.sendMessageToPreview(message);
5612
+ resolveLiveWidgetShapeIframe(widgetId)?.contentWindow?.postMessage(message, '*');
5613
+ console.log('[CreatorApp] Told the preview where visitor entries are saved');
5614
+ }
5615
+
5493
5616
  /** Push composition overlay to a specific panel preview iframe. */
5494
5617
  function applyPanelCompositionToPreview(widgetId: string): void {
5495
5618
  const panelRef = getWidgetDetailsRef(widgetId);
@@ -6230,6 +6353,11 @@
6230
6353
  let canvasPrimaryWidgetId: string | null = null;
6231
6354
  /** Restore Checkpoint back to the sketch brings the drawing tools back until the next generation. */
6232
6355
  let sketchToolbarAfterRestore = false;
6356
+ /**
6357
+ * Single-widget canvases hide both bottom bars until the primary widget has been read.
6358
+ * Otherwise the drawing toolbar flashes, then the selector replaces it.
6359
+ */
6360
+ let singleWidgetChromeReady = false;
6233
6361
 
6234
6362
  function primaryWidgetHasGeneratedCode(): boolean {
6235
6363
  if (!canvasPrimaryWidgetId || isDraftConvertId(canvasPrimaryWidgetId)) return false;
@@ -6237,10 +6365,12 @@
6237
6365
  return !!(panel.hasGeneratedCode || panel.lastCommitId || panel.lastPublishedVersion != null);
6238
6366
  }
6239
6367
 
6240
- $: showDrawingTools = sketchToolbarAfterRestore || !(
6241
- panelDisplayRevision >= 0
6242
- && !!canvasPrimaryWidgetId
6243
- && primaryWidgetHasGeneratedCode()
6368
+ $: showDrawingTools = (multipleWidgetsAllowed || singleWidgetChromeReady) && (
6369
+ sketchToolbarAfterRestore || !(
6370
+ panelDisplayRevision >= 0
6371
+ && !!canvasPrimaryWidgetId
6372
+ && primaryWidgetHasGeneratedCode()
6373
+ )
6244
6374
  );
6245
6375
 
6246
6376
  function emitCreatorWireframeChanged() {
@@ -7563,6 +7693,7 @@
7563
7693
  // widget_id belonging to the previous canvas.
7564
7694
  routeCanvasId = entry.id;
7565
7695
  canvasPrimaryWidgetId = null;
7696
+ singleWidgetChromeReady = false;
7566
7697
  syncUrlCanvasId(entry.id);
7567
7698
 
7568
7699
  // Clear existing widgets and canvas visually
@@ -7718,11 +7849,7 @@
7718
7849
  * it later would write one canvas's shapes into another.
7719
7850
  */
7720
7851
  function discardPendingCooldownAutosave(): void {
7721
- if (cooldownAutosaveTimer) {
7722
- clearTimeout(cooldownAutosaveTimer);
7723
- cooldownAutosaveTimer = null;
7724
- }
7725
- pendingCooldownAutosaveJson = null;
7852
+ heldCooldownAutosave.discard();
7726
7853
  }
7727
7854
 
7728
7855
  function relinkSelectedWidgetShape(): void {
@@ -9362,9 +9489,9 @@
9362
9489
  publishHistoryResolvedForWidgetId: widget.id,
9363
9490
  });
9364
9491
  }
9365
- // Reconcile GitLab HEAD whenever we have a repo — unpublished widgets
9366
- // also need lastCommitId so Create preview is not stuck on "No Code Yet".
9367
- if (currentRepositoryId) {
9492
+ // The version menu is the database history. GitLab is asked for HEAD only when this
9493
+ // browser has no commit yet, so a first open on another machine can leave "No Code Yet".
9494
+ if (currentRepositoryId && !lastCommitId) {
9368
9495
  void reconcileWidgetHeadCommit(widget.id);
9369
9496
  }
9370
9497
  }
@@ -11823,16 +11950,12 @@ Requirements:
11823
11950
  setTimeout(() => alignGeneratedVersion(0), 1200);
11824
11951
  }
11825
11952
 
11826
- // Always reconcile GitLab HEAD after codegen (metadata.commitId can be missing/stale).
11827
- // Deferred — same window as the schema/history reloads above.
11953
+ // The generation already returned its commit. Ask GitLab for HEAD only when that commit is missing.
11828
11954
  if (generationWidgetId) {
11829
11955
  setTimeout(() => {
11830
11956
  void (async () => {
11831
11957
  try {
11832
- const fetchedHead = await fetchRepoHeadCommitSha(generationWidgetId);
11833
- // Prefer the codegen commit from the operation. GitLab HEAD can still
11834
- // be the previous live SHA for a few seconds — that used to clear
11835
- // pending publish until Widget Details was reopened.
11958
+ const fetchedHead = completedCommitSha ? null : await fetchRepoHeadCommitSha(generationWidgetId);
11836
11959
  const headSha = completedCommitSha || fetchedHead;
11837
11960
  if (!headSha) return;
11838
11961
  saveCommitIdForWidget(generationWidgetId, headSha);
@@ -12642,7 +12765,10 @@ Requirements:
12642
12765
  for (const frame of frames) {
12643
12766
  if (!(frame instanceof HTMLIFrameElement) || event.source !== frame.contentWindow) continue;
12644
12767
  const widgetId = frame.dataset.widgetId;
12645
- if (widgetId) postContentItemsToPreviewFrames(widgetId);
12768
+ if (widgetId) {
12769
+ postContentItemsToPreviewFrames(widgetId);
12770
+ void postVisitorEntriesHost(widgetId);
12771
+ }
12646
12772
  }
12647
12773
  };
12648
12774
  window.addEventListener('message', onShapeWidgetReady);
@@ -13118,6 +13244,10 @@ Requirements:
13118
13244
 
13119
13245
  /** The canvas iframe painted, so the chat is no longer waiting on a hidden side preview. */
13120
13246
  function noteShapePreviewShown(widgetId: string): void {
13247
+ // The widget listens after it mounts. The load event can be early, and a reload can miss
13248
+ // `widgetic:ready`, so the address is sent again once the frame has had time to listen.
13249
+ void postVisitorEntriesHost(widgetId);
13250
+ setTimeout(() => { void postVisitorEntriesHost(widgetId); }, 800);
13121
13251
  const status = getPanelDisplayState(widgetId).generateCodeStatus || '';
13122
13252
  const waitingOnPreview = /loading preview|building preview|generating code|code generation in progress|code saved/i.test(status);
13123
13253
  const generationRunning = !!generatingWidgetIds[widgetId] || !!previewUnblockedByWidgetId[widgetId];
@@ -16384,7 +16514,6 @@ async function readPublishHistoryForPanel(widgetId: string, opts: { silent?: boo
16384
16514
  lastPublishedVersion = getPanelState(widgetId).lastPublishedVersion;
16385
16515
  }
16386
16516
  }
16387
- void reconcileWidgetHeadCommit(widgetId);
16388
16517
  if (widgetId === focusedPanelWidgetId) {
16389
16518
  publishHistory = history;
16390
16519
  publishHistoryResolved = true;
@@ -17460,6 +17589,9 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17460
17589
  if (!embedded || canvasAdvancedFeatures || !canvasComponentReady) return;
17461
17590
  if (finalizingDraftConversions.size > 0) return;
17462
17591
  const primaryId = (canvasPrimaryWidgetId || '').trim();
17592
+ // The canvas JSON is loaded before the primary widget is known. Opening the draft chat in that gap
17593
+ // paints the empty suggestions, then the real conversation replaces them.
17594
+ if (!primaryId && !singleWidgetChromeReady) return;
17463
17595
  const targetId = primaryId || CANVAS_SKETCH_DRAFT_ID;
17464
17596
  const key = `${canvasId || 'pending'}:${targetId}`;
17465
17597
  if (simpleCanvasChatKey === key && openWidgetPanelIds.includes(targetId)) return;
@@ -17478,16 +17610,14 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17478
17610
  }
17479
17611
  }
17480
17612
 
17481
- $: if (embedded && !canvasAdvancedFeatures && canvasComponentReady && isCanvasStateLoaded) {
17482
- const simpleChatTarget = (canvasPrimaryWidgetId || '').trim() || CANVAS_SKETCH_DRAFT_ID;
17483
- if (!openWidgetPanelIds.includes(simpleChatTarget)) {
17484
- void ensureSimpleCanvasChat();
17485
- }
17613
+ $: if (embedded && !canvasAdvancedFeatures && canvasComponentReady && isCanvasStateLoaded && (singleWidgetChromeReady || !!(canvasPrimaryWidgetId || '').trim())) {
17614
+ void ensureSimpleCanvasChat();
17486
17615
  }
17487
17616
 
17488
17617
  async function handleCanvasReady() {
17489
17618
  markCanvasOpenStep('creator:canvas-ready');
17490
17619
  // console.log('[WidgetCreator] Canvas component ready');
17620
+ singleWidgetChromeReady = false;
17491
17621
  await waitForCanvasRef();
17492
17622
  canvasComponentReady = true;
17493
17623
  if (ignoreIncomingCanvasLoads) {
@@ -17500,12 +17630,16 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17500
17630
  placeSelectedWidgetShapeOnCanvas();
17501
17631
  }
17502
17632
  syncWidgetShapeLivePreviews();
17633
+ singleWidgetChromeReady = true;
17503
17634
  void ensureSimpleCanvasChat();
17504
17635
  return;
17505
17636
  }
17506
17637
  const { loaded, widgetIds: widgetIdsOnCanvas } = await tryLoadCanvasState();
17507
17638
  if (!loaded) {
17508
17639
  console.log('[WidgetCreator] Canvas ready — JSON load deferred until canvasId is resolved');
17640
+ if (isCanvasStateLoaded && (canvasPrimaryWidgetId || widgets.length === 0)) {
17641
+ singleWidgetChromeReady = true;
17642
+ }
17509
17643
  if (!isCanvasStateLoaded) {
17510
17644
  scheduleCanvasHydrateRetry('canvas ready before canvasId');
17511
17645
  }
@@ -17526,6 +17660,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17526
17660
  setTimeout(() => applyPrimarySelectionOnCanvas(primaryId), 80);
17527
17661
  });
17528
17662
  syncWidgetShapeLivePreviews();
17663
+ singleWidgetChromeReady = true;
17529
17664
  void ensureSimpleCanvasChat();
17530
17665
  }
17531
17666
 
@@ -17685,8 +17820,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17685
17820
  console.log('[CanvasDebug] getCanvas returned no canvasContent, retry', attempt + 1);
17686
17821
  } catch (getErr) {
17687
17822
  console.warn('[CanvasDebug] getCanvas failed, retry', attempt + 1, getErr);
17688
- // "No such canvas" is an answer, not a hiccup: asking again would only get it again.
17689
- if (saysCanvasIsMissing(getErr) || attempt >= maxCanvasReadAttempts - 1) throw getErr;
17823
+ // Access denied and "no such canvas" are answers. A pause and another read only delay the sentence.
17824
+ if (canvasReadWillNotChange(getErr) || attempt >= maxCanvasReadAttempts - 1) throw getErr;
17690
17825
  }
17691
17826
  if (attempt < maxCanvasReadAttempts - 1) {
17692
17827
  await new Promise((resolve) => setTimeout(resolve, 400 * (attempt + 1)));
@@ -17753,8 +17888,9 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17753
17888
  canvasApiLoadError = errMsg;
17754
17889
  // Partner mode: the API says the canvas does not exist for this visitor. It is not an empty canvas to start on
17755
17890
  // (the fallbacks below would call it one and say the creator is ready): the page is told, and that is the end.
17756
- if (saysCanvasIsMissing(err)) {
17757
- declareCanvasUnavailable(canvasId || null, errMsg);
17891
+ if (canvasReadWillNotChange(err)) {
17892
+ if (saysCanvasIsMissing(err)) declareCanvasUnavailable(canvasId || null, errMsg);
17893
+ else stopAskingForCanvas(err, errMsg);
17758
17894
  return emptyResult;
17759
17895
  }
17760
17896
  if (/timed out|failed to fetch|network|econnrefused|503|502|load canvases/i.test(errMsg)) {
@@ -17839,14 +17975,24 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17839
17975
  let lastResolvedAutosaveSequence = 0;
17840
17976
  /** The requests that write the canvas to the API, one at a time and in the order they were made (see `handleCanvasAutoSave`). */
17841
17977
  const canvasSaveQueue = createSerialQueue();
17978
+ /** How long after a canvas load we still defer (not drop) autosaves. */
17979
+ const CANVAS_COOLDOWN_AUTOSAVE_DELAY_MS = 3000;
17980
+ /**
17981
+ * The longest `flush()` waits for a canvas that has only just loaded to be quiet. A load's cooldown is 3 s and a restore of
17982
+ * the widget's shapes can start another just after, so twice that is a hold that really is over.
17983
+ */
17984
+ const CANVAS_COOLDOWN_FLUSH_MAX_WAIT_MS = 6000;
17842
17985
  /**
17843
17986
  * Trailing save deferred while `isLoadCooldownActive` is set.
17844
- * See {@link handleCanvasAutoSave}: dropping cooldown saves lost user edits.
17987
+ * See {@link handleCanvasAutoSave}: dropping cooldown saves lost user edits. `flush()` waits for it and sends it; a save
17988
+ * that goes through, or a switch of canvas, drops it (`utils/heldAutosave.ts`).
17845
17989
  */
17846
- let pendingCooldownAutosaveJson: string | null = null;
17847
- let cooldownAutosaveTimer: ReturnType<typeof setTimeout> | null = null;
17848
- /** How long after a canvas load we still defer (not drop) autosaves. */
17849
- const CANVAS_COOLDOWN_AUTOSAVE_DELAY_MS = 3000;
17990
+ const heldCooldownAutosave = createHeldAutosave({
17991
+ isHolding: () => isLoadCooldownActive,
17992
+ send: (json) => handleCanvasAutoSave(json),
17993
+ delayMs: CANVAS_COOLDOWN_AUTOSAVE_DELAY_MS,
17994
+ maxWaitMs: CANVAS_COOLDOWN_FLUSH_MAX_WAIT_MS
17995
+ });
17850
17996
 
17851
17997
  async function handleCanvasAutoSave(
17852
17998
  json: string | null,
@@ -17876,14 +18022,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17876
18022
  // overwrite freshly painted state, but a real move/resize a moment later is
17877
18023
  // persisted rather than silently discarded.
17878
18024
  if (!force && isLoadCooldownActive && !isUnmountSave) {
17879
- pendingCooldownAutosaveJson = json;
17880
- if (cooldownAutosaveTimer) clearTimeout(cooldownAutosaveTimer);
17881
- cooldownAutosaveTimer = setTimeout(() => {
17882
- cooldownAutosaveTimer = null;
17883
- const deferred = pendingCooldownAutosaveJson;
17884
- pendingCooldownAutosaveJson = null;
17885
- if (deferred) void handleCanvasAutoSave(deferred);
17886
- }, CANVAS_COOLDOWN_AUTOSAVE_DELAY_MS);
18025
+ heldCooldownAutosave.hold(json);
17887
18026
  return;
17888
18027
  }
17889
18028
 
@@ -17928,6 +18067,10 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17928
18067
  // console.log('[CanvasDebug] Allowing save: last object deleted by user (1→0)');
17929
18068
  }
17930
18069
 
18070
+ // This save goes through, so the one held back from the load's cooldown is older than it: sent after it, three seconds
18071
+ // on, it would write the older canvas over the newer one and ask the server twice for one run of changes.
18072
+ heldCooldownAutosave.discard();
18073
+
17931
18074
  lastSavedCanvasObjectCount = objectCount;
17932
18075
  try { creatorSessionStorage.setItem(CANVAS_OBJ_COUNT_KEY, String(objectCount)); } catch {}
17933
18076
  emitCreatorSaveState(false);
@@ -19097,7 +19240,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
19097
19240
  {#if canvasApiLoadError}
19098
19241
  <p class="font-semibold">{canvasUnavailable ? $t('creator.canvas.canvasUnavailable') : $t('creator.canvas.canvasShapesFailedToLoad')}</p>
19099
19242
  <p class="text-xs mt-1">{canvasApiLoadError}</p>
19100
- {#if !partnerMode}
19243
+ {#if !partnerMode && !canvasUnavailable}
19101
19244
  <p class="text-xs mt-1 opacity-90">If Supabase shows a billing/quota warning, upgrade or review billing — API reads may fail while the widget list still loads.</p>
19102
19245
  {/if}
19103
19246
  {:else}
@@ -19146,7 +19289,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
19146
19289
  void captureListThumbnail(widgetId, true);
19147
19290
  }}
19148
19291
  onSetPrimaryWidget={handleSetPrimaryWidget}
19149
- showElementSelector={!!canvasPrimaryWidgetId && !isDraftConvertId(canvasPrimaryWidgetId)}
19292
+ showElementSelector={(multipleWidgetsAllowed || singleWidgetChromeReady) && !!canvasPrimaryWidgetId && !isDraftConvertId(canvasPrimaryWidgetId)}
19150
19293
  showDrawingTools={showDrawingTools}
19151
19294
  elementSelectorActive={!!(canvasPrimaryWidgetId && selectorEnabledByWidgetId[canvasPrimaryWidgetId])}
19152
19295
  selectorGuide={{
@@ -20008,6 +20151,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
20008
20151
  {:else}
20009
20152
  <div
20010
20153
  class="wc-version-history-scroll flex flex-col gap-1 overflow-x-hidden {hasChatScroll ? 'overflow-y-auto' : 'overflow-y-visible'}"
20154
+ use:revealSelectedVersion
20011
20155
  style="{hasChatScroll ? 'max-height: 185px; margin-inline-end: -4px; padding-inline-end: 4px;' : 'max-height: none;'} scrollbar-width: thin; scrollbar-color: rgba(0,0,0,0.2) transparent;"
20012
20156
  >
20013
20157
  {#each [...ps.publishHistory].sort((a, b) => Number(a.version) - Number(b.version)) as record (record.id)}
@@ -29,6 +29,6 @@ interface Props {
29
29
  language?: string;
30
30
  languageLocked?: boolean;
31
31
  }
32
- declare const BrandKitPanel: import("svelte").Component<Props, {}, "brandKitEnabled" | "librariesEnabled" | "primary" | "secondary" | "title" | "sub" | "fonts" | "libraries" | "libraryGitUrl" | "libraryFileName" | "libraryUploads" | "fontUploads" | "language">;
32
+ declare const BrandKitPanel: import("svelte").Component<Props, {}, "sub" | "title" | "brandKitEnabled" | "librariesEnabled" | "primary" | "secondary" | "fonts" | "libraries" | "libraryGitUrl" | "libraryFileName" | "libraryUploads" | "fontUploads" | "language">;
33
33
  type BrandKitPanel = ReturnType<typeof BrandKitPanel>;
34
34
  export default BrandKitPanel;
@@ -10,6 +10,6 @@ interface Props {
10
10
  urlPlaceholder?: string;
11
11
  accept?: string;
12
12
  }
13
- declare const FileUrlSourceControl: import("svelte").Component<Props, {}, "fileName" | "fileContent" | "fileEncoding" | "url">;
13
+ declare const FileUrlSourceControl: import("svelte").Component<Props, {}, "url" | "fileName" | "fileContent" | "fileEncoding">;
14
14
  type FileUrlSourceControl = ReturnType<typeof FileUrlSourceControl>;
15
15
  export default FileUrlSourceControl;
@@ -1,3 +1,28 @@
1
+ <script lang="ts" module>
2
+ /** Puts the selected row in view inside this menu only. Does not move the chat or the page. */
3
+ export function revealSelectedVersion(node: HTMLElement) {
4
+ const reveal = () => {
5
+ const selected = node.querySelector('[aria-selected="true"]');
6
+ if (!(selected instanceof HTMLElement)) return;
7
+ const rowRect = selected.getBoundingClientRect();
8
+ const viewRect = node.getBoundingClientRect();
9
+ if (rowRect.height === 0 || viewRect.height === 0) return;
10
+ if (rowRect.top >= viewRect.top && rowRect.bottom <= viewRect.bottom) return;
11
+ const delta = rowRect.top - viewRect.top - (viewRect.height - rowRect.height) / 2;
12
+ node.scrollTop += delta;
13
+ };
14
+ const frame = requestAnimationFrame(reveal);
15
+ const observer = new MutationObserver(() => requestAnimationFrame(reveal));
16
+ observer.observe(node, { childList: true });
17
+ return {
18
+ destroy() {
19
+ cancelAnimationFrame(frame);
20
+ observer.disconnect();
21
+ },
22
+ };
23
+ }
24
+ </script>
25
+
1
26
  <script lang="ts">
2
27
  /**
3
28
  * VersionDropdownRow — the ONE row used by BOTH version dropdowns (chat
@@ -1,3 +1,7 @@
1
+ /** Puts the selected row in view inside this menu only. Does not move the chat or the page. */
2
+ export declare function revealSelectedVersion(node: HTMLElement): {
3
+ destroy(): void;
4
+ };
1
5
  interface Props {
2
6
  /** Version label shown in the first cell (e.g. "v2"). */
3
7
  versionLabel: string;
@@ -100,7 +100,7 @@ declare const WidgetDetails: $$__sveltets_2_IsomorphicComponent<{
100
100
  /** Stacking order when multiple Widget Details panels are open. */ panelZIndex?: number;
101
101
  /** Cascade offset index (0 = centered, 1+ = shifted down-right). */ panelCascadeIndex?: number;
102
102
  /** False when another panel has keyboard/chat focus. */ isFocusedPanel?: boolean;
103
- currentStep?: "create" | "edit" | "embed";
103
+ currentStep?: "embed" | "create" | "edit";
104
104
  /**
105
105
  * Canvas Creator is code-only (chat + preview). Edit/Embed header steps stay
106
106
  * off until composition editing lives on /composition. Keep the Edit/Embed
@@ -7,7 +7,7 @@
7
7
  import { Checked } from '@widgetic/design-system/icons';
8
8
  import { Portal } from '@widgetic/design-system';
9
9
  import HoverTooltip from './HoverTooltip.svelte';
10
- import VersionDropdownRow from './VersionDropdownRow.svelte';
10
+ import VersionDropdownRow, { revealSelectedVersion } from './VersionDropdownRow.svelte';
11
11
  import WidgetElementSelector from './WidgetElementSelector.svelte';
12
12
  import type { SelectedWidgetElementReference } from '../utils/widgetElementSelector';
13
13
  import { errorLabel, useCreatorLanguage } from '../i18n/index.js';
@@ -1239,6 +1239,7 @@
1239
1239
  >
1240
1240
  <div
1241
1241
  class="widget-shape-version-scroll flex flex-col gap-1 overflow-x-hidden {hasScroll ? 'overflow-y-auto' : 'overflow-y-visible'}"
1242
+ use:revealSelectedVersion
1242
1243
  style="{hasScroll ? 'max-height: 185px; margin-inline-end: -4px; padding-inline-end: 4px;' : 'max-height: none;'} scrollbar-width: thin; scrollbar-color: rgba(0,0,0,0.2) transparent;"
1243
1244
  >
1244
1245
  {#each versionOptions as option (option.id)}
@@ -593,9 +593,7 @@ export declare const CREATOR_CATALOGS: {
593
593
  readonly 'chat.messages.restore': "Restore Checkpoint";
594
594
  readonly 'chat.messages.restoreTitle': "Restore widget code to this prompt's commit";
595
595
  readonly 'chat.messages.alreadyHead': "This checkpoint is already HEAD";
596
- readonly 'chat.messages.rateGroup': "Rate this version";
597
- readonly 'chat.messages.rateUp': "This version is good";
598
- readonly 'chat.messages.rateDown': "This version is not good";
596
+ readonly 'chat.messages.showSuggestions': "Show suggestions";
599
597
  readonly 'chat.messages.version': "Version {number}";
600
598
  readonly 'chat.messages.restoredFrom': "Restored from {label}";
601
599
  readonly 'chat.messages.previousVersion': "a previous version";
@@ -706,6 +704,7 @@ export declare const CREATOR_CATALOGS: {
706
704
  readonly 'canvas.state.loading': "Loading canvas\u2026";
707
705
  readonly 'canvas.state.initFailed': "Canvas failed to initialize.";
708
706
  readonly 'canvas.error.imageFromUrl': "Failed to load image from URL. Make sure the URL is correct and allows cross-origin requests.";
707
+ readonly 'canvas.defaults.text': "Hello World!";
709
708
  readonly 'canvas.defaults.textBox': "Type here";
710
709
  readonly 'canvas.defaults.frameLabel': "Frame";
711
710
  readonly 'canvas.defaults.untitledFrame': "Untitled Frame";
@@ -727,7 +726,6 @@ export declare const CREATOR_CATALOGS: {
727
726
  readonly 'canvas.tool.circle': "Circle";
728
727
  readonly 'canvas.tool.frame': "Frame";
729
728
  readonly 'canvas.tool.text': "Text";
730
- readonly 'canvas.tool.selector': "Selector";
731
729
  readonly 'canvas.tool.image': "Image";
732
730
  readonly 'canvas.tool.video': "Video";
733
731
  readonly 'canvas.tool.shapes': "Shapes";
@@ -825,7 +823,6 @@ export declare const CREATOR_CATALOGS: {
825
823
  readonly 'canvas.zoom.gridLabel': "Toggle grid";
826
824
  readonly 'canvas.zoom.panTitle': "Hand / Pan [H]";
827
825
  readonly 'canvas.zoom.panLabel': "Hand / pan tool";
828
- readonly 'canvas.zoom.panBanner': "Dragging the canvas";
829
826
  readonly 'canvas.zoom.outTitle': "Zoom Out [Ctrl/Cmd] + [\u2212]";
830
827
  readonly 'canvas.zoom.outLabel': "Zoom out";
831
828
  readonly 'canvas.zoom.inTitle': "Zoom In [Ctrl/Cmd] + [+]";
@@ -0,0 +1,65 @@
1
+ /**
2
+ * The save that a canvas holds back for a few seconds after it has loaded.
3
+ *
4
+ * Opening a canvas draws its shapes one by one, and every one of them fires an event that looks like a change made by the person.
5
+ * For a few seconds after a load the creator therefore does not send a save at once (`isLoadCooldownActive` in `CreatorApp.svelte`):
6
+ * dropping it would lose a real edit made in those seconds, so it keeps the newest one and sends it when the canvas is quiet again.
7
+ * This module is that keeper. It was a timer and a variable in the component, and it had two faults that a person only meets when
8
+ * they change something in the first seconds:
9
+ *
10
+ * - **A save that goes through did not make the held one stale.** The held one was sent three seconds later all the same: a second
11
+ * request for one run of changes, and an older snapshot written after a newer one. {@link HeldAutosave.discard} is what a save
12
+ * that goes through calls, so the held one is forgotten.
13
+ * - **A page that asked for a save now waited for nothing.** `flush()` resolves when the canvas's own save has resolved, and a save
14
+ * that is held resolves at once: the page was told "saved" with the canvas still on the shelf. {@link HeldAutosave.sendNow} waits
15
+ * for the hold to end (a snapshot taken in the middle of a load can be half a canvas), sends the held save and resolves when the
16
+ * save is done.
17
+ *
18
+ * Kept free of Svelte and of the DOM (the clock can be replaced) so that Node can test it.
19
+ */
20
+ /** The clock the keeper reads and sets timers with. Tests pass one they move by hand. */
21
+ export interface HeldAutosaveClock {
22
+ /** Milliseconds, from any fixed point. */
23
+ now(): number;
24
+ /** Calls `callback` once, `delayMs` from now. Returns what {@link clearTimer} needs to take it back. */
25
+ setTimer(callback: () => void, delayMs: number): unknown;
26
+ clearTimer(handle: unknown): void;
27
+ }
28
+ export interface HeldAutosaveOptions {
29
+ /** True while saves are held back (a canvas has just loaded). Read whenever it matters. */
30
+ isHolding: () => boolean;
31
+ /**
32
+ * Makes the save of the canvas (the component's `handleCanvasAutoSave`). Called while the hold is still on, it holds the
33
+ * save again, which is how a hold that lasts longer than the timer keeps the save until it is over.
34
+ */
35
+ send: (json: string) => Promise<unknown> | void;
36
+ /** How long the held save waits, after the last one handed over, before it is sent by itself. */
37
+ delayMs: number;
38
+ /** The longest {@link HeldAutosave.sendNow} waits for the hold to end. A hold that lasts longer leaves the save to its timer. */
39
+ maxWaitMs: number;
40
+ /** Told what went wrong or was left undone. Defaults to `console.warn`. */
41
+ warn?: (message: string, error?: unknown) => void;
42
+ /** Defaults to the real one. */
43
+ clock?: HeldAutosaveClock;
44
+ }
45
+ export interface HeldAutosave {
46
+ /**
47
+ * A save came while saves are held back. Keeps it in place of the one held (the canvas is saved whole, so the newest holds the
48
+ * changes of the older) and starts the wait again.
49
+ */
50
+ hold(json: string): void;
51
+ /**
52
+ * Forgets the held save: a newer one is going out, or the canvas it belongs to is not the one on the screen any more. A save
53
+ * that is already on its way is left alone.
54
+ */
55
+ discard(): void;
56
+ /**
57
+ * Sends the held save once the hold is over, and resolves when that save is done (when the one the timer already sent is done,
58
+ * if the timer was first). Resolves at once when nothing is held and nothing is on its way. Never rejects. A hold that outlasts
59
+ * `maxWaitMs` resolves it with the save still held: its timer sends it.
60
+ */
61
+ sendNow(): Promise<void>;
62
+ /** Whether a save is held. */
63
+ readonly isHeld: boolean;
64
+ }
65
+ export declare function createHeldAutosave(options: HeldAutosaveOptions): HeldAutosave;
@@ -0,0 +1,111 @@
1
+ /**
2
+ * The save that a canvas holds back for a few seconds after it has loaded.
3
+ *
4
+ * Opening a canvas draws its shapes one by one, and every one of them fires an event that looks like a change made by the person.
5
+ * For a few seconds after a load the creator therefore does not send a save at once (`isLoadCooldownActive` in `CreatorApp.svelte`):
6
+ * dropping it would lose a real edit made in those seconds, so it keeps the newest one and sends it when the canvas is quiet again.
7
+ * This module is that keeper. It was a timer and a variable in the component, and it had two faults that a person only meets when
8
+ * they change something in the first seconds:
9
+ *
10
+ * - **A save that goes through did not make the held one stale.** The held one was sent three seconds later all the same: a second
11
+ * request for one run of changes, and an older snapshot written after a newer one. {@link HeldAutosave.discard} is what a save
12
+ * that goes through calls, so the held one is forgotten.
13
+ * - **A page that asked for a save now waited for nothing.** `flush()` resolves when the canvas's own save has resolved, and a save
14
+ * that is held resolves at once: the page was told "saved" with the canvas still on the shelf. {@link HeldAutosave.sendNow} waits
15
+ * for the hold to end (a snapshot taken in the middle of a load can be half a canvas), sends the held save and resolves when the
16
+ * save is done.
17
+ *
18
+ * Kept free of Svelte and of the DOM (the clock can be replaced) so that Node can test it.
19
+ */
20
+ /** How often {@link HeldAutosave.sendNow} looks again at whether the hold is over. */
21
+ const POLL_INTERVAL_MS = 50;
22
+ const realClock = {
23
+ now: () => Date.now(),
24
+ setTimer: (callback, delayMs) => setTimeout(callback, delayMs),
25
+ clearTimer: (handle) => clearTimeout(handle)
26
+ };
27
+ export function createHeldAutosave(options) {
28
+ const clock = options.clock ?? realClock;
29
+ const warn = options.warn ??
30
+ ((message, error) => {
31
+ if (error === undefined)
32
+ console.warn(message);
33
+ else
34
+ console.warn(message, error);
35
+ });
36
+ /** The newest save handed over while the hold was on, if no newer one has gone out since. */
37
+ let heldJson = null;
38
+ let timerHandle = null;
39
+ /** The save this keeper sent and that is not done yet. It never rejects. */
40
+ let sending = null;
41
+ function stopTimer() {
42
+ if (timerHandle === null)
43
+ return;
44
+ clock.clearTimer(timerHandle);
45
+ timerHandle = null;
46
+ }
47
+ /** Sends what is held, now, whatever the hold. Resolves when that save is done; with nothing held, when the one on its way is. */
48
+ function sendHeld() {
49
+ stopTimer();
50
+ const json = heldJson;
51
+ heldJson = null;
52
+ if (json === null)
53
+ return sending ?? Promise.resolve();
54
+ let outcome;
55
+ try {
56
+ outcome = Promise.resolve(options.send(json));
57
+ }
58
+ catch (error) {
59
+ warn('[heldAutosave] the held save failed', error);
60
+ return Promise.resolve();
61
+ }
62
+ const running = outcome
63
+ .then(() => undefined, (error) => warn('[heldAutosave] the held save failed', error))
64
+ .then(() => {
65
+ if (sending === running)
66
+ sending = null;
67
+ });
68
+ sending = running;
69
+ return running;
70
+ }
71
+ function hold(json) {
72
+ heldJson = json;
73
+ stopTimer();
74
+ timerHandle = clock.setTimer(() => {
75
+ timerHandle = null;
76
+ void sendHeld();
77
+ }, options.delayMs);
78
+ }
79
+ function discard() {
80
+ stopTimer();
81
+ heldJson = null;
82
+ }
83
+ async function sendNow() {
84
+ const startedAt = clock.now();
85
+ // The hold is waited out: the events a canvas fires while it loads look like changes, and a save taken in the middle of
86
+ // them can be half a canvas written over the whole one.
87
+ while (heldJson !== null && options.isHolding()) {
88
+ if (clock.now() - startedAt >= options.maxWaitMs) {
89
+ warn('[heldAutosave] the canvas is still loading: the save it holds goes out when the hold is over');
90
+ return;
91
+ }
92
+ await new Promise((resolve) => {
93
+ clock.setTimer(resolve, POLL_INTERVAL_MS);
94
+ });
95
+ }
96
+ if (heldJson !== null) {
97
+ await sendHeld();
98
+ }
99
+ else if (sending) {
100
+ await sending;
101
+ }
102
+ }
103
+ return {
104
+ hold,
105
+ discard,
106
+ sendNow,
107
+ get isHeld() {
108
+ return heldJson !== null;
109
+ }
110
+ };
111
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@widgetic/creator",
3
- "version": "0.4.40",
3
+ "version": "0.4.42",
4
4
  "license": "SEE LICENSE IN LICENSE",
5
5
  "type": "module",
6
6
  "peerDependencies": {