@widgetic/creator 0.4.48 → 0.4.50

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.
@@ -9,6 +9,7 @@
9
9
  */
10
10
  import {
11
11
  Button,
12
+ CanvasBoardStatusChip,
12
13
  CreatorBar,
13
14
  DropdownMenu,
14
15
  PasswordInput,
@@ -60,7 +61,12 @@
60
61
  sketchBarShowsCustomize,
61
62
  sketchBarShowsPublish,
62
63
  sketchSavedStatusLabel,
64
+ widgetRowHeadIsAheadOfLive,
63
65
  } from './sketchBarState.js';
66
+ import { resolveSketchBoardStatusChip } from './sketchBoardStatusChip.js';
67
+ import { shouldHideDrawingToolbarForSelector } from './sketchToolbarMode.js';
68
+ import { stepAfterBoardChange } from './sketchBoardAfterDelete.js';
69
+ import { mergeBatchWidgetOntoListRecord } from './mergeBatchWidgetOntoListRecord.js';
64
70
  import { isDebugTabVisible } from './debug/debugUiVisibility.js';
65
71
  import { shouldNudgeSendBeforePublish } from './publish/publishGenerationGate.js';
66
72
 
@@ -295,6 +301,7 @@
295
301
  } from './host/hostControls.js';
296
302
  import { createSerialQueue } from './utils/serialQueue.js';
297
303
  import { createHeldAutosave } from './utils/heldAutosave.js';
304
+ import { refusesEmptyCanvas, requestInitForSave } from './utils/canvasSavePolicy.js';
298
305
  import { widgetsToRestore } from './utils/widgetsToRestore.js';
299
306
 
300
307
  function resolveCreatorWorkflowStep(
@@ -339,11 +346,17 @@
339
346
  $: limitNoticeMode = normalizeLimitNotices(limitNotices);
340
347
  /** What Publish would do now, for the host that draws its own button (see `CreatorAppProps.onPublishStateChanged`). */
341
348
  export let onPublishStateChanged: CreatorAppProps['onPublishStateChanged'] = undefined;
349
+ /**
350
+ * How long the canvas waits after the last change before it saves. The API is not asked after every stroke: a burst of
351
+ * changes is one save. The same on a developer's machine and for a visitor (a longer wait in development hid how the
352
+ * canvas is saved from the people who build it).
353
+ */
354
+ const CANVAS_AUTOSAVE_DELAY_MS = 3000;
342
355
  /**
343
356
  * How long the person can keep changing the canvas before it is saved anyway. The canvas waits for a quiet moment
344
- * (`autosaveDelayMs`) so the API is not asked after every stroke; this is the most that waiting may take.
357
+ * (`CANVAS_AUTOSAVE_DELAY_MS`) so the API is not asked after every stroke; this is the most that waiting may take.
345
358
  */
346
- const CANVAS_AUTOSAVE_MAX_WAIT_MS = 15000;
359
+ const CANVAS_AUTOSAVE_MAX_WAIT_MS = 10000;
347
360
  export let apiUrl: CreatorAppProps['apiUrl'] = null;
348
361
  export let widgetBuilderUrl: CreatorAppProps['widgetBuilderUrl'] = null;
349
362
  export let initialDebugMode: CreatorAppProps['initialDebugMode'] = undefined;
@@ -1401,6 +1414,16 @@
1401
1414
  try { return parseInt(creatorSessionStorage.getItem(CANVAS_OBJ_COUNT_KEY) || '0', 10) || 0; }
1402
1415
  catch { return 0; }
1403
1416
  })();
1417
+ /**
1418
+ * How many changes the canvas has reported (`onCanvasDirty`), and how many of them a save had seen when it got past the
1419
+ * guard against an empty canvas. A canvas that is empty after the person changed it (deleted everything) is a board
1420
+ * emptied on purpose; one that looks empty with no change reported is a snapshot gone wrong, and is not written over
1421
+ * the server's copy. See `handleCanvasAutoSave`.
1422
+ */
1423
+ let canvasEditRevision = 0;
1424
+ let canvasRevisionPassedGuard = 0;
1425
+ /** An autosave has failed and the person was told; cleared by the next save that goes through, so a run of failures is one notice. */
1426
+ let autosaveFailureToldToPerson = false;
1404
1427
 
1405
1428
  let selectedWidget: WidgetSummary | null = null;
1406
1429
  /** Set after canvas widget list restore; triggers preview load once WidgetDetails mounts. */
@@ -1428,7 +1451,11 @@
1428
1451
  let deleteDialogWidgetId = '';
1429
1452
  let deleteDialogStep: 'confirm-remove' | 'confirm-delete-db' = 'confirm-remove';
1430
1453
  let deleteDialogResolve: ((result: { proceed: boolean; deleteFromDb: boolean }) => void) | null = null;
1431
- /** Keep second-step UI/code; MVP deletes the DB widget after the first confirm. */
1454
+ /**
1455
+ * Delete recovery (item 21, option A): first confirm removes the canvas shape only (`deleteFromDb: false`).
1456
+ * Gateway `DELETE /widgets/:id` hard-deletes CDN, compositions, and the DB row — not called unless this flag enables step 2.
1457
+ * Undo restores the shape from canvas history; the widget row stays in the project list.
1458
+ */
1432
1459
  const ASK_DELETE_FROM_DB_CONFIRM = false;
1433
1460
 
1434
1461
  function showDeleteWidgetDialog(widgetId: string, widgetName: string): Promise<{ proceed: boolean; deleteFromDb: boolean }> {
@@ -1455,7 +1482,7 @@
1455
1482
  return;
1456
1483
  }
1457
1484
  deleteDialogOpen = false;
1458
- if (deleteDialogResolve) deleteDialogResolve({ proceed: true, deleteFromDb: true });
1485
+ if (deleteDialogResolve) deleteDialogResolve({ proceed: true, deleteFromDb: false });
1459
1486
  break;
1460
1487
  case 'keep-in-db':
1461
1488
  deleteDialogOpen = false;
@@ -1483,7 +1510,6 @@
1483
1510
  if (selectedWidgetId === widgetId) {
1484
1511
  selectedWidgetId = null;
1485
1512
  }
