@widgetic/creator 0.4.28 → 0.4.30

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.
@@ -493,10 +493,19 @@
493
493
  const gate = targetId ? getPublishGateForPanel(targetId) : null;
494
494
  const canPublish = !!gate && !gate.disabled;
495
495
  const label = gate?.label || $t('creator.common.publish');
496
- const signature = `${targetId}:${canPublish}:${label}:${panelDisplayRevision}:${isPublishing}:${generatingMark}`;
496
+ const publishedAlready = !!targetId && getPanelDisplayState(targetId).lastPublishedVersion !== null;
497
+ const unpublished = canPublish && (
498
+ /publish new v/i.test(label)
499
+ || (publishedAlready && hasUnpublishedChangesForPanel(targetId))
500
+ );
501
+ const signature = `${targetId}:${canPublish}:${label}:${unpublished}:${panelDisplayRevision}:${isPublishing}:${generatingMark}`;
497
502
  if (signature !== lastAnnouncedPublishState) {
498
503
  lastAnnouncedPublishState = signature;
499
- announceToSite(CREATOR_PUBLISH_STATE_EVENT, { canPublish, label });
504
+ announceToSite(CREATOR_PUBLISH_STATE_EVENT, {
505
+ canPublish,
506
+ label: unpublished ? 'Publish changes' : label,
507
+ unpublished,
508
+ });
500
509
  }
501
510
  }
502
511
 
@@ -1342,6 +1351,13 @@
1342
1351
  // while the repository save is still finishing. The canvas shape stays
1343
1352
  // deferred because generatingWidgetIds is still set.
1344
1353
  let previewUnblockedByWidgetId: Record<string, boolean> = {};
1354
+ /** The status line was set when the preview appeared. A later GitLab save must not write "Preview ready" again. */
1355
+ let previewReadyAnnouncedByWidgetId: Record<string, boolean> = {};
1356
+ /** Publish stays hidden until about five seconds after the preview is on screen. */
1357
+ let publishHeldByWidgetId: Record<string, boolean> = {};
1358
+ const PREVIEW_READY_STATUS = 'Generation complete (100%) · Preview ready';
1359
+ const PUBLISH_REVEAL_DELAY_MS = 5000;
1360
+ const publishRevealTimers = new Map<string, ReturnType<typeof setTimeout>>();
1345
1361
  /** Last slice of the model stream, per widget. Painted with the status throttle, not per token. */
1346
1362
  let generationStreamByWidgetId: Record<string, string> = {};
1347
1363
  function isAnyWidgetGenerating(): boolean {
@@ -1764,7 +1780,13 @@
1764
1780
  captureCanvasSketch?: () => Promise<string>;
1765
1781
  absorbCanvasSketchIntoWidget?: (widgetId: string, screenshotDataUrl: string) => Promise<string | null>;
1766
1782
  }) | null;
