@widgetic/creator 0.4.16 → 0.4.17

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.
@@ -855,7 +855,7 @@
855
855
  let widgetDetailsOpenTargetId: string | null = null;
856
856
 
857
857
  // Lightweight static imports from canvas (excludes Canvas.svelte — 10K+ lines)
858
- import { Tooltip } from '@widgetic/canvas/components';
858
+ import { Tooltip, CanvasBoardPlaceholder } from '@widgetic/canvas/components';
859
859
  // WidgetConversionPayload lives on the canvas root export (re-exported from
860
860
  // ./canvas); the components barrel only carries the input controls. Type-only
861
861
  // import, so the 10K-line Canvas.svelte still never loads.
@@ -881,6 +881,15 @@
881
881
  type DesignIntentClassification
882
882
  } from './utils/designIntentTelemetry';
883
883
 
884
+ /** Open-time marks (DevTools Performance panel, or `performance.getEntriesByType('mark')`). */
885
+ function markCanvasOpenStep(stepName: string): void {
886
+ try {
887
+ performance.mark(stepName);
888
+ } catch {
889
+ // Marks are diagnostics only.
890
+ }
891
+ }
892
+
884
893
  // Eagerly initiate canvas chunk fetching at script evaluation (parallel with DOM parsing)
885
894
  const canvasModulePromise = typeof window !== 'undefined' ? import('@widgetic/canvas') : null;
886
895
 
@@ -944,6 +953,7 @@
944
953
  mountUploadAbortController = new AbortController();
945
954
  if (canvasModulePromise) {
946
955
  const canvasModule = await canvasModulePromise;
956
+ markCanvasOpenStep('creator:canvas-module-loaded');
947
957
  // Installed before the canvas mounts so the first save already externalizes
948
958
  installCanvasThumbnailStore(canvasModule);
949
959
  // The canvas keeps the visitor's saved colors where the creator keeps its own memory: the browser's
@@ -1009,6 +1019,8 @@
1009
1019
  import {
1010
1020
  saveCanvasState,
1011
1021
  readCanvasState,
1022
+ saveCanvasWidgetList,
1023
+ readCanvasWidgetList,
1012
1024
  saveActiveGeneration,
1013
1025
  readActiveGeneration,
1014
1026
  clearActiveGeneration,
@@ -5835,6 +5847,7 @@
5835
5847
  id: targetCanvasId,
5836
5848
  updateCanvasRequest: { primaryWidgetId: widgetId }
5837
5849
  });
5850
+ canvasRecordReads.delete(targetCanvasId);
5838
5851
  } catch (err) {
5839
5852
  console.warn('[CreatorApp] Failed to save primary_widget_id:', err);
5840
5853
  }
@@ -6613,6 +6626,47 @@
6613
6626
  ]);
6614
6627
  }
6615
6628
 