1486
- showToast('success', $t('creator.widget.widgetDeletedFromDatabase'));
1487
1513
  } catch (err) {
1488
1514
  // A shape can outlive its widget row (deleted from the Projects page or
1489
1515
  // another session). The canvas only needs the shape and local entry gone,
@@ -1566,8 +1592,6 @@
1566
1592
  'Create a widget from the attached image (short description inside).';
1567
1593
  /** Prefilled prompt for Convert-to-Widget — user edits or presses Send to start. */
1568
1594
  const CONVERT_PROMPT = 'Create a widget starting from the attached image';
1569
- /** Id of the one model the docked chat offers when the person is not in debug mode (its label is a message: `creator.codegen.assistantModelLabel`). */
1570
- const ASSISTANT_MODEL_ID = 'assistant';
1571
1595
  let codeGenerationPrompt = DEFAULT_PROMPT;
1572
1596
  let isGeneratingCode = false;
1573
1597
  let generatingWidgetIds: Record<string, boolean> = {};
@@ -2452,6 +2476,11 @@
2452
2476
  function handleChatConversationChange(conversationId: string | null, sourceWidgetId?: string) {
2453
2477
  const widgetId = sourceWidgetId ?? selectedWidgetId;
2454
2478
  if (!widgetId) return;
2479
+ if (conversationId) {
2480
+ creatorStorage.setItem(CHAT_CONVERSATION_STORAGE_PREFIX + widgetId, conversationId);
2481
+ } else {
2482
+ creatorStorage.removeItem(CHAT_CONVERSATION_STORAGE_PREFIX + widgetId);
2483
+ }
2455
2484
  patchPanelSnapshot(widgetId, { currentChatConversationId: conversationId });
2456
2485
  if (widgetId === focusedPanelWidgetId) {
2457
2486
  currentChatConversationId = conversationId;
@@ -4133,6 +4162,7 @@
4133
4162
  const PROMPT_TEXT_STORAGE_PREFIX = 'widgetCreator_promptText_';
4134
4163
  const PROMPT_IMAGES_STORAGE_PREFIX = 'widgetCreator_promptImages_';
4135
4164
  const CHAT_DRAFT_STORAGE_PREFIX = 'widgetCreator_chatDraft_';
4165
+ const CHAT_CONVERSATION_STORAGE_PREFIX = 'widgetCreator_chatConversationId_';
4136
4166
 
4137
4167
  let isGenerateDisabled = true;
4138
4168
  // Publish state: true while the build job is running
@@ -6394,9 +6424,20 @@
6394
6424
  return isSketchGenerationFailed(getPanelDisplayState(widgetId), w);
6395
6425
  }
6396
6426
 
6397
- $: sketchBarGenerationFailed = sketchPrimaryGenerationFailed(canvasPrimaryWidgetId);
6427
+ /**
6428
+ * What the bar above the sketch shows (title, status, Publish, Live badge, board chip, drawing tools or selector) is worked
6429
+ * out by functions that read the widget record (`widgetsById`) and the panel state (`panelDisplayRevision`). Svelte 4 re-runs
6430
+ * a `$:` line only when a variable named in the line itself changes, so a line that named only `canvasPrimaryWidgetId` kept
6431
+ * the answer it had when the id was set, and an answer that arrived afterwards (the widgets of the canvas, the canvas
6432
+ * document, the publish history) never reached the bar: a published widget with changes showed "Live" and no Publish, and a
6433
+ * widget whose build failed lost its drawing tools. Every line of the bar names this object, which is new whenever either
6434
+ * of the two changes. Pinned by `sketchBarReactivity.test.ts`.
6435
+ */
6436
+ $: sketchBarSources = { panelDisplayRevision, widgetsById };
6437
+
6438
+ $: sketchBarGenerationFailed = (void sketchBarSources, sketchPrimaryGenerationFailed(canvasPrimaryWidgetId));
6398
6439
 
6399
- $: sketchBarTitleLabel = (void panelDisplayRevision, void sketchBarGenerationFailed, void canvasPrimaryWidgetId, sketchBarTitle());
6440
+ $: sketchBarTitleLabel = (void sketchBarSources, void panelDisplayRevision, void sketchBarGenerationFailed, void canvasPrimaryWidgetId, void sketchWidgetNamesFromBatch, void sketchCanvasPersistenceName, void activeCanvasName, sketchBarTitle());
6400
6441
 
6401
6442
  function sketchBarTitle(): string {
6402
6443
  const untitled = $t('creator.widget.untitledName');
@@ -6447,6 +6488,23 @@
6447
6488
  return resolvePublishedVersionFromWidget(widget as WidgetSummary | null) !== null;
6448
6489
  }
6449
6490
 
6491
+ /**
6492
+ * A published widget whose row says HEAD is not the live commit. The panel's own answer can lag on embed load, and it
6493
+ * cannot know a build made on another device (it trusts a head that differs from live only when this browser saw the
6494
+ * build finish), so the row's two commits are asked as well.
6495
+ */
6496
+ function sketchWidgetRowHeadIsAheadOfLive(widgetId: string | null): boolean {
6497
+ if (!widgetId || !sketchPrimaryShowsLiveBadge(widgetId)) return false;
6498
+ return widgetRowHeadIsAheadOfLive(getWidgetById(widgetId) as Record<string, unknown> | null, commitsMatch);
6499
+ }
6500
+
6501
+ /** Sketch header publish: panel diff can lag on embed load — fall back to widget commit SHAs. */
6502
+ function sketchPrimaryHasUnpublishedChanges(widgetId: string | null): boolean {
6503
+ if (!widgetId) return false;
6504
+ if (hasUnpublishedChangesForPanel(widgetId)) return true;
6505
+ return sketchWidgetRowHeadIsAheadOfLive(widgetId);
6506
+ }
6507
+
6450
6508
  function sketchWidgetHasActiveCodegenOperation(widgetId: string | null): boolean {
6451
6509
  if (!widgetId) return false;
6452
6510
  const w = getWidgetById(widgetId) as Record<string, unknown> | null;
@@ -6456,52 +6514,154 @@
6456
6514
  return !!op;
6457
6515
  }
6458
6516
 
6459
- $: sketchBarCanvasGenerating =
6517
+ $: sketchBarCanvasGenerating = (void sketchBarSources,
6460
6518
  !!canvasPrimaryWidgetId &&
6461
6519
  (!!generatingWidgetIds[canvasPrimaryWidgetId] ||
6462
- sketchWidgetHasActiveCodegenOperation(canvasPrimaryWidgetId));
6520
+ sketchWidgetHasActiveCodegenOperation(canvasPrimaryWidgetId)));
6463
6521
 
6464
- $: sketchBarStatusLabel = !embeddedSketchShell
6522
+ $: sketchBarHasUnpublishedLive = (void sketchBarSources,
6523
+ !!canvasPrimaryWidgetId &&
6524
+ sketchPrimaryShowsLiveBadge(canvasPrimaryWidgetId) &&
6525
+ sketchPrimaryHasUnpublishedChanges(canvasPrimaryWidgetId));
6526
+
6527
+ $: sketchBarStatusLabel = (void sketchBarSources, !embeddedSketchShell
6465
6528
  ? ''
6466
6529
  : !canvasPrimaryWidgetId
6467
- ? $t('creator.common.draft')
6468
- : sketchPrimaryShowsLiveBadge(canvasPrimaryWidgetId)
6469
- ? $t('creator.sketch.publishedJustNow')
6470
- : sketchBarGenerationFailed
6471
- ? $t('creator.common.draft')
6472
- : sketchPrimaryHasGeneratedCode(canvasPrimaryWidgetId)
6473
- ? sketchSavedStatusLabel(
6474
- $t('creator.general.saved'),
6475
- (getWidgetById(canvasPrimaryWidgetId) as { updatedAt?: string; updated_at?: string } | null)
6476
- ?.updatedAt ?? (getWidgetById(canvasPrimaryWidgetId) as { updated_at?: string } | null)?.updated_at,
6477
- )
6478
- : $t('creator.common.draft');
6479
-
6480
- $: sketchBarShowPublish = sketchBarShowsPublish({
6530
+ ? ''
6531
+ : sketchBarGenerationFailed
6532
+ ? sketchPrimaryHasGeneratedCode(canvasPrimaryWidgetId)
6533
+ ? $t('creator.general.saved')
6534
+ : ''
6535
+ : sketchBarCanvasGenerating
6536
+ ? sketchPrimaryHasGeneratedCode(canvasPrimaryWidgetId)
6537
+ ? $t('creator.general.saved')
6538
+ : ''
6539
+ : sketchBarHasUnpublishedLive
6540
+ ? $t('creator.general.saved')
6541
+ : sketchPrimaryShowsLiveBadge(canvasPrimaryWidgetId)
6542
+ ? $t('creator.sketch.publishedJustNow')
6543
+ : sketchPrimaryHasGeneratedCode(canvasPrimaryWidgetId)
6544
+ ? $t('creator.general.saved')
6545
+ : '');
6546
+
6547
+ $: sketchBarShowPublish = (void sketchBarSources, sketchBarShowsPublish({
6481
6548
  embedded: embeddedSketchShell,
6482
6549
  widgetId: canvasPrimaryWidgetId,
6483
6550
  hasGeneratedCode: sketchPrimaryHasGeneratedCode(canvasPrimaryWidgetId),
6484
6551
  showsLive: sketchPrimaryShowsLiveBadge(canvasPrimaryWidgetId),
6485
6552
  generating: sketchBarCanvasGenerating,
6486
6553
  failed: sketchBarGenerationFailed,
6487
- });
6554
+ hasUnpublishedChanges: canvasPrimaryWidgetId
6555
+ ? sketchPrimaryHasUnpublishedChanges(canvasPrimaryWidgetId)
6556
+ : false,
6557
+ }));
6558
+
6559
+ $: sketchBoardStatusChip = (void sketchBarSources, resolveSketchBoardStatusChip({
6560
+ embedded: embeddedSketchShell,
6561
+ generating: sketchBarCanvasGenerating,
6562
+ failed: sketchBarGenerationFailed,
6563
+ hasGeneratedCode: sketchPrimaryHasGeneratedCode(canvasPrimaryWidgetId),
6564
+ showsLive:
6565
+ sketchPrimaryShowsLiveBadge(canvasPrimaryWidgetId) && !sketchBarHasUnpublishedLive,
6566
+ }));
6567
+
6568
+ function sketchBoardStatusChipLabel(variant: 'generating' | 'ready' | 'failed'): string {
6569
+ if (variant === 'generating') return $t('creator.sketch.boardChipGenerating');
6570
+ if (variant === 'ready') return $t('creator.sketch.boardChipReady');
6571
+ return $t('creator.sketch.boardChipFailed');
6572
+ }
6573
+
6574
+ function sketchBoardStatusChipActionLabel(variant: 'generating' | 'failed'): string {
6575
+ return variant === 'generating' ? $t('creator.sketch.boardChipStop') : $t('creator.sketch.boardChipTryAgain');
6576
+ }
6577
+
6578
+ function handleSketchBoardStatusChipAction(): void {
6579
+ const widgetId = canvasPrimaryWidgetId;
6580
+ if (!widgetId) return;
6581
+ if (sketchBarCanvasGenerating) {
6582
+ stopGeneration(widgetId);
6583
+ return;
6584
+ }
6585
+ if (sketchBarGenerationFailed) {
6586
+ const ps = getPanelDisplayState(widgetId);
6587
+ void handleChatRetryMessage(lastGenerationPrompt || ps.codeGenerationPrompt, widgetId);
6588
+ }
6589
+ }
6488
6590
 
6489
- $: sketchBarShowCustomize = sketchBarShowsCustomize({
6591
+ $: sketchBarShowCustomize = (void sketchBarSources, sketchBarShowsCustomize({
6490
6592
  embedded: embeddedSketchShell,
6491
6593
  widgetId: canvasPrimaryWidgetId,
6492
6594
  hasGeneratedCode: sketchPrimaryHasGeneratedCode(canvasPrimaryWidgetId),
6493
6595
  generating: !!canvasPrimaryWidgetId && !!generatingWidgetIds[canvasPrimaryWidgetId],
6494
6596
  failed: sketchBarGenerationFailed,
6495
6597
  hasActiveCodegen: sketchWidgetHasActiveCodegenOperation(canvasPrimaryWidgetId),
6496
- });
6598
+ }));
6497
6599
 
6498
- $: sketchBarShowLiveBadge =
6499
- embeddedSketchShell && sketchPrimaryShowsLiveBadge(canvasPrimaryWidgetId);
6600
+ $: sketchBarShowLiveBadge = (void sketchBarSources,
6601
+ embeddedSketchShell
6602
+ && sketchPrimaryShowsLiveBadge(canvasPrimaryWidgetId)
6603
+ && !sketchBarHasUnpublishedLive);
6604
+
6605
+ $: sketchBarLoading = embeddedSketchShell && !isCanvasStateLoaded && !canvasUnavailable;
6606
+
6607
+ let sketchTitleMenuOpen = false;
6608
+
6609
+ function handleSketchTitleMenuRename(): void {
6610
+ sketchTitleMenuOpen = false;
6611
+ const widgetId = canvasPrimaryWidgetId;
6612
+ if (widgetId) {
6613
+ const widget = getWidgetById(widgetId);
6614
+ if (widget) {
6615
+ startRenameWidget(widget);
6616
+ return;
6617
+ }
6618
+ }
6619
+ void startCanvasNameEdit();
6620
+ }
6621
+
6622
+ async function handleSketchTitleMenuDuplicate(): Promise<void> {
6623
+ sketchTitleMenuOpen = false;
6624
+ await handleHostDuplicateWidgetEvent();
6625
+ }
6626
+
6627
+ async function handleSketchTitleMenuDelete(): Promise<void> {
6628
+ sketchTitleMenuOpen = false;
6629
+ await handleHostDeleteWidgetEvent();
6630
+ }
6500
6631
 
6501
- $: sketchBarPublishLabel =
6502
- sketchBarShowLiveBadge
6503
- ? $t('creator.common.update')
6504
- : $t('creator.common.publish');
6632
+ $: sketchBarPublishLabel = (void sketchBarSources, (() => {
6633
+ if (!canvasPrimaryWidgetId) return $t('creator.common.publish');
6634
+ const panel = getPanelDisplayState(canvasPrimaryWidgetId);
6635
+ const widget = getWidgetById(canvasPrimaryWidgetId) as { hasLiveVersion?: boolean; has_live_version?: boolean } | null;
6636
+ const wasPublished =
6637
+ panel.lastPublishedVersion != null
6638
+ || !!(widget?.hasLiveVersion || widget?.has_live_version);
6639
+ const unpublishedChanges =
6640
+ wasPublished
6641
+ && (sketchBarShowLiveBadge || sketchPrimaryHasUnpublishedChanges(canvasPrimaryWidgetId));
6642
+ return unpublishedChanges ? $t('creator.publish.publishChanges') : $t('creator.common.publish');
6643
+ })());
6644
+
6645
+ /**
6646
+ * Whether the Publish button of the bar is disabled. `getPublishGateForPanel` reads the publish state of the panel (the head
6647
+ * commit, the live commit, a build that is running, a publish that is open, the session); the template's own call of it is not
6648
+ * tracked, so the button kept the answer it got the first time, "No new version to publish" while the head commit had not
6649
+ * reached the panel yet, and a widget with changes showed "Publish changes" on a button that could not be clicked. The
6650
+ * variables the gate reads are named here, with the two sources of the bar.
6651
+ */
6652
+ $: sketchBarPublishDisabled = (void sketchBarSources,
6653
+ void isPublishing,
6654
+ void publishingWidgetId,
6655
+ void generatingWidgetIds,
6656
+ void previewReadyAnnouncedByWidgetId,
6657
+ void publishHeldByWidgetId,
6658
+ void hasValidToken,
6659
+ void $userSession,
6660
+ void canvasId,
6661
+ void sessionCanvasId,
6662
+ void lastCommitId,
6663
+ void focusedPanelWidgetId,
6664
+ !!canvasPrimaryWidgetId && isPublishDisabledForPanel(canvasPrimaryWidgetId));
6505
6665
 
6506
6666
  $: if (embeddedSketchShell && canvasRef?.saveCanvas && isCanvasStateLoaded) {
6507
6667
  try {
@@ -6532,11 +6692,7 @@
6532
6692
  }
6533
6693
 
6534
6694
  function handleSketchBarTitleClick() {
6535
- if (canvasPrimaryWidgetId) {
6536
- void openWidgetDetailsPanel(canvasPrimaryWidgetId);
6537
- return;
6538
- }
6539
- startCanvasNameEdit();
6695
+ void startCanvasNameEdit();
6540
6696
  }
6541
6697
 
6542
6698
  function handleSketchCustomize() {
@@ -6822,12 +6978,16 @@
6822
6978
  return !!(panel.hasGeneratedCode || panel.lastCommitId || panel.lastPublishedVersion != null);
6823
6979
  }
6824
6980
 
6981
+ $: hideDrawingToolbarForSelector = (void sketchBarSources,
6982
+ panelDisplayRevision >= 0
6983
+ && !!canvasPrimaryWidgetId
6984
+ && shouldHideDrawingToolbarForSelector({
6985
+ hasBuiltArtifact: primaryWidgetHasGeneratedCode(),
6986
+ generating: sketchBarCanvasGenerating,
6987
+ generationFailed: sketchBarGenerationFailed,
6988
+ }));
6825
6989
  $: showDrawingTools = (multipleWidgetsAllowed || singleWidgetChromeReady) && (
6826
- sketchToolbarAfterRestore || !(
6827
- panelDisplayRevision >= 0
6828
- && !!canvasPrimaryWidgetId
6829
- && primaryWidgetHasGeneratedCode()
6830
- )
6990
+ sketchToolbarAfterRestore || !hideDrawingToolbarForSelector
6831
6991
  );
6832
6992
  $: sketchCanvasShowDrawingTools = embeddedSketchShell
6833
6993
  ? !canvasPrimaryWidgetId || showDrawingTools
@@ -6916,7 +7076,7 @@
6916
7076
  }
6917
7077
  const widgetName = getWidgetById(widgetId)?.name || 'Widget';
6918
7078
  const result = await showDeleteWidgetDialog(widgetId, widgetName);
6919
- if (result.proceed) {
7079
+ if (result.proceed && result.deleteFromDb) {
6920
7080
  await deleteWidgetFromDb(widgetId);
6921
7081
  }
6922
7082
  }
@@ -6926,6 +7086,88 @@
6926
7086
  announceToSite('widgetic:creator-save-state', { dirty });
6927
7087
  }