1767
- if (embedded && !canvasAdvancedFeatures && sketchCanvas?.captureCanvasSketch) {
1783
+ const sketchPanel = getPanelState(widgetId);
1784
+ const widgetAlreadyBuilt = !isDraftConvertId(widgetId) && !!(
1785
+ sketchPanel.lastCommitId || sketchPanel.hasGeneratedCode || sketchPanel.lastPublishedVersion != null
1786
+ );
1787
+ // The board sketch belongs on the first prompt only. A later message was
1788
+ // picking up the line on the canvas instead of the widget.
1789
+ if (!widgetAlreadyBuilt && embedded && !canvasAdvancedFeatures && sketchCanvas?.captureCanvasSketch) {
1768
1790
  try {
1769
1791
  const canvasSketch = await sketchCanvas.captureCanvasSketch();
1770
1792
  if (canvasSketch?.startsWith('data:image/')) {
@@ -1781,6 +1803,16 @@
1781
1803
  ...(attachments || []),
1782
1804
  { url: canvasSketch, fileType: 'image/png', fileName: 'design-screenshot.png' },
1783
1805
  ];
1806
+ getChatMethodsForWidget(widgetId)?.updateLastUserMessageAttachments?.(
1807
+ (attachments || [])
1808
+ .filter((attachment) => typeof attachment.url === 'string' && attachment.url.length > 0)
1809
+ .map((attachment) => ({
1810
+ url: attachment.url,
1811
+ file_type: attachment.fileType,
1812
+ file_name: attachment.fileName ?? null,
1813
+ })),
1814
+ );
1815
+ console.log('[Chat→Sketch] Sketch attached to the sent message', widgetId.substring(0, 8));
1784
1816
  }
1785
1817
  }
1786
1818
  } catch (captureError) {
@@ -2101,6 +2133,7 @@
2101
2133
  const retryImageAttachments = retryFileAttachments.filter((attachment) => {
2102
2134
  const type = String(attachment.file_type || '');
2103
2135
  const name = String(attachment.file_name || '');
2136
+ if (/design-screenshot|attached-sketch/i.test(name)) return false;
2104
2137
  return type.startsWith('image/') || /\.(png|jpe?g|gif|webp|svg)(\?|$)/i.test(name) || /\.(png|jpe?g|gif|webp|svg)(\?|$)/i.test(attachment.url);
2105
2138
  });
2106
2139
  const retryUploadIds = [
@@ -4550,14 +4583,7 @@
4550
4583
  // Clear stuck "Code saved — loading preview…" once the iframe has content
4551
4584
  const panelStatus = getPanelState(panelWidgetId).generateCodeStatus || '';
4552
4585
  if (/loading preview|building preview|preview rebuilt from saved code/i.test(panelStatus)) {
4553
- const panelCommit =
4554
- getPanelState(panelWidgetId).lastCommitId || loadCommitIdForWidget(panelWidgetId);
4555
- const commitShort = panelCommit ? panelCommit.substring(0, 7) : '';
4556
- patchCodegenUiState(panelWidgetId, {
4557
- hasGeneratedCode: true,
4558
- ...(panelCommit ? { lastCommitId: panelCommit } : {}),
4559
- generateCodeStatus: `Code generation completed!${commitShort ? ` Commit: ${commitShort}` : ''} Preview ready.`,
4560
- });
4586
+ markGenerationPreviewReady(panelWidgetId);
4561
4587
  }
4562
4588
  if (event.detail.step === 'create') {
4563
4589
  let psCreate = getPanelDisplayState(panelWidgetId);
@@ -4777,6 +4803,35 @@
4777
4803
  'enforce'
4778
4804
  ) as 'off' | 'shadow' | 'enforce';
4779
4805
 
4806
+ /** Same-origin previews: set the CSS variables directly, so a color shows while the field is still focused. */
4807
+ function paintDesignVarsOnPreview(widgetId: string, design: Record<string, unknown>): void {
4808
+ const frames = [
4809
+ getWidgetDetailsRef(widgetId)?.getPreviewIframe?.() ?? null,
4810
+ resolveLiveWidgetShapeIframe(widgetId)
4811
+ ];
4812
+ for (const frame of frames) {
4813
+ const doc = frame?.contentDocument;
4814
+ if (!doc) continue;
4815
+ const roots = [
4816
+ doc.documentElement,
4817
+ doc.body,
4818
+ doc.querySelector('.widget-root'),
4819
+ doc.querySelector('#widget-root'),
4820
+ doc.querySelector('[data-widget-root]')
4821
+ ].filter((node, index, list): node is HTMLElement => node instanceof HTMLElement && list.indexOf(node) === index);
4822
+ for (const [key, value] of Object.entries(design)) {
4823
+ if (!key || value == null) continue;
4824
+ for (const root of roots) {
4825
+ try {
4826
+ root.style.setProperty('--' + key, String(value));
4827
+ } catch (error) {
4828
+ console.warn('[CreatorApp] Could not paint a design variable on the preview', key, error);
4829
+ }
4830
+ }
4831
+ }
4832
+ }
4833
+ }
4834
+
4780
4835
  /** Apply design values to the live preview + persist, mirroring the editor path. */
4781
4836
  let designEditsByWidgetId: Record<string, Record<string, unknown>> = {};
4782
4837
 
@@ -4799,15 +4854,24 @@
4799
4854
  };
4800
4855
  getWidgetDetailsRef(widgetId)?.sendMessageToPreview(designMessage);
4801
4856
  resolveLiveWidgetShapeIframe(widgetId)?.contentWindow?.postMessage(designMessage, '*');
4857
+ paintDesignVarsOnPreview(widgetId, designMessage.design);
4802
4858
  compositionDirty = true;
4803
4859
  if (widgetId === focusedPanelWidgetId) {
4804
4860
  syncFocusedPanelEditorSnapshot();
4805
- // Design edits are committed as soon as they are made, so the next codegen
4806
- // turn already sees the updated values.
4861
+ scheduleDesignPersist(widgetId);
4862
+ }
4863
+ }
4864
+
4865
+ let designPersistTimer: ReturnType<typeof setTimeout> | null = null;
4866
+ /** The preview updates on each key. The composition save waits until typing pauses, so a slow save cannot put the old color back. */
4867
+ function scheduleDesignPersist(widgetId: string): void {
4868
+ if (designPersistTimer) clearTimeout(designPersistTimer);
4869
+ designPersistTimer = setTimeout(() => {
4870
+ designPersistTimer = null;
4807
4871
  if (selectedComposition && selectedWidgetId === widgetId) {
4808
4872
  void updateCompositionValues();
4809
4873
  }
4810
- }
4874
+ }, 400);
4811
4875
  }
4812
4876
 