6629
+ /**
6630
+ * One read of a canvas record per open. The JSON load and the primary-widget lookups run from two start paths
6631
+ * (loadCurrentCanvas and handleCanvasReady); each used to read the canvas again. A read is shared for
6632
+ * CANVAS_RECORD_SHARE_MS, then the next caller reads fresh.
6633
+ */
6634
+ const CANVAS_RECORD_SHARE_MS = 15000;
6635
+ type CanvasRecordRead = { status: number; record: Record<string, any> | null };
6636
+ const canvasRecordReads = new Map<string, { startedAt: number; read: Promise<CanvasRecordRead> }>();
6637
+
6638
+ function forgetCanvasRecordReads(): void {
6639
+ canvasRecordReads.clear();
6640
+ }
6641
+
6642
+ function readCanvasRecord(targetCanvasId: string, options: { fresh?: boolean } = {}): Promise<CanvasRecordRead> {
6643
+ const shared = canvasRecordReads.get(targetCanvasId);
6644
+ if (!options.fresh && shared && Date.now() - shared.startedAt < CANVAS_RECORD_SHARE_MS) return shared.read;
6645
+ const read = (async (): Promise<CanvasRecordRead> => {
6646
+ if (!canvasesClient) throw new Error('Canvases API client is not configured');
6647
+ const response = await withCanvasApiTimeout(canvasesClient.getCanvasRaw({ id: targetCanvasId }), 'getCanvas');
6648
+ // A 304 has no body; the caller keeps what it already painted.
6649
+ if (response.raw.status === 304) return { status: 304, record: null };
6650
+ const body = await response.raw.json();
6651
+ const record = (body?.data || body) ?? null;
6652
+ announceCanvasName(targetCanvasId, record);
6653
+ return { status: response.raw.status, record };
6654
+ })();
6655
+ canvasRecordReads.set(targetCanvasId, { startedAt: Date.now(), read });
6656
+ // A failed read is not shared: the next caller asks again.
6657
+ read.catch(() => {
6658
+ if (canvasRecordReads.get(targetCanvasId)?.read === read) canvasRecordReads.delete(targetCanvasId);
6659
+ });
6660
+ return read;
6661
+ }
6662
+
6663
+ /** The site header shows the canvas name; it reads it from here instead of asking the API again. */
6664
+ function announceCanvasName(targetCanvasId: string, record: Record<string, any> | null): void {
6665
+ const name = String(record?.persistenceKey || record?.persistence_key || '').trim();
6666
+ if (!name) return;
6667
+ announceToSite('widgetic:creator-canvas-name', { canvasId: targetCanvasId, name });
6668
+ }
6669
+
6616
6670
  function clearCanvasHydrateRetry() {
6617
6671
  if (canvasHydrateRetryTimer) {
6618
6672
  clearTimeout(canvasHydrateRetryTimer);
@@ -6949,8 +7003,8 @@
6949
7003
 
6950
7004
  // Reload canvas shapes first, then widget metadata for the new canvas
6951
7005
  try {
6952
- lastWidgetsCanvasId = null;
6953
- isLoadingWidgetsOnce = false;
7006
+ forgetWidgetListRead();
7007
+ forgetCanvasRecordReads();
6954
7008
  const { widgetIds: widgetIdsOnCanvas } = await tryLoadCanvasState();
6955
7009
  await syncWidgetsWithCanvas(widgetIdsOnCanvas);
6956
7010
  } catch (err) {
@@ -7430,9 +7484,19 @@
7430
7484
  deleteCanvasTarget = null;
7431
7485
  }
7432
7486
 
7433
- let lastWidgetsCanvasId: string | null = null;
7434
- let isLoadingWidgetsOnce = false;
7435
- async function loadWidgetsForCanvas() {
7487
+ /**
7488
+ * The widget list read for the open canvas. Both start paths (loadCurrentCanvas and handleCanvasReady) need it;
7489
+ * they wait on this one read. A refresh, a retry or another canvas forgets it and reads again.
7490
+ */
7491
+ let widgetListReadCanvasId: string | null = null;
7492
+ let widgetListRead: Promise<boolean> | null = null;
7493
+
7494
+ function forgetWidgetListRead(): void {
7495
+ widgetListReadCanvasId = null;
7496
+ widgetListRead = null;
7497
+ }
7498
+
7499
+ async function loadWidgetsForCanvas(): Promise<void> {
7436
7500
  // if no canvas id, return
7437
7501
  if (!canvasId) {
7438
7502
  // console.log('Widget Creator: loadWidgetsForCanvas: No canvas id, returning');
@@ -7442,13 +7506,23 @@
7442
7506
  isLoadingWidgets = false;
7443
7507
  return;
7444
7508
  }
7509
+ if (widgetListRead && widgetListReadCanvasId === canvasId) {
7510
+ await widgetListRead;
7511
+ return;
7512
+ }
7513
+ const listCanvasId = canvasId;
7514
+ const read = readAndApplyWidgetList(listCanvasId);
7515
+ widgetListReadCanvasId = listCanvasId;
7516
+ widgetListRead = read;
7517
+ const loaded = await read;
7518
+ // A failed read is not kept, so the next caller asks again.
7519
+ if (!loaded && widgetListRead === read) forgetWidgetListRead();
7520
+ }
7445
7521
 
7446
- // if canvas id, load the widgets for the canvas
7447
- // console.log('Widget Creator: loadWidgetsForCanvas:', canvasId);
7522
+ async function readAndApplyWidgetList(listCanvasId: string): Promise<boolean> {
7523
+ // console.log('Widget Creator: loadWidgetsForCanvas:', listCanvasId);
7524
+ let networkListSettled = false;
7448
7525
  try {
7449
- if (isLoadingWidgetsOnce && lastWidgetsCanvasId === canvasId) return;
7450
- isLoadingWidgetsOnce = true;
7451
- lastWidgetsCanvasId = canvasId;
7452
7526
  isLoadingWidgets = true;
7453
7527
  widgetsError = null;
7454
7528
  if (!$userSession?.jwt) {
@@ -7459,7 +7533,13 @@
7459
7533
  // which the generated model drops. A refused request or an error answer
7460
7534
  // is thrown (see readWidgetList), so the catch below shows it and
7461
7535
  // saysCanvasIsMissing can read a 404 in partner mode.
7462
- const fetched = await readWidgetList(canvasId);
7536
+ // The request starts first; the cached list is read beside it and shown only until it answers.
7537
+ const networkListPromise = readWidgetList(listCanvasId);
7538
+ void showCachedWidgetList(listCanvasId, () => networkListSettled);
7539
+ const fetched = await networkListPromise;
7540
+ networkListSettled = true;
7541
+ markCanvasOpenStep('creator:widget-list-ready');
7542
+ saveCanvasWidgetList(listCanvasId, fetched);
7463
7543
 
7464
7544
  const previousById = new Map(
7465
7545
  widgets.filter((w) => w.id).map((w) => [w.id as string, w]),
@@ -7537,6 +7617,7 @@
7537
7617
  selectedWidgetId = null;
7538
7618
  saveSelectedWidgetId(null); // Clear localStorage if no widgets
7539
7619
  }
7620
+ return true;
7540
7621
  } catch (error) {
7541
7622
  console.error('Widget Creator: Failed to load widgets for canvas:', error);
7542
7623
  const defaultError = $t('creator.widget.failedToLoadWidgets');
@@ -7552,9 +7633,34 @@
7552
7633
  duration: 5000
7553
7634
  });
7554
7635
  }
7636
+ return false;
7555
7637
  } finally {
7638
+ networkListSettled = true;
7556
7639
  isLoadingWidgets = false;
7557
- isLoadingWidgetsOnce = false;
7640
+ }
7641
+ }
7642
+
7643
+ /**
7644
+ * Second open of a canvas: show the widget list saved last time, so names and
7645
+ * thumbnails on the board do not wait for the network. Needs enableLocalCache.
7646
+ */
7647
+ async function showCachedWidgetList(listCanvasId: string, hasNetworkSettled: () => boolean): Promise<void> {
7648
+ if (!isLocalCacheEnabled()) return;
7649
+ try {
7650
+ const cachedList = (await readCanvasWidgetList(listCanvasId)) as WidgetSummary[] | null;
7651
+ if (!cachedList?.length || hasNetworkSettled() || canvasId !== listCanvasId) return;
7652
+ // Something already put widgets of this canvas on screen; the network list will replace them.
7653
+ const alreadyShowsThisCanvas = widgets.some(
7654
+ (widget) => widgetCanvasIdOf(widget as { canvasId?: string | null; canvas_id?: string | null }) === listCanvasId,
7655
+ );
7656
+ if (alreadyShowsThisCanvas) return;
7657
+ widgets = sortWidgetSummaries(cachedList);
7658
+ markCanvasOpenStep('creator:widget-list-from-cache');
7659
+ widgetNamesRevision += 1;
7660
+ backfillWidgetShapeMetadata();
7661
+ syncWidgetShapeLivePreviews();
7662
+ } catch (error) {
7663
+ console.warn('[WidgetCreator] Cached widget list could not be read:', error);
7558
7664
  }
7559
7665
  }
7560
7666
 
@@ -7986,10 +8092,10 @@
7986
8092
  async function readPrimaryWidgetIdForCanvas(targetCanvasId: string): Promise<string | null> {
7987
8093
  if (!canvasesClient || !targetCanvasId?.trim()) return null;
7988
8094
  try {
7989
- const canvasRecord = await canvasesClient.getCanvas({ id: targetCanvasId });
7990
- const record =
7991
- (canvasRecord as { data?: Record<string, unknown> })?.data ??
7992
- (canvasRecord as unknown as Record<string, unknown>);
8095
+ const canvasRead = await readCanvasRecord(targetCanvasId);
8096
+ // 304: nothing new about this canvas; keep the primary already known.
8097
+ if (!canvasRead.record) return canvasPrimaryWidgetId || null;
8098
+ const record = canvasRead.record;
7993
8099
  const raw =
7994
8100
  (record as { primaryWidgetId?: unknown })?.primaryWidgetId ??
7995
8101
  (record as { primary_widget_id?: unknown })?.primary_widget_id ??
@@ -8219,13 +8325,14 @@
8219
8325
 
8220
8326
  function handleRefreshWidgets() {
8221
8327
  // console.log('Widget Creator: Refresh widgets clicked');
8222
- lastWidgetsCanvasId = null;
8223
- isLoadingWidgetsOnce = false;
8328
+ forgetWidgetListRead();
8224
8329
  void syncWidgetsWithCanvas();
8225
8330
  }
8226
8331
 
8227
8332
  function retryLoadCanvas() {
8228
8333
  console.log('Widget Creator: Retry loading canvas');
8334
+ forgetWidgetListRead();
8335
+ forgetCanvasRecordReads();
8229
8336
  isLoadingCanvasOnce = false;
8230
8337
  isCanvasStateLoaded = false;
8231
8338
  canvasHydrateRetryCount = 0;
@@ -16094,13 +16201,29 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16094
16201
  return !!getWidgetById(widgetId);
16095
16202
  }
16096
16203
 
16204
+ /**
16205
+ * The canvas calls onReady from its own mount, before `bind:this` has filled canvasRef.
16206
+ * Loading then would be skipped and wait for the retry timer (~0.9s), so wait for the ref.
16207
+ */
16208
+ async function waitForCanvasRef(): Promise<boolean> {
16209
+ if (canvasRef) return true;
16210
+ await tick();
16211
+ for (let frame = 0; frame < 3 && !canvasRef; frame++) {
16212
+ await new Promise((resolve) => requestAnimationFrame(() => resolve(null)));
16213
+ }
16214
+ if (!canvasRef) console.warn('[WidgetCreator] Canvas ready, but its ref is still empty');
16215
+ return !!canvasRef;
16216
+ }
16217
+
16097
16218
  /**
16098
16219
  * Called when WidgeticCanvas is initialized and ready.
16099
16220
  * Marks the canvas as ready; actual state loading happens in loadCanvasState()
16100
16221
  * which is called after loadCurrentCanvas() resolves canvasId.
16101
16222
  */
16102
16223
  async function handleCanvasReady() {
16224
+ markCanvasOpenStep('creator:canvas-ready');
16103
16225
  // console.log('[WidgetCreator] Canvas component ready');
16226
+ await waitForCanvasRef();
16104
16227
  canvasComponentReady = true;
16105
16228
  if (ignoreIncomingCanvasLoads) {
16106
16229
  // console.log('[WidgetCreator] Canvas ready — skipping JSON hydrate (new widget)');
@@ -16155,6 +16278,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16155
16278
  canvasLoadFailsafeArmedForId = null;
16156
16279
  }
16157
16280
  function markCanvasStateLoaded() {
16281
+ if (!isCanvasStateLoaded) markCanvasOpenStep('creator:canvas-state-loaded');
16158
16282
  isCanvasStateLoaded = true;
16159
16283
  canvasHydrateRetryCount = 0;
16160
16284
  clearCanvasHydrateRetry();
@@ -16233,6 +16357,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16233
16357
  localCachedJson = (await readCanvasState(canvasId)) ?? (() => {
16234
16358
  try { return creatorStorage.getItem(getCanvasStorageKey()); } catch { return null; }
16235
16359
  })();
16360
+ markCanvasOpenStep(localCachedJson ? 'creator:canvas-cache-hit' : 'creator:canvas-cache-miss');
16236
16361
  if (localCachedJson && canvasRef) {
16237
16362
  const parsed = JSON.parse(localCachedJson);
16238
16363
  const objects = parsed?.canvas?.objects ?? parsed?.objects ?? [];
@@ -16262,13 +16387,11 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16262
16387
  // Another read has already found out there is no such canvas for this visitor.
16263
16388
  if (canvasUnavailable) return emptyResult;
16264
16389
  try {
16265
- const canvasResponse = await withCanvasApiTimeout(
16266
- canvasesClient.getCanvasRaw({ id: canvasId }),
16267
- 'getCanvas',
16268
- );
16390
+ // The first attempt joins the read a primary-widget lookup may already have started.
16391
+ const canvasRead = await readCanvasRecord(canvasId, { fresh: attempt > 0 });
16269
16392
  // A 304 has no body. Parsing it throws, the loader treats that as a
16270
16393
  // failed read, and the page asks for the same canvas again.
16271
- if (canvasResponse.raw.status === 304) {
16394
+ if (canvasRead.status === 304) {
16272
16395
  markCanvasStateLoaded();
16273
16396
  let cachedIds: string[] = [];
16274
16397
  if (localCachedJson) {
@@ -16280,8 +16403,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16280
16403
  }
16281
16404
  return { loaded: true, widgetIds: cachedIds };
16282
16405
  }
16283
- const canvasJson = await canvasResponse.raw.json();
16284
- const canvasRecord = canvasJson?.data || canvasJson;
16406
+ markCanvasOpenStep('creator:canvas-json-fetched');
16407
+ const canvasRecord = canvasRead.record;
16285
16408
  if (loadEpoch !== canvasLoadEpoch || ignoreIncomingCanvasLoads) {
16286
16409
  console.log('[CanvasDebug] Ignoring stale getCanvas result', { loadEpoch, canvasLoadEpoch });
16287
16410
  return emptyResult;
@@ -16569,6 +16692,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16569
16692
  canvasContent: parsedCanvas ?? JSON.parse(json)
16570
16693
  }
16571
16694
  });
16695
+ canvasRecordReads.delete(canvasId);
16572
16696
  if (currentSeq < lastResolvedAutosaveSequence) {
16573
16697
  // console.log(
16574
16698
  // `[CanvasDebug] Dropped out-of-order autosave response (${currentSeq} < ${lastResolvedAutosaveSequence})`
@@ -17667,6 +17791,9 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17667
17791
  suspendAutosave={suspendCanvasAutosave}
17668
17792
  isExternalDataLoading={!isCanvasStateLoaded}
17669
17793
  />
17794
+ {:else}
17795
+ <!-- Empty board while the canvas code downloads; the canvas mounts over the same surface. -->
17796
+ <CanvasBoardPlaceholder class="wc-canvas-placeholder" {locale} messages={canvasMessages} />
17670
17797
  {/if}
17671
17798
  </div>
17672
17799
 
@@ -12,6 +12,8 @@ export declare function readAllWidgetDrafts(): Promise<Record<string, WidgetDraf
12
12
  export declare function copyWidgetDraft(sourceWidgetId: string, targetWidgetId: string): Promise<void>;
13
13
  export declare function saveCanvasState(canvasId: string | null, json: string): void;
14
14
  export declare function readCanvasState(canvasId: string | null): Promise<string | null>;
15
+ export declare function saveCanvasWidgetList(canvasId: string, widgetList: unknown[]): void;
16
+ export declare function readCanvasWidgetList(canvasId: string): Promise<unknown[] | null>;
15
17
  /** False before an owner is known — nothing can be persisted yet. */
16
18
  export declare function canPersistShapeThumbnails(): boolean;
17
19
  export declare function saveShapeThumbnail(ref: string, dataUrl: string): void;
@@ -10,6 +10,7 @@
10
10
  import { deleteEntity, getCacheOwner, readAllEntitiesForKind, readEntity, writeEntity } from '@widgetic/cache-layer';
11
11
  const DRAFT_KIND = 'creatorDrafts';
12
12
  const CANVAS_KIND = 'creatorCanvasState';
13
+ const CANVAS_WIDGETS_KIND = 'creatorCanvasWidgets';
13
14
  const GENERATION_KIND = 'creatorActiveGeneration';
14
15
  const SHAPE_THUMBNAIL_KIND = 'creatorShapeThumbnails';
15
16
  function ownerIdOrNull() {
@@ -70,6 +71,26 @@ export async function readCanvasState(canvasId) {
70
71
  const record = await readEntity(ownerId, CANVAS_KIND, canvasId ?? 'default');
71
72
  return record?.json ?? null;
72
73
  }
74
+ // ─── Canvas widget list ──────────────────────────────────────────
75
+ //
76
+ // The last widget list read for a canvas. A second open shows it before the
77
+ // network answers; the network list then replaces it.
78
+ export function saveCanvasWidgetList(canvasId, widgetList) {
79
+ const ownerId = ownerIdOrNull();
80
+ if (!ownerId || !canvasId)
81
+ return;
82
+ // Wrapped in an object: readEntity only hands back object payloads.
83
+ void writeEntity(ownerId, CANVAS_WIDGETS_KIND, canvasId, { widgets: widgetList }).catch((error) => {
84
+ console.warn('[creatorDraftStorage] Failed to persist the canvas widget list:', error);
85
+ });
86
+ }
87
+ export async function readCanvasWidgetList(canvasId) {
88
+ const ownerId = ownerIdOrNull();
89
+ if (!ownerId || !canvasId)
90
+ return null;
91
+ const record = await readEntity(ownerId, CANVAS_WIDGETS_KIND, canvasId);
92
+ return Array.isArray(record?.widgets) ? record.widgets : null;
93
+ }
73
94
  // ─── Widget shape thumbnails ─────────────────────────────────────
74
95
  //
75
96
  // Widget screenshots used to be serialized inline in the canvas JSON, which
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@widgetic/creator",
3
- "version": "0.4.16",
3
+ "version": "0.4.17",
4
4
  "license": "SEE LICENSE IN LICENSE",
5
5
  "type": "module",
6
6
  "peerDependencies": {