6928
7088
 
7089
+ /**
7090
+ * The widget whose card Delete widget took off this one-widget canvas (item 21). The bar, the status chip, the toolbar and the
7091
+ * chat all follow `canvasPrimaryWidgetId`, so the canvas is empty again only when that id is empty too, and Undo gives the
7092
+ * widget back its name, chip and chat only when the id comes back with the card. The widget row itself stays: the delete
7093
+ * takes the card off the board, and Undo (or Restore shapes) brings it back.
7094
+ */
7095
+ let widgetDeletedFromBoardId: string | null = null;
7096
+
7097
+ /**
7098
+ * The draft chat that docks after Delete widget puts the cursor in its composer (a new chat does that), and a focused text box
7099
+ * keeps Cmd+Z for its own undo. The person's next key is most likely Cmd+Z for the delete they just made, so for a moment the
7100
+ * composer cannot take the focus from the page, unless the person goes there themselves (a click or a key press).
7101
+ */
7102
+ const KEYS_STAY_ON_PAGE_AFTER_DELETE_MS = 2500;
7103
+ let stopKeepingKeysOnPage: (() => void) | null = null;
7104
+
7105
+ function keepKeysOnPageAfterDelete(): void {
7106
+ if (typeof document === 'undefined') return;
7107
+ stopKeepingKeysOnPage?.();
7108
+ const keepingTimer = setTimeout(() => stopKeepingKeysOnPage?.(), KEYS_STAY_ON_PAGE_AFTER_DELETE_MS);
7109
+ const keepKeysOnPage = (event: FocusEvent) => {
7110
+ const target = (event.composedPath?.()[0] ?? event.target) as Element | null;
7111
+ if (target instanceof HTMLTextAreaElement && target.closest('.floating-panels-overlay')) {
7112
+ console.log('[CreatorApp] The chat composer asked for the focus right after Delete widget: the keys stay on the page for Undo');
7113
+ target.blur();
7114
+ }
7115
+ };
7116
+ const personActs = () => stopKeepingKeysOnPage?.();
7117
+ document.addEventListener('focusin', keepKeysOnPage, true);
7118
+ document.addEventListener('pointerdown', personActs, true);
7119
+ document.addEventListener('keydown', personActs, true);
7120
+ stopKeepingKeysOnPage = () => {
7121
+ clearTimeout(keepingTimer);
7122
+ document.removeEventListener('focusin', keepKeysOnPage, true);
7123
+ document.removeEventListener('pointerdown', personActs, true);
7124
+ document.removeEventListener('keydown', personActs, true);
7125
+ stopKeepingKeysOnPage = null;
7126
+ };
7127
+ }
7128
+
7129
+ /** The one-widget canvas goes back to the empty canvas: no widget name, no chip, the drawing tools, and the draft chat takes the chat's place. */
7130
+ function takeWidgetOffSketchBoard(widgetId: string): void {
7131
+ console.log('[CreatorApp] Widget card is off the board: back to the empty canvas', widgetId.slice(0, 8));
7132
+ widgetDeletedFromBoardId = widgetId;
7133
+ closeWidgetDetailsPanel(widgetId, { fromShapeSwitch: true });
7134
+ if (canvasPrimaryWidgetId === widgetId) canvasPrimaryWidgetId = null;
7135
+ if (selectedWidgetId === widgetId) selectedWidgetId = null;
7136
+ keepKeysOnPageAfterDelete();
7137
+ }
7138
+
7139
+ /** After every change of the board: follow the card of the widget the person deleted (Undo puts it back, Redo takes it off again). */
7140
+ function reconcileSketchBoardWithDeletedWidget(): void {
7141
+ if (!widgetDeletedFromBoardId || !embeddedSketchShell || !isCanvasStateLoaded) return;
7142
+ try {
7143
+ const step = stepAfterBoardChange({
7144
+ deletedWidgetId: widgetDeletedFromBoardId,
7145
+ primaryWidgetId: canvasPrimaryWidgetId,
7146
+ linkedWidgetIds: canvasRef?.getLinkedWidgetIds?.() ?? new Set<string>(),
7147
+ });
7148
+ if (step.kind === 'forget') {
7149
+ widgetDeletedFromBoardId = null;
7150
+ } else if (step.kind === 'clear') {
7151
+ takeWidgetOffSketchBoard(step.widgetId);
7152
+ } else if (step.kind === 'restore') {
7153
+ console.log('[CreatorApp] Widget card is back on the board: the canvas speaks for its widget again', step.widgetId.slice(0, 8));
7154
+ canvasPrimaryWidgetId = step.widgetId;
7155
+ panelDisplayRevision += 1;
7156
+ }
7157
+ } catch (error) {
7158
+ console.warn('[CreatorApp] Could not follow the card of the deleted widget', error);
7159
+ }
7160
+ }
7161
+
7162
+ /** The canvas says the person changed the board (a shape, a property, the letters of a text): it is unsaved until a save goes through. */
7163
+ function handleCanvasDirty(): void {
7164
+ canvasEditRevision += 1;
7165
+ emitCreatorSaveState(true);
7166
+ // After the canvas has finished the change it is telling us about: follow the card of a widget the person deleted (Undo, Redo).
7167
+ if (widgetDeletedFromBoardId) queueMicrotask(reconcileSketchBoardWithDeletedWidget);
7168
+ scheduleSketchPrefillFromCanvasDirty();
7169
+ }
7170
+
6929
7171
  function handleHostSaveCanvasEvent(): void {
6930
7172
  // Explicit Save must always persist — bypass soft load-cooldown / not-ready guards.
6931
7173
  const json = canvasRef?.saveCanvas?.() ?? null;
@@ -7123,10 +7365,34 @@
7123
7365
  async function resumeEmbeddedSketchScenario(primaryId: string): Promise<void> {
7124
7366
  if (!embeddedSketchShell || !primaryId) return;
7125
7367
  ensurePanelState(primaryId);
7126
- const widget = getWidgetById(primaryId) as Record<string, unknown> | null;
7368
+ const widget = getWidgetById(primaryId) as WidgetSummary | null;
7369
+ if (widget) {
7370
+ hydrateWidgetVersionAndCommitState(widget);
7371
+ }
7372
+ const widgetRecord = widget as Record<string, unknown> | null;
7373
+ if (widgetRecord && isSketchGenerationFailed(getPanelState(primaryId), widgetRecord)) {
7374
+ patchCodegenUiState(primaryId, {
7375
+ lastGenerationFailed: true,
7376
+ lastGenerationError:
7377
+ String(widgetRecord.lastGenerationError ?? widgetRecord.last_generation_error ?? '').trim()
7378
+ || 'Code generation failed',
7379
+ hasGeneratedCode: sketchPrimaryHasGeneratedCode(primaryId),
7380
+ });
7381
+ widgets = widgets.map((w) =>
7382
+ w.id === primaryId
7383
+ ? {
7384
+ ...w,
7385
+ codegenStatus: 'failed',
7386
+ codegen_status: 'failed',
7387
+ generationFailed: true,
7388
+ generation_failed: true,
7389
+ }
7390
+ : w,
7391
+ );
7392
+ }
7127
7393
  const opId = String(
7128
- (widget?.activeOperationId as string | undefined)
7129
- ?? (widget?.active_operation_id as string | undefined)
7394
+ (widgetRecord?.activeOperationId as string | undefined)
7395
+ ?? (widgetRecord?.active_operation_id as string | undefined)
7130
7396
  ?? '',
7131
7397
  ).trim();
7132
7398
  if (opId && operationsClient) {
@@ -7225,6 +7491,11 @@
7225
7491
  emitCanvasWidgetsList('hydrate-primary');
7226
7492
  if (embeddedSketchShell) {
7227
7493
  await mergeWidgetsLinkedOnCanvas([primaryId]);
7494
+ const recordedPrimary = await resolvePrimaryWidgetIdForCanvas(targetCanvasId);
7495
+ if (recordedPrimary && recordedPrimary !== primaryId) {
7496
+ primaryId = recordedPrimary;
7497
+ canvasPrimaryWidgetId = recordedPrimary;
7498
+ }
7228
7499
  }
7229
7500
  }
7230
7501
  return primaryId || canvasPrimaryWidgetId || null;
@@ -9246,7 +9517,14 @@
9246
9517
  }
9247
9518
  for (const widget of fetched) {
9248
9519
  if (widget?.id) {
9249
- mergedById.set(widget.id, preserveRepositoryOnWidget(widget, previousById.get(widget.id)));
9520
+ // The batch row is read through the generated model and carries fewer fields than the list row
9521
+ // (`hasLiveVersion`, `lastPublishCommitSha`, `thumbnailUrl`, ...): it goes onto the list row, not over it,
9522
+ // or a published widget with changes loses the live commit and the bar reads "Live" with no Publish.
9523
+ const previousListRow = previousById.get(widget.id);
9524
+ mergedById.set(
9525
+ widget.id,
9526
+ preserveRepositoryOnWidget(mergeBatchWidgetOntoListRecord(previousListRow, widget), previousListRow),
9527
+ );
9250
9528
  const batchName = String(widget.name ?? '').trim();
9251
9529
  if (embeddedSketchShell && batchName) {
9252
9530
  sketchWidgetNamesFromBatch = { ...sketchWidgetNamesFromBatch, [widget.id]: batchName };
@@ -10928,6 +11206,19 @@
10928
11206
  pendingReferenceImageDataUrl = null;
10929
11207
  chatMethods.restoreAttachmentsFromDataUrls?.([dataUrl]);
10930
11208
  }
11209
+ const storedConversationId = ownerWidgetId
11210
+ ? creatorStorage.getItem(CHAT_CONVERSATION_STORAGE_PREFIX + ownerWidgetId)
11211
+ : null;
11212
+ if (storedConversationId && methods.selectConversation) {
11213
+ // The method may answer at once or with a promise; a failed restore leaves the chat on its own latest conversation.
11214
+ void (async () => {
11215
+ try {
11216
+ await methods.selectConversation?.(storedConversationId);
11217
+ } catch (error) {
11218
+ console.debug('[CreatorApp] Could not restore the last conversation of this widget', error);
11219
+ }
11220
+ })();
11221
+ }
10931
11222
  }
10932
11223
 
10933
11224
  /**
@@ -13560,6 +13851,7 @@ Requirements:
13560
13851
  clearTimeout(sketchPrefillDirtyTimer);
13561
13852
  sketchPrefillDirtyTimer = null;
13562
13853
  }
13854
+ stopKeepingKeysOnPage?.();
13563
13855
  if (tokenCheckInterval) clearInterval(tokenCheckInterval);
13564
13856
  if (tokenDisplayInterval) clearInterval(tokenDisplayInterval);
13565
13857
  if (hydrationSafetyTimeout) clearTimeout(hydrationSafetyTimeout);
@@ -16770,7 +17062,11 @@ Requirements:
16770
17062
  || !!(pendingSha && liveSha && !commitsMatch(pendingSha, liveSha));
16771
17063
  const unpublishedAhead = hasUnpublishedChangesForPanel(widgetId)
16772
17064
  || !!(pendingPublish && ps.lastCommitId && liveSha && !commitsMatch(ps.lastCommitId, liveSha))
16773
- || !!(ps.lastCommitId && liveSha && !commitsMatch(ps.lastCommitId, liveSha));
17065
+ || !!(ps.lastCommitId && liveSha && !commitsMatch(ps.lastCommitId, liveSha))
17066
+ // The bar above the sketch says "Publish changes" when the widget row's HEAD is not its live commit, also for a
17067
+ // build this browser never saw finish (made on another device): the button follows the bar. The server publishes
17068
+ // its own HEAD whatever commit is sent, so nothing older can go live through this.
17069
+ || (embeddedSketchShell && sketchWidgetRowHeadIsAheadOfLive(widgetId));
16774
17070
 
16775
17071
  // Pending codegen SHA wins over a stale GitLab HEAD that still matches live.
16776
17072
  if (headSha && liveSha && commitsMatch(headSha, liveSha) && !pendingPublish && !unpublishedAhead) {
@@ -18196,12 +18492,16 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18196
18492
 
18197
18493
  if (!result.proceed) return false;
18198
18494
 
18199
- closeWidgetDetailsPanel(widgetId);
18495
+ if (embeddedSketchShell && widgetId === canvasPrimaryWidgetId) {
18496
+ // One-widget canvas: the card leaves the board, so the canvas is empty again and the draft chat takes the chat's place.
18497
+ // (Closing the panel and opening it again for the same id in one go leaves the panel without a ref: the chat stayed blank.)
18498
+ takeWidgetOffSketchBoard(widgetId);
18499
+ } else {
18500
+ closeWidgetDetailsPanel(widgetId);
18501
+ }
18200
18502
 
18201
18503
  if (result.deleteFromDb) {
18202
18504
  await deleteWidgetFromDb(widgetId);
18203
- } else {
18204
- showToast('info', $t('creator.canvas.shapeRemovedFromCanvas'), { description: $t('creator.widget.widgetKeptInDatabase2', { name: widgetName }) });
18205
18505
  }
18206
18506
  return true;
18207
18507
  }
@@ -18420,7 +18720,11 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18420
18720
  canvasLoadFailsafeArmedForId = null;
18421
18721
  }
18422
18722
  function markCanvasStateLoaded() {
18423
- if (!isCanvasStateLoaded) markCanvasOpenStep('creator:canvas-state-loaded');
18723
+ if (!isCanvasStateLoaded) {
18724
+ markCanvasOpenStep('creator:canvas-state-loaded');
18725
+ // What was reported before the board loaded belongs to the board that was there: the guard starts again from here.
18726
+ canvasRevisionPassedGuard = canvasEditRevision;
18727
+ }
18424
18728
  isCanvasStateLoaded = true;
18425
18729
  canvasHydrateRetryCount = 0;
18426
18730
  clearCanvasHydrateRetry();
@@ -18737,6 +19041,15 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18737
19041
  */
18738
19042
  let autosaveSequence = 0;
18739
19043
  let lastResolvedAutosaveSequence = 0;
19044
+ /**
19045
+ * What `handleCanvasAutoSave` did with the canvas it was given:
19046
+ * - `skipped`: nothing was kept (the canvas is not ready, or a guard refused an empty snapshot);
19047
+ * - `held`: kept back for the few seconds after a load, and sent when they are over;
19048
+ * - `local`: kept on this device only (there is no canvas row or client to send it to yet);
19049
+ * - `saved`: the API has it;
19050
+ * - `failed`: the API refused it; the copy on this device is written.
19051
+ */
19052
+ type CanvasSaveOutcome = 'skipped' | 'held' | 'local' | 'saved' | 'failed';
18740
19053
  /** The requests that write the canvas to the API, one at a time and in the order they were made (see `handleCanvasAutoSave`). */
18741
19054
  const canvasSaveQueue = createSerialQueue();
18742
19055
  /** How long after a canvas load we still defer (not drop) autosaves. */
@@ -18761,21 +19074,23 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18761
19074
  async function handleCanvasAutoSave(
18762
19075
  json: string | null,
18763
19076
  isUnmountSave = false,
18764
- opts: { force?: boolean } = {},
18765
- ) {
19077
+ opts: { force?: boolean; pageIsLeaving?: boolean } = {},
19078
+ ): Promise<CanvasSaveOutcome> {
18766
19079
  if (!json) {
18767
19080
  if (isUnmountSave) console.warn('[CanvasDebug] onBeforeUnmount: saveCanvas returned null — canvas not initialized');
18768
- return;
19081
+ return 'skipped';
18769
19082
  }
18770
19083
 
18771
19084
  const force = opts.force === true;
19085
+ // The changes this save takes with it: a change reported while it is on its way is not saved by it.
19086
+ const editRevisionAtStart = canvasEditRevision;
18772
19087
 
18773
19088
  // Guard: don't overwrite DB with an empty canvas if state hasn't loaded yet
18774
19089
  if (!force && !isCanvasStateLoaded) {
18775
19090
  // console.log(
18776
19091
  // '[CanvasDebug] Skipping autosave — canvas state not loaded yet (guard active, avoids overwrite with empty)'
18777
19092
  // );
18778
- return;
19093
+ return 'skipped';
18779
19094
  }
18780
19095
 
18781
19096
  // Guard: skip autosaves triggered by loadCanvas() object:added events
@@ -18787,7 +19102,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18787
19102
  // persisted rather than silently discarded.
18788
19103
  if (!force && isLoadCooldownActive && !isUnmountSave) {
18789
19104
  heldCooldownAutosave.hold(json);
18790
- return;
19105
+ return 'held';
18791
19106
  }
18792
19107
 
18793
19108
  let objectCount = 0;
@@ -18812,11 +19127,20 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18812
19127
 
18813
19128
  // Guard: prevent saving empty canvas over non-empty data.
18814
19129
  // Unmount saves (HMR) are always blocked when going from N→0.
18815
- // Normal autosaves going from N→0 are allowed only if the drop is gradual
18816
- // (user deleted objects one by one) — a sudden jump from many to 0 is suspicious.
18817
- // Explicit Save (force) still blocks sudden N→0 to avoid wiping the canvas.
19130
+ // Normal autosaves going from N→0 are allowed when the drop is gradual (user deleted objects one by one), and when
19131
+ // the canvas has reported a change since the last save got past this guard (`canvasEditRevision`): a person who
19132
+ // selects everything and deletes it has emptied the board on purpose, and the server must not keep the old shapes.
19133
+ // A canvas that looks empty with no change reported is a snapshot gone wrong, and is still refused.
19134
+ // Explicit Save (force) follows the same rule.
18818
19135
  if (objectCount === 0 && lastSavedCanvasObjectCount > 0) {
18819
- if (isUnmountSave || lastSavedCanvasObjectCount > 1) {
19136
+ if (
19137
+ refusesEmptyCanvas({
19138
+ shapesToSave: objectCount,
19139
+ shapesSavedBefore: lastSavedCanvasObjectCount,
19140
+ isUnmountSave,
19141
+ changedSinceLastSave: canvasEditRevision > canvasRevisionPassedGuard,
19142
+ })
19143
+ ) {
18820
19144
  console.warn(
18821
19145
  `[CanvasDebug] BLOCKING save: would overwrite ${lastSavedCanvasObjectCount} shapes with 0 (isUnmount=${isUnmountSave}, force=${force})`
18822
19146
  );
@@ -18825,7 +19149,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18825
19149
  description: $t('creator.canvas.canvasSnapshotLookedEmptyRefresh'),
18826
19150
  });
18827
19151
  }
18828
- return;
19152
+ return 'skipped';
18829
19153
  }
18830
19154
  // lastSavedCanvasObjectCount === 1 → user deleted the last object, allow it
18831
19155
  // console.log('[CanvasDebug] Allowing save: last object deleted by user (1→0)');
@@ -18837,9 +19161,10 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18837
19161
 
18838
19162
  lastSavedCanvasObjectCount = objectCount;
18839
19163
  try { creatorSessionStorage.setItem(CANVAS_OBJ_COUNT_KEY, String(objectCount)); } catch {}
19164
+ // The changes reported so far are in this save: the next empty canvas needs a change of its own to be written.
19165
+ canvasRevisionPassedGuard = editRevisionAtStart;
18840
19166
  noteDrawnObjectCount(countDrawnCanvasObjectsInJson(json));
18841
19167
  maybeSyncSketchGeneratePrefill();
18842
- emitCreatorSaveState(false);
18843
19168
 
18844
19169
  // Save to durable L1 fallback (always, even with 0 objects for legitimate clears)
18845
19170
  saveCanvasState(canvasId, json);
@@ -18865,11 +19190,19 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18865
19190
  }
18866
19191
 
18867
19192
  // Save to API via SDK with sequence race protection
19193
+ let outcome: CanvasSaveOutcome = 'local';
18868
19194
  if (canvasId && canvasesClient) {
18869
19195
  const currentSeq = ++autosaveSequence;
18870
19196
  // The canvas this save is for, read now: the request waits its turn in the queue, and the person may switch canvas meanwhile.
18871
19197
  const saveCanvasId = canvasId;
18872
19198
  const saveClient = canvasesClient;
19199
+ // A page that is going away (the tab closes, a reload) drops a request that is still on its way, and the last
19200
+ // changes would be lost. `keepalive` lets the browser finish it; it takes bodies up to 64 KB, so a larger canvas goes as usual.
19201
+ const requestInit = requestInitForSave(json, {
19202
+ isUnmountSave,
19203
+ pageIsLeaving: opts.pageIsLeaving === true,
19204
+ visibilityState: typeof document !== 'undefined' ? document.visibilityState : null,
19205
+ });
18873
19206
  try {
18874
19207
  // One request at a time, in the order the canvas was changed: two in flight can reach the server in either
18875
19208
  // order, and the older canvas would overwrite the newer one.
@@ -18879,14 +19212,16 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18879
19212
  updateCanvasRequest: {
18880
19213
  canvasContent: parsedCanvas ?? JSON.parse(json)
18881
19214
  }
18882
- })
19215
+ }, requestInit)
18883
19216
  );