4813
4877
  /**
@@ -6702,18 +6766,6 @@
6702
6766
  if (panelHadPublishedVersion) patchPanelSnapshot(widgetId, { pendingPublishAfterCodegen: true });
6703
6767
  panelDisplayRevision += 1;
6704
6768
 
6705
- if (announce) {
6706
- const isFocusedPanel = widgetId === focusedPanelWidgetId;
6707
- const completedWidgetName = getWidgetById(widgetId)?.name || 'widget';
6708
- showToast(
6709
- 'success',
6710
- isFocusedPanel ? $t('creator.codegen.codeGenerationCompleted') : $t('creator.codegen.generationCompleted', { name: completedWidgetName }),
6711
- {
6712
- description: isFocusedPanel ? $t('creator.codegen.codeSavedToGitlabAnd') : $t('creator.general.switchToThatPanelTo'),
6713
- duration: 5000
6714
- }
6715
- );
6716
- }
6717
6769
  setTimeout(() => {
6718
6770
  void refreshWidgetAfterRemoteGeneration(widgetId);
6719
6771
  }, 800);
@@ -6747,7 +6799,8 @@
6747
6799
  shapePreviewSourceByWidgetId = { ...shapePreviewSourceByWidgetId, [widgetId]: 'preview' };
6748
6800
  syncWidgetShapeLivePreviews();
6749
6801
  widgetShapeLivePreviewsRef?.requestReload?.(widgetId);
6750
- patchCodegenUiState(widgetId, { generateCodeStatus: 'Code generation completed! Preview ready.' });
6802
+ patchCodegenUiState(widgetId, { generateCodeStatus: PREVIEW_READY_STATUS });
6803
+ markGenerationPreviewReady(widgetId);
6751
6804
  void refreshTrialCounter();
6752
6805
  setTimeout(async () => {
6753
6806
  try {
@@ -8693,9 +8746,18 @@
8693
8746
  await getWidgetDetailsRef(selectedWidgetId)?.loadWidget(selectedWidgetId);
8694
8747
  }
8695
8748
 
8696
- // Auto-create repository if widget has none (silently, in background)
8749
+ // A repo is created when the widget is actually started (a prompt is typed, or Send).
8750
+ // Opening a sketch must not create one — that used to make a repo for every untouched widget.
8697
8751
  if (widget?.id && !normalizeRepositoryId(widget)) {
8698
8752
  const capturedId = widget.id;
8753
+ const panel = getPanelState(capturedId);
8754
+ const started = !!(
8755
+ panel.lastCommitId
8756
+ || panel.lastPublishedVersion != null
8757
+ || panel.hasGeneratedCode
8758
+ || (conversationsByWidgetId[capturedId]?.length ?? 0) > 0
8759
+ );
8760
+ if (started) {
8699
8761
  repositorySetupByWidgetId = { ...repositorySetupByWidgetId, [capturedId]: 'pending' };
8700
8762
  ensureWidgetRepository(widget, { silent: true }).then((repoId) => {
8701
8763
  if (repoId) {
@@ -8716,8 +8778,10 @@
8716
8778
  repositorySetupByWidgetId = { ...repositorySetupByWidgetId, [capturedId]: 'failed' };
8717
8779
  console.warn('[WidgetCreator] Auto-repo creation failed:', err);
8718
8780
  });
8781
+ }
8719
8782
  } else if (widget?.id && normalizeRepositoryId(widget)) {
8720
8783
  repositorySetupByWidgetId = { ...repositorySetupByWidgetId, [widget.id]: 'ready' };
8784
+ void prewarmWidgetCodegenOnTyping(widget.id);
8721
8785
  }
8722
8786
 
8723
8787
  if (
@@ -10689,6 +10753,12 @@ Requirements:
10689
10753
  cancelQuietScreenshots();
10690
10754
  cancelIdleThumbnailPersist();
10691
10755
  widgetShapeLivePreviewsRef?.cancelReloads?.();
10756
+ if (options.fromChat) {
10757
+ console.log('[Chat→Preview] Reloading preview iframe on send', generationWidgetId.substring(0, 8));
10758
+ widgetShapeLivePreviewsRef?.requestReload?.(generationWidgetId, { immediate: true });
10759
+ void getWidgetDetailsRef(generationWidgetId)?.refreshPreview?.();
10760
+ }
10761
+ holdPublishForGeneration(generationWidgetId);
10692
10762
  if (restoredViewingVersionByWidgetId[generationWidgetId] != null) {
10693
10763
  const { [generationWidgetId]: _droppedRestore, ...restRestored } = restoredViewingVersionByWidgetId;
10694
10764
  restoredViewingVersionByWidgetId = restRestored;
@@ -10968,6 +11038,57 @@ Requirements:
10968
11038
  // a generation slot. Anything unexpected here falls through to the
10969
11039
  // normal path (operation tracking), never blocks a real build.
10970
11040
  const gatedData = (response as any)?.data;
11041
+ if (gatedData?.gated === true && gatedData.action === 'property_edit') {
11042
+ const propertyKey = typeof gatedData.key === 'string' ? gatedData.key : '';
11043
+ const propertyValue = gatedData.value;
11044
+ clearActiveOperationId(generationWidgetId);
11045
+ if (propertyKey && gatedData.group !== 'content') {
11046
+ applyDesignValuesToPreview(generationWidgetId, { [propertyKey]: propertyValue });
11047
+ }
11048
+ const psNow = getPanelDisplayState(generationWidgetId);
11049
+ const schemaProp = collectDesignProperties(psNow.compositionDesignSchema).find(
11050
+ (property) => property.id === propertyKey || property.id.endsWith(`.${propertyKey}`)
11051
+ );
11052
+ const label = schemaProp?.label || propertyKey;
11053
+ const card: DesignControlRequest = {
11054
+ summary: gatedData.reply || `Set ${label} to ${String(propertyValue)}.`,
11055
+ properties: propertyKey
11056
+ ? [{
11057
+ id: schemaProp?.id || propertyKey,
11058
+ label,
11059
+ controllerType: schemaProp?.controllerType ?? '',
11060
+ value: propertyValue,
11061
+ options: schemaProp?.options,
11062
+ min: schemaProp?.min,
11063
+ max: schemaProp?.max,
11064
+ step: schemaProp?.step,
11065
+ helpText: schemaProp?.helpText,
11066
+ }]
11067
+ : [],
11068
+ compositionId: psNow.selectedComposition?.id ?? gatedData.compositionId ?? null,
11069
+ };
11070
+ getChatMethodsForWidget(generationWidgetId)?.addDesignControlsMessage?.(card.summary, card);
11071
+ patchCodegenUiState(generationWidgetId, {
11072
+ lastGenerationFailed: false,
11073
+ lastGenerationError: null,
11074
+ generateCodeStatus: 'Ready',
11075
+ });
11076
+ if (debugMode) {
11077
+ showToast('info', $t('creator.codegen.noGenerationStarted'), {
11078
+ description: String(gatedData.reply || '').slice(0, 140),
11079
+ duration: 8000,
11080
+ });
11081
+ }
11082
+ generatingWidgetIds = (() => {
11083
+ const { [generationWidgetId]: _gated, ...rest } = generatingWidgetIds;
11084
+ return rest;
11085
+ })();
11086
+ isGeneratingCode = !!(focusedPanelWidgetId && generatingWidgetIds[focusedPanelWidgetId]);
11087
+ setCrossTabGenerating(false, generationWidgetId);
11088
+ widgetAbortControllers.delete(generationWidgetId);
11089
+ console.log('[DesignIntent] Applied a property edit without generating', propertyKey);
11090
+ return;
11091
+ }
10971
11092
  if (gatedData?.gated === true && typeof gatedData.action === 'string' && gatedData.action !== 'generate') {
10972
11093
  const gatedAction = gatedData.action as 'answer' | 'redirect' | 'clarify';
10973
11094
  const gatedReply: string = gatedData.reply ?? '';
@@ -10994,14 +11115,16 @@ Requirements:
10994
11115
  chatMethods.addAssistantMessage(gatedReply);
10995
11116
  }
10996
11117
 
10997
- showToast(
10998
- gatedAction === 'answer' ? 'info' : 'warning',
10999
- gatedAction === 'answer' ? $t('creator.codegen.answeredWithoutGenerating') : $t('creator.codegen.noGenerationStarted'),
11000
- {
11001
- description: gatedReply.slice(0, 140),
11002
- duration: 8000,
11003
- },
11004
- );
11118
+ if (debugMode) {
11119
+ showToast(
11120
+ gatedAction === 'answer' ? 'info' : 'warning',
11121
+ gatedAction === 'answer' ? $t('creator.codegen.answeredWithoutGenerating') : $t('creator.codegen.noGenerationStarted'),
11122
+ {
11123
+ description: gatedReply.slice(0, 140),
11124
+ duration: 8000,
11125
+ },
11126
+ );
11127
+ }
11005
11128
  generatingWidgetIds = (() => {
11006
11129
  const { [generationWidgetId]: _gated, ...rest } = generatingWidgetIds;
11007
11130
  return rest;
@@ -11114,7 +11237,7 @@ Requirements:
11114
11237
  ...previewUnblockedByWidgetId,
11115
11238
  [generationWidgetId]: true,
11116
11239
  };
11117
- panelChat?.updateLatestCodegenStatusMessage?.('Preview ready');
11240
+ markGenerationPreviewReady(generationWidgetId);
11118
11241
  options.onPreviewVisible?.();
11119
11242
  }
11120
11243
  }
@@ -11378,11 +11501,18 @@ Requirements:
11378
11501
  const commitShort = completedCommitSha ? completedCommitSha.substring(0, 7) : '';
11379
11502
  const unsavedText = repositorySaveError
11380
11503
  || 'Code was not saved to the repository. Retry saves it and records a version.';
11504
+ const previewAlreadyOnCanvas = !!(
11505
+ previewReadyAnnouncedByWidgetId[generationWidgetId]
11506
+ || previewUnblockedByWidgetId[generationWidgetId]
11507
+ || runningWorkerPreviewUrlByWidgetId[generationWidgetId]
11508
+ );
11381
11509
  const savedStatus = !completedCommitSha
11382
11510
  ? unsavedText
11383
- : completedPreviewBuildErr
11384
- ? `Code saved (${commitShort}) — building preview…`
11385
- : `Code saved (${commitShort}) — loading preview…`;
11511
+ : previewAlreadyOnCanvas
11512
+ ? PREVIEW_READY_STATUS
11513
+ : completedPreviewBuildErr
11514
+ ? `Code saved (${commitShort}) — building preview…`
11515
+ : `Code saved (${commitShort}) — loading preview…`;
11386
11516
  const shownFailure = [completedPreviewBuildErr, !completedCommitSha ? unsavedText : null]
11387
11517
  .filter((part): part is string => !!part)
11388
11518
  .join('\n');
@@ -11393,6 +11523,9 @@ Requirements:
11393
11523
  lastGenerationError: shownFailure || null,
11394
11524
  generateCodeStatus: savedStatus,
11395
11525
  });
11526
+ if (previewAlreadyOnCanvas && completedCommitSha && !completedPreviewBuildErr) {
11527
+ markGenerationPreviewReady(generationWidgetId);
11528
+ }
11396
11529
 
11397
11530
  if (!completedCached) {
11398
11531
  panelChat?.updateLatestCodegenStatusMessage?.(savedStatus);
@@ -11416,7 +11549,7 @@ Requirements:
11416
11549
  description: repositorySaveError || $t('creator.codegen.retrySavesItAndRecordsAVersion'),
11417
11550
  duration: 8000
11418
11551
  });
11419
- } else {
11552
+ } else if (debugMode) {
11420
11553
  showToast(
11421
11554
  'success',
11422
11555
  isFocusedPanel ? $t('creator.codegen.codeGenerationCompleted') : $t('creator.codegen.generationCompleted', { name: completedWidgetName }),
@@ -11462,7 +11595,7 @@ Requirements:
11462
11595
  // Served from the operation metadata; the server also embeds it in the
11463
11596
  // persisted reply, so it survives a reload.
11464
11597
  const designContractWarning = getOperationDesignContractWarning(op.metadata);
11465
- if (designContractWarning) {
11598
+ if (designContractWarning && debugMode) {
11466
11599
  panelChat?.addAssistantMessage(designContractWarning, true);
11467
11600
  }
11468
11601
 
@@ -11500,10 +11633,10 @@ Requirements:
11500
11633
  // cache-busts the same URL and looks like an extra reload.
11501
11634
  // console.log('[CreatorApp] Skipping extra preview remount — Worker iframe already showing');
11502
11635
  activePanelRef?.setPreviewLoadingState(false);
11503
- // previewReady may not re-fire when we skip remount — clear stuck status.
11504
- patchCodegenUiState(generationWidgetId, {
11505
- generateCodeStatus: `Code generation completed!${commitShort ? ` Commit: ${commitShort}` : ''} Preview ready.`,
11506
- });
11636
+ // The running preview already wrote the status. Don't write "Preview ready" again.
11637
+ if (!previewReadyAnnouncedByWidgetId[generationWidgetId]) {
11638
+ markGenerationPreviewReady(generationWidgetId);
11639
+ }
11507
11640
  } else {
11508
11641
  activePanelRef?.setPreviewLoadingState(true);
11509
11642
  await activePanelRef?.refreshPreview?.({ withRetry: true, skipIfAlreadyShowing: true });
@@ -11531,12 +11664,9 @@ Requirements:
11531
11664
  } else if (!completedPreviewBuildErr) {
11532
11665
  await applyDesignSchemaDefaultsToPreview(generationWidgetId);
11533
11666
  pendingCreatePreviewDefaultsWidgetId = null;
11534
- panelChat?.updateLatestCodegenStatusMessage?.(
11535
- `Code generation completed!${commitShort ? ` Commit: ${commitShort}` : ''}\nPreview ready.`,
11536
- );
11537
- patchCodegenUiState(generationWidgetId, {
11538
- generateCodeStatus: `Code generation completed!${commitShort ? ` Commit: ${commitShort}` : ''} Preview ready.`,
11539
- });
11667
+ if (!previewReadyAnnouncedByWidgetId[generationWidgetId]) {
11668
+ markGenerationPreviewReady(generationWidgetId);
11669
+ }
11540
11670
  void refreshTrialCounter();
11541
11671
  setTimeout(async () => {
11542
11672
  await panelChat?.reloadConversationMessages?.();
@@ -11691,11 +11821,13 @@ Requirements:
11691
11821
  // Update global flag: true only if the CURRENT widget is still generating
11692
11822
  isGeneratingCode = !!(focusedPanelWidgetId && generatingWidgetIds[focusedPanelWidgetId]);
11693
11823
  setCrossTabGenerating(false, generationWidgetId);
11694
- // The reload requested while generation was still on was deferred and kept the previous iframe.
11695
- // Wait until that flag has reached the shape, then load the new document immediately.
11696
- void tick().then(() => {
11697
- widgetShapeLivePreviewsRef?.requestReload?.(generationWidgetId, { immediate: true });
11698
- });
11824
+ // A finished run already loads the new preview. Reloading here as well
11825
+ // flashed the shape a second time. A failed run still needs the one reload.
11826
+ if (getPanelState(generationWidgetId).lastGenerationFailed) {
11827
+ void tick().then(() => {
11828
+ widgetShapeLivePreviewsRef?.requestReload?.(generationWidgetId, { immediate: true });
11829
+ });
11830
+ }
11699
11831
  }
11700
11832
  }
11701
11833
  }
@@ -12370,6 +12502,18 @@ Requirements:
12370
12502
  return () => window.removeEventListener('keydown', handleEscapeCapture, { capture: true });
12371
12503
  });
12372
12504
 
12505
+ onMount(() => {
12506
+ const closeSelectorOnSelectTool = () => {
12507
+ const next: Record<string, boolean> = {};
12508
+ for (const widgetId of Object.keys(selectorEnabledByWidgetId)) next[widgetId] = false;
12509
+ selectorEnabledByWidgetId = next;
12510
+ panelDisplayRevision += 1;
12511
+ console.log('[WidgetShape] Select tool closes the element selector');
12512
+ };
12513
+ window.addEventListener('widgetic:canvas-select-tool', closeSelectorOnSelectTool);
12514
+ return () => window.removeEventListener('widgetic:canvas-select-tool', closeSelectorOnSelectTool);
12515
+ });
12516
+
12373
12517
  // Capture-phase paste: redirect clipboard images to prompt images
12374
12518
  // ONLY when the paste target is inside the widget-details panel or widgets-list
12375
12519
  // (e.g., user is focused on the prompt input). If target is body/document/canvas area,
@@ -12547,9 +12691,10 @@ Requirements:
12547
12691
  /** The canvas iframe painted, so the chat is no longer waiting on a hidden side preview. */