18884
19217
  canvasRecordReads.delete(saveCanvasId);
19218
+ outcome = 'saved';
19219
+ autosaveFailureToldToPerson = false;
18885
19220
  if (currentSeq < lastResolvedAutosaveSequence) {
18886
19221
  // console.log(
18887
19222
  // `[CanvasDebug] Dropped out-of-order autosave response (${currentSeq} < ${lastResolvedAutosaveSequence})`
18888
19223
  // );
18889
- return;
19224
+ return outcome;
18890
19225
  }
18891
19226
  lastResolvedAutosaveSequence = currentSeq;
18892
19227
  if (force) {
@@ -18897,10 +19232,18 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18897
19232
  // );
18898
19233
  } catch (err) {
18899
19234
  console.warn('[WidgetCreator] Failed to save canvas to API:', err);
19235
+ outcome = 'failed';
18900
19236
  if (force) {
18901
19237
  showToast('error', $t('creator.canvas.canvasSaveFailed'), {
18902
19238
  description: $t('creator.general.keptALocalCopyCheck'),
18903
19239
  });
19240
+ } else if (!isUnmountSave && !autosaveFailureToldToPerson) {
19241
+ // An automatic save the person did not ask for: said once, until a save goes through again.
19242
+ autosaveFailureToldToPerson = true;
19243
+ showToast('error', $t('creator.canvas.canvasSaveFailed'), {
19244
+ description: $t('creator.canvas.autosaveFailedWillRetry'),
19245
+ duration: 8000,
19246
+ });
18904
19247
  }
18905
19248
  }
18906
19249
  } else if (force) {
@@ -18910,7 +19253,24 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18910
19253
  });
18911
19254
  }
18912
19255
 
19256
+ // The page around the creator says "saved" once the server has the canvas (or there is no server to send it to), and
19257
+ // only if nothing was changed while the save was on its way: a refused save leaves it saying there are changes.
19258
+ if (outcome !== 'failed' && editRevisionAtStart === canvasEditRevision) emitCreatorSaveState(false);
19259
+
18913
19260
  refreshLinkedWidgetIds();
19261
+ return outcome;
19262
+ }
19263
+
19264
+ /**
19265
+ * What the canvas's own autosave calls. The same save as `handleCanvasAutoSave`, with one difference: when the API
19266
+ * refuses it, this rejects, so the canvas keeps the board marked as unsaved and asks again (a swallowed failure told
19267
+ * the person "saved" for a board the server never got). Everything else that saves the canvas keeps the quiet
19268
+ * version: a rejection there would stop a flow that does not care.
19269
+ */
19270
+ async function saveCanvasForHost(json: string | null, context?: { leaving?: boolean }): Promise<void> {
19271
+ // The canvas says when the page is going away (`pagehide`): that save has to be a request that outlives the page.
19272
+ const outcome = await handleCanvasAutoSave(json, false, { pageIsLeaving: context?.leaving === true });
19273
+ if (outcome === 'failed') throw new Error('The canvas could not be saved to the server');
18914
19274
  }