12548
12692
  function noteShapePreviewShown(widgetId: string): void {
12549
12693
  const status = getPanelDisplayState(widgetId).generateCodeStatus || '';
12550
- if (!status.includes('loading preview')) return;
12551
- patchCodegenUiState(widgetId, { generateCodeStatus: 'Preview ready' });
12552
- getChatMethodsForWidget(widgetId)?.updateLatestCodegenStatusMessage?.('Preview ready');
12694
+ const waitingOnPreview = /loading preview|building preview|generating code|code generation in progress|code saved/i.test(status);
12695
+ const generationRunning = !!generatingWidgetIds[widgetId] || !!previewUnblockedByWidgetId[widgetId];
12696
+ if (!waitingOnPreview && !generationRunning) return;
12697
+ markGenerationPreviewReady(widgetId);
12553
12698
  }
12554
12699
 
12555
12700
  function getOperationPreviewBuildError(metadata?: Record<string, unknown>): string | null {
@@ -12645,10 +12790,79 @@ Requirements:
12645
12790
  return typeof raw === 'string' ? raw.slice(-1600) : '';
12646
12791
  }
12647
12792
 
12793
+ function holdPublishForGeneration(widgetId: string): void {
12794
+ const pending = publishRevealTimers.get(widgetId);
12795
+ if (pending) {
12796
+ clearTimeout(pending);
12797
+ publishRevealTimers.delete(widgetId);
12798
+ }
12799
+ publishHeldByWidgetId = { ...publishHeldByWidgetId, [widgetId]: true };
12800
+ if (previewReadyAnnouncedByWidgetId[widgetId]) {
12801
+ const next = { ...previewReadyAnnouncedByWidgetId };
12802
+ delete next[widgetId];
12803
+ previewReadyAnnouncedByWidgetId = next;
12804
+ }
12805
+ }
12806
+
12807
+ function releasePublishHold(widgetId: string): void {
12808
+ const pending = publishRevealTimers.get(widgetId);
12809
+ if (pending) {
12810
+ clearTimeout(pending);
12811
+ publishRevealTimers.delete(widgetId);
12812
+ }
12813
+ if (!publishHeldByWidgetId[widgetId]) return;
12814
+ const next = { ...publishHeldByWidgetId };
12815
+ delete next[widgetId];
12816
+ publishHeldByWidgetId = next;
12817
+ panelDisplayRevision += 1;
12818
+ }
12819
+
12820
+ function schedulePublishReveal(widgetId: string): void {
12821
+ const pending = publishRevealTimers.get(widgetId);
12822
+ if (pending) clearTimeout(pending);
12823
+ publishRevealTimers.set(widgetId, setTimeout(() => {
12824
+ publishRevealTimers.delete(widgetId);
12825
+ releasePublishHold(widgetId);
12826
+ console.log('[CodeGen] Publish revealed after preview', widgetId.substring(0, 8));
12827
+ }, PUBLISH_REVEAL_DELAY_MS));
12828
+ }
12829
+
12830
+ function cancelPendingCodegenStatus(widgetId: string): void {
12831
+ if (codegenStatusTimers[widgetId]) {
12832
+ clearTimeout(codegenStatusTimers[widgetId]);
12833
+ delete codegenStatusTimers[widgetId];
12834
+ }
12835
+ delete codegenStatusPendingLine[widgetId];
12836
+ delete codegenStreamPending[widgetId];
12837
+ if (codegenChatStatusTimers[widgetId]) {
12838
+ clearTimeout(codegenChatStatusTimers[widgetId]);
12839
+ delete codegenChatStatusTimers[widgetId];
12840
+ }
12841
+ delete codegenChatStatusPendingLine[widgetId];
12842
+ }
12843
+
12844
+ /** Preview is on screen. Status settles once. Publish waits about five seconds. GitLab keeps saving. */
12845
+ function markGenerationPreviewReady(widgetId: string): void {
12846
+ const alreadyAnnounced = !!previewReadyAnnouncedByWidgetId[widgetId];
12847
+ if (!alreadyAnnounced) {
12848
+ previewReadyAnnouncedByWidgetId = { ...previewReadyAnnouncedByWidgetId, [widgetId]: true };
12849
+ cancelPendingCodegenStatus(widgetId);
12850
+ schedulePublishReveal(widgetId);
12851
+ console.log('[CodeGen] Preview ready', widgetId.substring(0, 8));
12852
+ }
12853
+ const current = getPanelState(widgetId).generateCodeStatus || '';
12854
+ if (current === PREVIEW_READY_STATUS) return;
12855
+ patchCodegenUiState(widgetId, { generateCodeStatus: PREVIEW_READY_STATUS });
12856
+ if (!alreadyAnnounced) {
12857
+ getChatMethodsForWidget(widgetId)?.updateLatestCodegenStatusMessage?.(PREVIEW_READY_STATUS);
12858
+ }
12859
+ }
12860
+
12648
12861
  function pushCodegenProgressToUi(op: OperationStatus, widgetId: string | null | undefined) {
12649
12862
  // The preview is already on the canvas while the version is still saving.
12650
12863
  // The bar stays at 70 until that save ends, so show 100 for that pause.
12651
12864
  const stillRunning = String(op.status || '').toLowerCase() === 'running';
12865
+ if (widgetId && previewReadyAnnouncedByWidgetId[widgetId] && stillRunning) return;
12652
12866
  const versionStillSaving = !!(widgetId && previewUnblockedByWidgetId[widgetId] && stillRunning);
12653
12867
  const shown = versionStillSaving ? { ...op, progress: 100 } : op;
12654
12868
  const line = formatCodegenProgressStatus(shown);
@@ -12696,7 +12910,7 @@ Requirements:
12696
12910
  const pendingTail = codegenStreamPending[widgetId];
12697
12911
  delete codegenStatusPendingLine[widgetId];
12698
12912
  delete codegenStreamPending[widgetId];
12699
- if (pending) patchCodegenUiState(widgetId, { generateCodeStatus: pending });
12913
+ if (pending && !previewReadyAnnouncedByWidgetId[widgetId]) patchCodegenUiState(widgetId, { generateCodeStatus: pending });
12700
12914
  if (pendingTail && pendingTail !== generationStreamByWidgetId[widgetId]) {
12701
12915
  generationStreamByWidgetId = { ...generationStreamByWidgetId, [widgetId]: pendingTail };
12702
12916
  }
@@ -12715,7 +12929,9 @@ Requirements:
12715
12929
  delete codegenChatStatusTimers[key];
12716
12930
  const pending = codegenChatStatusPendingLine[key];
12717
12931
  delete codegenChatStatusPendingLine[key];
12718
- if (pending) getChatMethodsForWidget(widgetId)?.updateLatestCodegenStatusMessage?.(pending);
12932
+ if (pending && !(widgetId && previewReadyAnnouncedByWidgetId[widgetId])) {
12933
+ getChatMethodsForWidget(widgetId)?.updateLatestCodegenStatusMessage?.(pending);
12934
+ }
12719
12935
  }, CODEGEN_STATUS_THROTTLE_MS);
12720
12936
  }
12721
12937
 
@@ -15069,6 +15285,10 @@ Requirements:
15069
15285
  }
15070
15286
 
15071
15287
  function hasUnpublishedChangesForPanel(widgetId: string): boolean {
15288
+ if (publishHeldByWidgetId[widgetId]) return false;
15289
+ if (generatingWidgetIds[widgetId] && !previewReadyAnnouncedByWidgetId[widgetId]) return false;
15290
+ // Preview is up and the five seconds have passed. GitLab may still be saving.
15291
+ if (generatingWidgetIds[widgetId] && previewReadyAnnouncedByWidgetId[widgetId]) return true;
15072
15292
  const ps = getPanelDisplayState(widgetId);
15073
15293
  if (ps.pendingPublishAfterCodegen) return true;
15074
15294
 
@@ -15203,7 +15423,12 @@ Requirements:
15203
15423
  showDisabledHint: true,
15204
15424
  };
15205
15425
  }
15206
- if (generatingWidgetIds[widgetId]) {
15426
+ const gitlabSaveStillRunning = !!(
15427
+ generatingWidgetIds[widgetId]
15428
+ && previewReadyAnnouncedByWidgetId[widgetId]
15429
+ && !publishHeldByWidgetId[widgetId]
15430
+ );
15431
+ if (generatingWidgetIds[widgetId] && !gitlabSaveStillRunning) {
15207
15432
  return {
15208
15433
  disabled: true,
15209
15434
  label: getPublishButtonLabelFallback(ps),
@@ -15483,15 +15708,23 @@ $: if ($widgetPublishStatus.timestamp && $widgetPublishStatus.widgetId) {
15483
15708
  // console.log('[Publish] WS success — refreshing preview after publish for', publishWidgetId.substring(0, 8));
15484
15709
  void getWidgetDetailsRef(publishWidgetId)?.refreshPreview({ withRetry: true });
15485
15710
  }
15486
- if (publishWidgetId) {
15487
- // console.log('[Publish] Refreshing canvas widget screenshot after successful publish');
15488
- scheduleQuietScreenshot(publishWidgetId, 2000);
15489
- }
15490
15711
  if (embedded && onPublishComplete && publishWidgetId) {
15491
- onPublishComplete({
15492
- widgetId: publishWidgetId,
15493
- version: publishResult.version
15494
- });
15712
+ const publishedWidgetId = publishWidgetId;
15713
+ const publishedVersion = publishResult.version;
15714
+ void (async () => {
15715
+ await Promise.race([
15716
+ handleRefreshScreenshot(publishedWidgetId, { quiet: true }).catch((error) => {
15717
+ console.warn('[Publish] Thumbnail before leaving the canvas failed', error);
15718
+ }),
15719
+ new Promise((resolve) => setTimeout(resolve, 2500)),
15720
+ ]);
15721
+ onPublishComplete({
15722
+ widgetId: publishedWidgetId,
15723
+ version: publishedVersion
15724
+ });
15725
+ })();
15726
+ } else if (publishWidgetId) {
15727
+ scheduleQuietScreenshot(publishWidgetId, 2000);
15495
15728
  }
15496
15729
  } else if (publishResult.status === 'failure') {
15497
15730
  if (isFocusedPublish) {
@@ -15660,6 +15893,30 @@ async function readPublishHistoryForPanel(widgetId: string, opts: { silent?: boo
15660
15893
  // must stop `ensureShapePublishHistory` from re-fetching on every render.
15661
15894
  shapeHistoryResolvedByWidgetId = { ...shapeHistoryResolvedByWidgetId, [widgetId]: true };
15662
15895
  queueUnpublishedHeadOnShape(widgetId);
15896
+ const publishedVersions = history
15897
+ .filter((row) => row.publishedAt ?? row.published_at)
15898
+ .map((row) => Number(row.version))
15899
+ .filter((version) => Number.isFinite(version));
15900
+ const liveFromHistory = publishedVersions.length > 0 ? Math.max(...publishedVersions) : null;
15901
+ const draftVersions = history
15902
+ .filter((row) => !(row.publishedAt ?? row.published_at))
15903
+ .map((row) => Number(row.version))
15904
+ .filter((version) => Number.isFinite(version));
15905
+ const newestDraft = draftVersions.length > 0 ? Math.max(...draftVersions) : null;
15906
+ const knownLive = getPanelState(widgetId).lastPublishedVersion ?? liveFromHistory;
15907
+ const draftAhead = newestDraft != null && knownLive != null && newestDraft > knownLive;
15908
+ if ((getPanelState(widgetId).lastPublishedVersion == null && liveFromHistory != null) || draftAhead) {
15909
+ patchPanelSnapshot(widgetId, {
15910
+ ...(getPanelState(widgetId).lastPublishedVersion == null && liveFromHistory != null
15911
+ ? { lastPublishedVersion: liveFromHistory }
15912
+ : {}),
15913
+ ...(draftAhead ? { pendingPublishAfterCodegen: true, hasGeneratedCode: true } : {}),
15914
+ });
15915
+ if (widgetId === focusedPanelWidgetId && getPanelState(widgetId).lastPublishedVersion != null) {
15916
+ lastPublishedVersion = getPanelState(widgetId).lastPublishedVersion;
15917
+ }
15918
+ }
15919
+ void reconcileWidgetHeadCommit(widgetId);
15663
15920
  if (widgetId === focusedPanelWidgetId) {
15664
15921
  publishHistory = history;
15665
15922
  publishHistoryResolved = true;
@@ -18314,7 +18571,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18314
18571
 
18315
18572
 
18316
18573
  <!-- Widgetic Canvas Editor - Full width background (lazy-loaded) -->
18317
- <div class="wc-canvas-area flex-1 min-h-0 relative {embedded && !canvasAdvancedFeatures ? 'pe-[480px]' : ''}">
18574
+ <div class="wc-canvas-area flex-1 min-h-0 relative {embedded && !canvasAdvancedFeatures ? 'pe-[450px]' : ''}">
18318
18575
  <!-- Embedded: Debug toggle lives in site AppHeader (avoids overlapping Props Panel). -->
18319
18576
  {#if canvasApiLoadError || canvasShapesMissingWarning}
18320
18577
  <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">
@@ -18454,7 +18711,17 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18454
18711
  resolveSelectedElements={(widgetId) => selectedElementsByWidgetId[widgetId] ?? []}
18455
18712
  onSelectWidgetElement={(widgetId, element) => handleSelectWidgetElement(widgetId, element)}
18456
18713
  onRemoveWidgetElement={(widgetId, elementId) => handleRemoveWidgetElement(widgetId, elementId)}
18457
- onCloseWidgetSelector={(widgetId) => handleToggleWidgetSelector(widgetId, false)}
18714
+ onCloseWidgetSelector={(widgetId) => {
18715
+ handleToggleWidgetSelector(widgetId, false);
18716
+ canvasRef?.setWidgetShapeBodyDragAllowed?.(widgetId, false);
18717
+ }}
18718
+ onCommandClickPreview={(widgetId) => {
18719
+ const next = !selectorEnabledByWidgetId[widgetId];
18720
+ canvasRef?.selectWidgetShapeById?.(widgetId);
18721
+ canvasSelectedWidgetShapeId = widgetId;
18722
+ handleToggleWidgetSelector(widgetId, next);
18723
+ console.log('[WidgetShape] Alt click toggles the selector', widgetId.substring(0, 8), next);
18724
+ }}
18458
18725
  />
18459
18726
 
18460
18727
  <!-- ═══ PANEL 2: Widgets Panel — debug + showWidgetsList (site passes false) ═══ -->
@@ -18592,7 +18859,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18592
18859
  <!-- svelte-ignore a11y-click-events-have-key-events -->
18593
18860
  <div
18594
18861
  class="widget-item widgets-list-grid-row items-center gap-x-2 border rounded px-2 py-1 text-sm {selectedWidgetId === w.id ? 'border-blue-500 bg-blue-50 cursor-default' : 'border-gray-200 cursor-pointer hover:bg-blue-50'}"
18595
- tabindex="0"
18862
+ tabindex="-1"
18596
18863
  role="button"
18597
18864
  onclick={() => {
18598
18865
  if (renamingWidgetId === w.id) return;
@@ -18849,12 +19116,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18849
19116
  if (!previewWidgetId) return;
18850
19117
  // Clear the "…loading preview…" / "…building preview…" status once the iframe reports ready.
18851
19118
  const panelStatus = getPanelState(previewWidgetId).generateCodeStatus || '';
18852
- if (/loading preview|building preview|preview rebuilt from saved code/i.test(panelStatus)) {
18853
- const panelCommit = getPanelState(previewWidgetId).lastCommitId;
18854
- const commitShort = panelCommit ? panelCommit.substring(0, 7) : '';
18855
- patchCodegenUiState(previewWidgetId, {
18856
- generateCodeStatus: `Code generation completed!${commitShort ? ` Commit: ${commitShort}` : ''} Preview ready.`,
18857
- });
19119
+ if (/loading preview|building preview|preview rebuilt from saved code|generating code/i.test(panelStatus)) {
19120
+ markGenerationPreviewReady(previewWidgetId);
18858
19121
  }
18859
19122
  if (isPanelFocused && previewWidgetId === panelWidgetId) {
18860
19123
  chatMethods?.clearStalePreviewBuildFailures?.();
@@ -19186,7 +19449,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
19186
19449
  {/if}
19187
19450
  {/if}
19188
19451
  {#if isHistoryOpen && isPanelFocused}
19189
- <Portal target="wc-live-history-portal-{panelWidgetId}">
19452
+ <Portal target="wc-live-history-portal-{panelWidgetId}" style="z-index: 100000010; width: auto; height: auto; overflow: visible;">
19190
19453
  <button
19191
19454
  type="button"
19192
19455
  class="wc-live-history-backdrop fixed start-0 end-0 bottom-0 top-14 z-[9998] cursor-default bg-transparent"