18915
19275
 
18916
19276
  /**
@@ -19882,28 +20242,63 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
19882
20242
  data-testid="embedded-sketch-panel-wrap"
19883
20243
  >
19884
20244
  <section
20245
+ data-testid={embeddedSketchShell ? 'embedded-sketch-canvas-panel' : undefined}
19885
20246
  data-sketch-mobile-tab={embeddedSketchShell ? embeddedSketchMobileTab : undefined}
19886
20247
  class="{embeddedSketchShell
19887
- ? 'embedded-sketch-canvas-panel border-border bg-background flex min-h-0 min-w-0 w-full flex-1 flex-col overflow-hidden rounded-panel max-md:data-[sketch-mobile-tab=chat]:hidden md:max-lg:row-start-1 md:max-lg:h-[600px] md:max-lg:max-h-[600px] md:max-lg:min-h-0 md:max-lg:w-full md:max-lg:flex-none max-md:flex-1 max-md:min-h-0 lg:min-h-0 lg:min-w-0'
20248
+ ? 'embedded-sketch-canvas-panel bg-background flex min-h-0 min-w-0 w-full flex-1 flex-col overflow-hidden rounded-panel max-md:data-[sketch-mobile-tab=chat]:hidden md:max-lg:row-start-1 md:max-lg:h-[600px] md:max-lg:max-h-[600px] md:max-lg:min-h-0 md:max-lg:w-full md:max-lg:flex-none max-md:flex-1 max-md:min-h-0 lg:min-h-0 lg:min-w-0'
19888
20249
  : 'contents'}"
19889
20250
  >
19890
20251
  {#if embeddedSketchShell}
20252
+ {#snippet sketchTitleMenu()}
20253
+ <DropdownMenu.Content
20254
+ class="w-[12.5rem] p-1"
20255
+ data-testid="creator-sketch-title-menu"
20256
+ align="start"
20257
+ sideOffset={4}
20258
+ >
20259
+ <DropdownMenu.Item
20260
+ data-testid="creator-title-menu-rename"
20261
+ class="h-8"
20262
+ onclick={handleSketchTitleMenuRename}
20263
+ >
20264
+ {$t('creator.name.renameWidget')}
20265
+ </DropdownMenu.Item>
20266
+ {#if canvasPrimaryWidgetId}
20267
+ <DropdownMenu.Item
20268
+ data-testid="creator-title-menu-duplicate"
20269
+ class="h-8"
20270
+ onclick={() => void handleSketchTitleMenuDuplicate()}
20271
+ >
20272
+ {$t('creator.name.duplicateWidget')}
20273
+ </DropdownMenu.Item>
20274
+ <DropdownMenu.Separator />
20275
+ <DropdownMenu.Item
20276
+ data-testid="creator-title-menu-delete"
20277
+ class="h-8 text-destructive"
20278
+ onclick={() => void handleSketchTitleMenuDelete()}
20279
+ >
20280
+ {$t('creator.widget.deleteWidget')}
20281
+ </DropdownMenu.Item>
20282
+ {/if}
20283
+ </DropdownMenu.Content>
20284
+ {/snippet}
19891
20285
  <CreatorBar
19892
20286
  class="shrink-0"
19893
20287
  title={sketchBarTitleLabel}
20288
+ titleButtonClass="min-w-0"
19894
20289
  status={sketchBarStatusLabel}
19895
- showStatus={true}
19896
- showTitleChevron={true}
20290
+ showStatus={!!sketchBarStatusLabel && !sketchBarLoading && !sketchBarCanvasGenerating}
20291
+ titleAsCaption={sketchBarLoading}
20292
+ showTitleChevron={!sketchBarLoading}
19897
20293
  showLiveBadge={sketchBarShowLiveBadge}
19898
20294
  liveLabel={$t('creator.common.live')}
19899
- showCustomize={sketchBarShowCustomize}
19900
- customizeLabel={$t('creator.sketch.customize')}
19901
- showPublish={sketchBarShowPublish}
19902
- publishLabel={sketchBarPublishLabel}
19903
- publishDisabled={!!canvasPrimaryWidgetId && isPublishDisabledForPanel(canvasPrimaryWidgetId)}
20295
+ showCustomize={false}
20296
+ showPublish={sketchBarLoading ? true : sketchBarShowPublish}
20297
+ publishLabel={sketchBarLoading ? $t('creator.common.publish') : sketchBarPublishLabel}
20298
+ publishDisabled={sketchBarLoading || sketchBarPublishDisabled}
20299
+ bind:titleMenuOpen={sketchTitleMenuOpen}
20300
+ titleMenu={sketchBarLoading ? undefined : sketchTitleMenu}
19904
20301
  onBack={() => window.dispatchEvent(new CustomEvent('widgetic:host-request-back'))}
19905
- onTitleClick={handleSketchBarTitleClick}
19906
- onCustomize={handleSketchCustomize}
19907
20302
  onPublish={() => void publish()}
19908
20303
  />
19909
20304
  {/if}
@@ -19913,6 +20308,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
19913
20308
  : 'contents'}"
19914
20309
  >
19915
20310
  <div
20311
+ data-testid="embedded-sketch-canvas-stage"
19916
20312
  class="embedded-sketch-canvas-stage flex-1 min-h-0 relative min-w-0 {embeddedSketchShell
19917
20313
  ? 'rounded-card bg-muted overflow-hidden max-md:absolute max-md:inset-0 max-md:z-0'
19918
20314
  : ''} {embeddedSketchShell && embeddedSketchMobileTab !== 'canvas'
@@ -19920,7 +20316,16 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
19920
20316
  : ''}"
19921
20317
  aria-hidden={embeddedSketchShell && embeddedSketchMobileTab !== 'canvas' ? 'true' : undefined}
19922
20318
  >
19923
- <!-- Generating, ready and failed are said in the side chat only: nothing about the generation is drawn over the canvas. -->
20319
+ {#if sketchBoardStatusChip}
20320
+ <CanvasBoardStatusChip
20321
+ variant={sketchBoardStatusChip.variant}
20322
+ label={sketchBoardStatusChipLabel(sketchBoardStatusChip.variant)}
20323
+ actionLabel={sketchBoardStatusChip.showAction
20324
+ ? sketchBoardStatusChipActionLabel(sketchBoardStatusChip.variant as 'generating' | 'failed')
20325
+ : ''}
20326
+ onAction={sketchBoardStatusChip.showAction ? handleSketchBoardStatusChipAction : undefined}
20327
+ />
20328
+ {/if}
19924
20329
  <!-- Embedded: Debug toggle lives in site AppHeader (avoids overlapping Props Panel). -->
19925
20330
  {#if canvasApiLoadError || canvasShapesMissingWarning}
19926
20331
  <div class="canvas-state-warning-ct absolute top-3 left-1/2 -translate-x-1/2 z-30 max-w-lg w-[calc(100%-2rem)] pointer-events-auto">
@@ -19953,13 +20358,13 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
19953
20358
  bind:this={canvasRef}
19954
20359
  locale={locale}
19955
20360
  messages={canvasMessages}
19956
- showContainerFrame={embeddedSketchShell || !embedded}
20361
+ showContainerFrame={!embedded}
19957
20362
  widgetSelectionLayerTarget="floating-panels-overlay"
19958
20363
  bind:wireframeMode={canvasWireframeMode}
19959
20364
  advancedFeatures={canvasAdvancedFeatures}
19960
20365
  showZoomPanel={sketchCanvasShowZoom}
19961
20366
  onReady={handleCanvasReady}
19962
- onAutoSave={handleCanvasAutoSave}
20367
+ onAutoSave={saveCanvasForHost}
19963
20368
  onBeforeUnmount={(json) => {
19964
20369
  // console.log('[CanvasDebug] onBeforeUnmount fired, json length:', json?.length ?? 0, 'lastSavedCount:', lastSavedCanvasObjectCount);
19965
20370
  handleCanvasAutoSave(json, true);
@@ -19969,10 +20374,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
19969
20374
  }}
19970
20375
  onRecognizeStroke={handleRecognizeStroke}
19971
20376
  onWidgetImageClick={handleWidgetImageClick}
19972
- onCanvasDirty={() => {
19973
- emitCreatorSaveState(true);
19974
- scheduleSketchPrefillFromCanvasDirty();
19975
- }}
20377
+ onCanvasDirty={handleCanvasDirty}
19976
20378
  onWidgetShapeDuplicated={handleWidgetShapeDuplicated}
19977
20379
  onWidgetShapeDeleting={handleWidgetShapeDeleting}
19978
20380
  onWidgetRename={handleWidgetRename}
@@ -20019,7 +20421,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
20019
20421
  workspaceId={canvasWorkspaceStorageId}
20020
20422
  workspaceFonts={canvasWorkspaceFonts ?? []}
20021
20423
  showSaveButton={sketchCanvasShowSaveButton}
20022
- autosaveDelayMs={import.meta.env.DEV ? 15000 : 5000}
20424
+ autosaveDelayMs={CANVAS_AUTOSAVE_DELAY_MS}
20023
20425
  autosaveMaxWaitMs={CANVAS_AUTOSAVE_MAX_WAIT_MS}
20024
20426
  suspendAutosave={suspendCanvasAutosave}
20025
20427
  isExternalDataLoading={!isCanvasStateLoaded}
@@ -20034,6 +20436,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
20034
20436
 
20035
20437
  <!-- FLOATING PANELS OVERLAY (pointer-events-none container, each panel is pointer-events-auto) -->
20036
20438
  <div
20439
+ data-testid={embeddedSketchShell ? 'embedded-sketch-chat-panel' : undefined}
20037
20440
  class="floating-panels-overlay z-2003 {embeddedSketchShell
20038
20441
  ? 'md:max-lg:pointer-events-auto md:max-lg:relative md:max-lg:row-start-2 md:max-lg:flex md:max-lg:h-[400px] md:max-lg:max-h-[400px] md:max-lg:min-h-0 md:max-lg:w-full md:max-lg:min-w-0 md:max-lg:flex-none md:max-lg:flex-col max-md:absolute max-md:inset-x-2 max-md:bottom-0 max-md:top-0 max-md:z-[1] max-md:flex max-md:flex-1 max-md:min-h-0 lg:pointer-events-none lg:relative lg:flex lg:w-chat-panel lg:max-w-full lg:shrink-0 lg:flex-col'
20039
20442
  : 'pointer-events-none absolute inset-0'} {embeddedSketchShell && embeddedSketchMobileTab !== 'chat'
@@ -21082,11 +21485,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
21082
21485
  <!-- Svelte 5: `{@const}` must be the direct child of a block; this wrapper exists only for dockedChatPanel and composerModelOptions. -->
21083
21486
  {#if true}
21084
21487
  {@const dockedChatPanel = embedded && !canvasAdvancedFeatures}
21085
- {@const composerModelOptions = dockedChatPanel
21086
- ? debugMode
21087
- ? availableModels.map((model) => ({ id: model.id, label: model.name }))
21088
- : [{ id: ASSISTANT_MODEL_ID, label: $t('creator.codegen.assistantModelLabel') }]
21089
- : debugMode
21488
+ {@const composerModelOptions =
21489
+ debugMode && debugModeAvailable
21090
21490
  ? availableModels.map((model) => ({ id: model.id, label: model.name }))
21091
21491
  : []}
21092
21492
  <Chat class="code-generation-chat h-full w-full max-w-full rounded-none border-0"
@@ -21692,26 +22092,17 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
21692
22092
  <Dialog.Root bind:open={deleteDialogOpen} onOpenChange={(open) => { if (!open) handleDeleteDialogResponse('cancel'); }}>
21693
22093
  <Dialog.Content closeLabel={$t('creator.common.close')} layerBase={creatorDialogLayerBase} class="confirm-delete-dialog-content max-w-md bg-white z-9999">
21694
22094
  <Dialog.Header class="confirm-delete-dialog-header">
21695
- <Dialog.Title>{$t('creator.widget.deleteWidgetShape')}</Dialog.Title>
21696
- <Dialog.Description>
21697
- {#each sentenceParts(deleteDialogStep === 'confirm-remove' ? 'creator.dialog.removeShape' : 'creator.dialog.alsoDeleteWidget', ['name'], $t) as part}
21698
- {#if 'text' in part}{part.text}{:else}<strong>"{deleteDialogWidgetName}"</strong>{/if}
21699
- {/each}
21700
- </Dialog.Description>
22095
+ <Dialog.Title>{$t('creator.widget.deleteWidget')}</Dialog.Title>
21701
22096
  </Dialog.Header>
21702
22097
 
21703
22098
  <div class="confirm-delete-dialog-action-ct flex justify-end gap-2 pt-2">
21704
22099
  {#if deleteDialogStep === 'confirm-remove'}
21705
- <button
21706
- type="button"
21707
- class="px-4 py-2 text-sm rounded-lg border border-gray-300 hover:bg-gray-100 cursor-pointer"
21708
- onclick={() => handleDeleteDialogResponse('cancel')}
21709
- >{$t('creator.general.cancel')}</button>
21710
- <button
21711
- type="button"
21712
- class="px-4 py-2 text-sm rounded-lg bg-red-600 hover:bg-red-700 text-white cursor-pointer"
21713
- onclick={() => handleDeleteDialogResponse('remove-and-ask-db')}
21714
- >{$t('creator.common.delete')}</button>
22100
+ <Button variant="outline" size="sm" onclick={() => handleDeleteDialogResponse('cancel')}>
22101
+ {$t('creator.general.cancel')}
22102
+ </Button>
22103
+ <Button variant="destructive" size="sm" onclick={() => handleDeleteDialogResponse('remove-and-ask-db')}>
22104
+ {$t('creator.widget.deleteWidget')}
22105
+ </Button>
21715
22106
  {:else if ASK_DELETE_FROM_DB_CONFIRM}
21716
22107
  <button
21717
22108
  type="button"