@widgetic/creator 0.4.46 → 0.4.48

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.
@@ -10,7 +10,6 @@
10
10
  import {
11
11
  Button,
12
12
  CreatorBar,
13
- CanvasBoardStatusChip,
14
13
  DropdownMenu,
15
14
  PasswordInput,
16
15
  showToast,
@@ -62,6 +61,8 @@
62
61
  sketchBarShowsPublish,
63
62
  sketchSavedStatusLabel,
64
63
  } from './sketchBarState.js';
64
+ import { isDebugTabVisible } from './debug/debugUiVisibility.js';
65
+ import { shouldNudgeSendBeforePublish } from './publish/publishGenerationGate.js';
65
66
 
66
67
  /**
67
68
  * Idempotency middleware (Phase 2 hardening): the gateway rejects
@@ -310,11 +311,15 @@
310
311
  export let projectId: CreatorAppProps['projectId'] = null;
311
312
  export let workspaceType: CreatorAppProps['workspaceType'] = 'personal';
312
313
  export let organizationId: CreatorAppProps['organizationId'] = null;
314
+ /** Brand-kit fonts the host mapped for the sketch canvas. */
315
+ export let canvasWorkspaceFonts: CreatorAppProps['canvasWorkspaceFonts'] = [];
313
316
  export let initialWidgetId: CreatorAppProps['initialWidgetId'] = null;
314
317
  export let initialCompositionId: CreatorAppProps['initialCompositionId'] = null;
315
318
  export let initialStep: CreatorAppProps['initialStep'] = null;
316
319
  export let forceCreateNewWidget: CreatorAppProps['forceCreateNewWidget'] = false;
317
320
  export let initialSketchName: CreatorAppProps['initialSketchName'] = null;
321
+ /** Title the host already knows for the canvas being opened: shown at once, then replaced by the canvas record's own. */
322
+ export let initialCanvasTitle: CreatorAppProps['initialCanvasTitle'] = null;
318
323
  /** Words to put in the chat input of a new widget, once (never sent by the creator itself). */
319
324
  export let initialPrompt: CreatorAppProps['initialPrompt'] = null;
320
325
  /** The initial prompt was put in the input; later draft restores leave the person's own text alone. */
@@ -323,6 +328,8 @@
323
328
  export let initialMessage: CreatorAppProps['initialMessage'] = null;
324
329
  /** The host's message was put in the input (and sent, when asked); later draft restores leave the person's text alone. */
325
330
  let appliedInitialMessage = false;
331
+ /** Opened from the Home page with a drawing: the drawing is centred in the main window once, when it has loaded. */
332
+ let centerSketchOnFirstLoad = !!initialMessage;
326
333
  /** Where the canvas's tool bar stands along the bottom edge (see `CreatorAppProps.toolbarPosition`). */
327
334
  export let toolbarPosition: CreatorAppProps['toolbarPosition'] = undefined;
328
335
  /** Whether the canvas shows its Save button (see `CreatorAppProps.showSaveButton`): the site and the standalone creator do. */
@@ -340,6 +347,7 @@
340
347
  export let apiUrl: CreatorAppProps['apiUrl'] = null;
341
348
  export let widgetBuilderUrl: CreatorAppProps['widgetBuilderUrl'] = null;
342
349
  export let initialDebugMode: CreatorAppProps['initialDebugMode'] = undefined;
350
+ export let initialDebugOn: CreatorAppProps['initialDebugOn'] = undefined;
343
351
  export let initialAdvancedFeatures: CreatorAppProps['initialAdvancedFeatures'] = false;
344
352
  export let defaultCoderModelId: CreatorAppProps['defaultCoderModelId'] = undefined;
345
353
  export let defaultPlannerModelId: CreatorAppProps['defaultPlannerModelId'] = undefined;
@@ -622,7 +630,7 @@
622
630
  function handleHostRequestPublishEvent(): void {
623
631
  const targetId = focusedPanelWidgetId || selectedWidgetId;
624
632
  if (!targetId) {
625
- showToast('error', $t('creator.publish.cannotPublish'), { description: $t('creator.widget.noWidgetSelected') });
633
+ showToast('error', $t('creator.publish.cannotPublish'), { description: $t('creator.sketch.publishNeedsWidget') });
626
634
  return;
627
635
  }
628
636
  // console.log('[CreatorApp] Host requested publish for', targetId.substring(0, 8));
@@ -644,7 +652,7 @@
644
652
  const targetId = publishTargetOf(focusedPanelWidgetId, canvasPrimaryWidgetId, isDraftConvertId);
645
653
  if (!targetId) {
646
654
  console.warn('[CreatorApp] Host publish ignored: there is no widget to publish yet');
647
- showToast('error', $t('creator.publish.cannotPublish'), { description: $t('creator.widget.noWidgetSelected') });
655
+ showToast('error', $t('creator.publish.cannotPublish'), { description: $t('creator.sketch.publishNeedsWidget') });
648
656
  return;
649
657
  }
650
658
  try {
@@ -1147,7 +1155,7 @@
1147
1155
  */
1148
1156
  let canvasRef: WithoutIndexKeys<InstanceType<typeof import('@widgetic/canvas').Canvas>> | null = null;
1149
1157
  /**
1150
- * HTML iframe overlays over Fabric WidgetShapes (W3).
1158
+ * HTML iframe overlays over the canvas's widget shapes (W3).
1151
1159
  *
1152
1160
  * Typed as the component's **own instance type**, not a hand-written
1153
1161
  * mirror: a Svelte 5 component is a call-signature type whose return is
@@ -1162,7 +1170,7 @@
1162
1170
  * lazily — the optionality lives at the binding, not in the type.
1163
1171
  */
1164
1172
  let widgetShapeLivePreviewsRef: ReturnType<typeof WidgetShapeLivePreviews> | null = null;
1165
- /** Selected WidgetShape id for chrome highlight (from Fabric selection). */
1173
+ /** Selected WidgetShape id for chrome highlight (from the canvas selection). */
1166
1174
  let canvasSelectedWidgetShapeId: string | null = null;
1167
1175
  let widgetDetailsModulePromise: Promise<typeof WidgetDetailsComponent> | null = null;
1168
1176
 
@@ -1289,6 +1297,18 @@
1289
1297
  appliedSketchName = true;
1290
1298
  activeCanvasName = initialSketchName.trim();
1291
1299
  }
1300
+ let appliedInitialCanvasTitle = false;
1301
+ // The dashboard already holds this title: show it before the canvas record has been read (about a second).
1302
+ $: if (
1303
+ !appliedInitialCanvasTitle &&
1304
+ !appliedSketchName &&
1305
+ activeCanvasName === 'Loading...' &&
1306
+ typeof initialCanvasTitle === 'string' &&
1307
+ initialCanvasTitle.trim()
1308
+ ) {
1309
+ appliedInitialCanvasTitle = true;
1310
+ activeCanvasName = initialCanvasTitle.trim();
1311
+ }
1292
1312
  let canvasNameEditing = false; // kept for existing startCanvasNameEdit/commitCanvasNameEdit
1293
1313
  let canvasNameInputEl: HTMLInputElement | null = null;
1294
1314
 
@@ -1639,15 +1659,9 @@
1639
1659
  let pendingAutoGenerateWidgetId: string | null = null; // Widget created from canvas that needs auto code generation
1640
1660
  let pendingDuplicateBuildWidgetId: string | null = null; // Duplicated widget awaiting repo fork + compile
1641
1661
  let isWidgetOperationInProgress = false; // Guards against concurrent duplicate/convert
1642
- /** Convert-to-widget skips the confirm dialog and auto-starts codegen once. */
1643
- const skipAutoGenConfirmWidgetIds = new Set<string>();
1644
1662
  /** New widgets: 'pending' while GitLab repo is created — preview shows loader, not "no repository". */
1645
1663
  let repositorySetupByWidgetId: Record<string, 'pending' | 'ready' | 'failed'> = {};
1646
1664
 
1647
- // Confirm generation dialog state (shown before auto-generating on convert)
1648
- let confirmGenerateDialogOpen = false;
1649
- /** Widget targeted by the open confirm-generate dialog (may differ from focused panel). */
1650
- let confirmGenerateWidgetId: string | null = null;
1651
1665
 
1652
1666
  // ─── Convert UX v2: draft panel state (no widget record until first Send) ────
1653
1667
  /** Synthetic id for the draft convert panel — NOT a widget id in the DB. */
@@ -1658,7 +1672,7 @@
1658
1672
  const draftConvertObjectIds = new Map<string, string>();
1659
1673
  /** Captured sketch screenshot (data URL) per draft id — reused on first Send. */
1660
1674
  const draftConvertScreenshots = new Map<string, string>();
1661
- /** Fabric JSON of the board, kept so the first checkpoint can put the sketch back. */
1675
+ /** The board's saved scene (JSON), kept so the first checkpoint can put the sketch back. */
1662
1676
  const draftConvertSketchJson = new Map<string, string>();
1663
1677
  const sketchSnapshotsByWidgetId = new Map<string, string>();
1664
1678
 
@@ -1711,6 +1725,7 @@
1711
1725
  getDraftText?: () => string;
1712
1726
  setDraftText?: (text: string) => void;
1713
1727
  getAttachmentDataUrls?: () => string[];
1728
+ getDraftAttachmentDataUrls?: () => string[];
1714
1729
  getAttachmentUploadIds?: () => string[];
1715
1730
  restoreAttachmentsFromDataUrls?: (dataUrls: string[]) => void;
1716
1731
  clearDraft?: () => void;
@@ -2280,33 +2295,6 @@
2280
2295
  return /(?:Commit:?\s+|Code saved\s*\()[a-f0-9]{7,40}/i.test(String(content || ''));
2281
2296
  }
2282
2297
 
2283
- /** The "Try again" button of the failed chip on the board: runs the last prompt of the primary widget's chat again,
2284
- * the same way the retry button of the failed message in the chat does. */
2285
- async function handleSketchRetryFailedGeneration() {
2286
- const widgetId = canvasPrimaryWidgetId;
2287
- if (!widgetId) return;
2288
- try {
2289
- const panelChat = getChatMethodsForWidget(widgetId);
2290
- const conversationId = panelChat?.getConversationId?.() ?? getPanelState(widgetId).currentChatConversationId ?? null;
2291
- if (!conversationId) {
2292
- console.warn('[Creator] Try again on the failed chip: the widget has no conversation to read the prompt from');
2293
- return;
2294
- }
2295
- const conversationMessages = (await handleLoadMessages(conversationId, widgetId, { scope: 'all' })) || [];
2296
- const lastUserMessage = [...conversationMessages]
2297
- .reverse()
2298
- .find((message) => (message.messageType || message.message_type) === 'user');
2299
- const lastPromptText = String(lastUserMessage?.messageContent || lastUserMessage?.message_content || '').trim();
2300
- if (!lastPromptText) {
2301
- console.warn('[Creator] Try again on the failed chip: no earlier prompt found in the conversation');
2302
- return;
2303
- }
2304
- await handleChatRetryMessage(lastPromptText, widgetId);
2305
- } catch (error) {
2306
- console.error('[Creator] Try again on the failed chip did not start', error);
2307
- }
2308
- }
2309
-
2310
2298
  /** Retry failed codegen without duplicating the user bubble. A successful prompt forks a new message so each version has its own turn. */
2311
2299
  async function handleChatRetryMessage(content: string, sourceWidgetId?: string) {
2312
2300
  const widgetId = sourceWidgetId ?? selectedWidgetId;
@@ -2557,7 +2545,9 @@
2557
2545
  try {
2558
2546
  const panelChat = getChatMethodsForWidget(widgetId);
2559
2547
  const chatDraft = panelChat?.getDraftText?.() ?? '';
2560
- const chatAttachmentUrls = panelChat?.getAttachmentDataUrls?.() ?? [];
2548
+ // The draft keeps pictures as data: URLs, the one form a refresh can rebuild them from (an older chat only has the send list).
2549
+ const chatAttachmentUrls =
2550
+ panelChat?.getDraftAttachmentDataUrls?.() ?? panelChat?.getAttachmentDataUrls?.() ?? [];
2561
2551
  patchPanelSnapshot(widgetId, {
2562
2552
  codeGenerationPrompt: chatDraft || getPanelState(widgetId).codeGenerationPrompt,
2563
2553
  promptImages: chatAttachmentUrls,
@@ -2699,15 +2689,16 @@
2699
2689
  }
2700
2690
  }
2701
2691
 
2702
- /** Push confirm-dialog / local prompt into chat input (not as a sent message). */
2703
- function syncPromptToChatDraft() {
2704
- if (!chatMethods) return;
2692
+ /** Push the local prompt into the chat input of a widget's panel (the focused one by default), not as a sent message. */
2693
+ function syncPromptToChatDraft(widgetId?: string | null) {
2694
+ const targetChatMethods = (widgetId ? getChatMethodsForWidget(widgetId) : null) ?? chatMethods;
2695
+ if (!targetChatMethods) return;
2705
2696
  suppressChatDraftSync = true;
2706
2697
  try {
2707
2698
  if (promptImages.length > 0) {
2708
- chatMethods.restoreAttachmentsFromDataUrls?.(promptImages);
2699
+ targetChatMethods.restoreAttachmentsFromDataUrls?.(promptImages);
2709
2700
  }
2710
- chatMethods.setDraftText?.(codeGenerationPrompt);
2701
+ targetChatMethods.setDraftText?.(codeGenerationPrompt);
2711
2702
  } finally {
2712
2703
  suppressChatDraftSync = false;
2713
2704
  }
@@ -2757,7 +2748,7 @@
2757
2748
  /**
2758
2749
  * Keeps widget screenshots out of the canvas JSON.
2759
2750
  *
2760
- * Fabric serialized each widget shape's screenshot inline as base64, so an
2751
+ * The canvas used to serialize each widget shape's screenshot inline as base64, so an
2761
2752
  * autosave stringified megabytes of image data and wrote it three times over —
2762
2753
  * the main-thread block the freeze reports kept naming. The canvas now stores a
2763
2754
  * reference and asks for the bytes back through this store: the local copy
@@ -3246,7 +3237,7 @@
3246
3237
  try {
3247
3238
  const screenshot = await handleChatScreenshot(widgetId, iframe, true);
3248
3239
  if (!screenshot || !isCurrent()) return;
3249
- // Persist before Fabric/autosave side effects can resync the live overlay.
3240
+ // Persist before the canvas/autosave side effects can resync the live overlay.
3250
3241
  await persistWidgetListThumbnail(widgetId, screenshot, isCurrent);
3251
3242
  if (!isCurrent()) return;
3252
3243
  capturedCanvas?.updateWidgetImage(widgetId, screenshot);
@@ -3260,7 +3251,7 @@
3260
3251
  }
3261
3252
  }
3262
3253
 
3263
- /** Screenshot: capture the live WidgetShape iframe (CDN or Worker), not Fabric wireframe. */
3254
+ /** Screenshot: capture the live WidgetShape iframe (CDN or Worker), not the wireframe on the canvas. */
3264
3255
  async function handleChatScreenshot(widgetId?: string | null, requiredIframe: HTMLIFrameElement | null = null, quiet = false): Promise<string | null> {
3265
3256
  const targetId = widgetId || focusedPanelWidgetId || selectedWidgetId;
3266
3257
  if (!targetId) {
@@ -3329,7 +3320,7 @@
3329
3320
  console.warn('[Chat→Screenshot] Live iframe capture failed:', fromLive.error);
3330
3321
  }
3331
3322
 
3332
- // Explicit refresh must not persist a different version or a stale Fabric image.
3323
+ // Explicit refresh must not persist a different version or a stale canvas image.
3333
3324
  if (requiredIframe) return null;
3334
3325
  // Quiet thumbnail sync must NEVER construct a temporary hidden iframe and compile worker preview.
3335
3326
  if (quiet) return null;
@@ -3338,14 +3329,14 @@
3338
3329
  const fromWorker = await captureViaHiddenWorkerPreview(targetId);
3339
3330
  if (fromWorker && fromWorker.length > 500) return fromWorker;
3340
3331
 
3341
- // 3) Last resort: Fabric thumbnail (often stale / wireframe) — only if nothing else works
3332
+ // 3) Last resort: the canvas's own thumbnail (often stale / wireframe) — only if nothing else works
3342
3333
  const shapeDataUrl =
3343
3334
  typeof canvasRef?.getWidgetShapeDataUrl === 'function'
3344
3335
  ? canvasRef.getWidgetShapeDataUrl(targetId)
3345
3336
  : null;
3346
3337
  if (shapeDataUrl && shapeDataUrl.length > 100) {
3347
3338
  console.warn(
3348
- '[Chat→Screenshot] Falling back to Fabric thumbnail (may be stale wireframe)',
3339
+ '[Chat→Screenshot] Falling back to the canvas thumbnail (may be stale wireframe)',
3349
3340
  targetId.substring(0, 8),
3350
3341
  );
3351
3342
  return shapeDataUrl;
@@ -6385,8 +6376,12 @@
6385
6376
  ? false
6386
6377
  : (VITE_DEBUG_MODE === 'true' || VITE_DEBUG_MODE === '1' || !isProduction);
6387
6378
 
6379
+ // A host that keeps the preference itself (the site, per account) says whether debug starts ON; the creator then neither
6380
+ // reads nor writes its own stored copy, which was one flag for every account of the browser.
6381
+ const hostOwnsDebugPreference = hostProvidedDebug && typeof initialDebugOn === 'boolean';
6382
+
6388
6383
  // debugMode — current ON/OFF state. User can still toggle when the UI is available.
6389
- let debugMode = debugModeAvailable;
6384
+ let debugMode = hostOwnsDebugPreference ? debugModeAvailable && initialDebugOn === true : debugModeAvailable;
6390
6385
  $: codegenErrorDisplay = { debugMode, ...CODEGEN_ERROR_DISPLAY };
6391
6386
  $: canvasLoadErrorDisplay = { debugMode, ...CANVAS_LOAD_ERROR_DISPLAY };
6392
6387
  /** Mobile embedded sketch: Canvas | Chat tabs (both panes stay mounted; CSS hides the inactive one). */
@@ -6536,39 +6531,6 @@
6536
6531
  }
6537
6532
  }
6538
6533
 
6539
- $: sketchBoardStatusChip = (() => {
6540
- if (!embeddedSketchShell) return null;
6541
- const id = canvasPrimaryWidgetId;
6542
- if (!id) return null;
6543
- if (generatingWidgetIds[id] || sketchWidgetHasActiveCodegenOperation(id)) {
6544
- return { variant: 'generating' as const, label: $t('creator.sketch.boardGenerating') };
6545
- }
6546
- const ps = getPanelDisplayState(id);
6547
- const w = getWidgetById(id) as Record<string, unknown> | null;
6548
- const codegenStatus = String(
6549
- (w?.codegenStatus as string | undefined) ?? (w?.codegen_status as string | undefined) ?? '',
6550
- ).trim();
6551
- const failed =
6552
- ps.lastGenerationFailed
6553
- || codegenStatus === 'failed'
6554
- || (w as { generationFailed?: boolean } | null)?.generationFailed === true
6555
- || (w as { generation_failed?: boolean } | null)?.generation_failed === true;
6556
- if (failed) {
6557
- return {
6558
- variant: 'failed' as const,
6559
- label: $t('creator.sketch.boardFailed'),
6560
- actionLabel: $t('creator.sketch.boardFailedRetry'),
6561
- };
6562
- }
6563
- if (sketchPrimaryShowsLiveBadge(id)) {
6564
- return null;
6565
- }
6566
- if (sketchPrimaryHasGeneratedCode(id)) {
6567
- return { variant: 'ready' as const, label: $t('creator.sketch.boardReady') };
6568
- }
6569
- return null;
6570
- })();
6571
-
6572
6534
  function handleSketchBarTitleClick() {
6573
6535
  if (canvasPrimaryWidgetId) {
6574
6536
  void openWidgetDetailsPanel(canvasPrimaryWidgetId);
@@ -6587,8 +6549,10 @@
6587
6549
 
6588
6550
  $: sketchCanvasShowZoom = embeddedSketchShell || debugMode;
6589
6551
  $: sketchCanvasPanZoomPosition = (embeddedSketchShell ? 'BL' : 'TL') as 'BL' | 'TL';
6552
+ $: canvasWorkspaceStorageId =
6553
+ workspaceType === 'organization' && organizationId ? `organization:${organizationId}` : 'personal';
6590
6554
  $: sketchCanvasShowSaveButton = embeddedSketchShell ? false : showSaveButton;
6591
- if (debugModeAvailable && typeof window !== 'undefined') {
6555
+ if (debugModeAvailable && !hostOwnsDebugPreference && typeof window !== 'undefined') {
6592
6556
  try {
6593
6557
  const storedDebugMode = creatorStorage.getItem('widgetic:site-debug-on');
6594
6558
  if (storedDebugMode === '1' || storedDebugMode === 'true') debugMode = true;
@@ -6776,7 +6740,8 @@
6776
6740
  debugMode = !debugMode;
6777
6741
  if (!debugMode) brandKitEnabled = false;
6778
6742
  try {
6779
- creatorStorage.setItem('widgetic:site-debug-on', debugMode ? '1' : '0');
6743
+ // The host that owns the preference stores it (it is told below); the creator's own copy is for standalone use
6744
+ if (!hostOwnsDebugPreference) creatorStorage.setItem('widgetic:site-debug-on', debugMode ? '1' : '0');
6780
6745
  } catch (err) {
6781
6746
  console.warn('[WidgetCreator] Could not persist debug mode', err);
6782
6747
  }
@@ -7602,7 +7567,8 @@
7602
7567
  // This tab learned of it from the browser's own store: the other tabs may not know of it yet
7603
7568
  if (origin === 'stored') generationChannel?.announceStarted(widgetId, operationId);
7604
7569
  // (A refused request has been told already, in the words of its refusal)
7605
- if (widgetId === focusedPanelWidgetId && origin !== 'stop-failed' && origin !== 'refused') {
7570
+ // In the sketch layout the side chat is where the generation is told: no toast over the canvas.
7571
+ if (widgetId === focusedPanelWidgetId && origin !== 'stop-failed' && origin !== 'refused' && !embeddedSketchShell) {
7606
7572
  showToast('info', $t('creator.codegen.generationInProgress'), {
7607
7573
  description: $t('creator.codegen.reconnectedToAnActiveCode'),
7608
7574
  duration: 4000
@@ -8469,7 +8435,7 @@
8469
8435
  return;
8470
8436
  }
8471
8437
  } else {
8472
- // Recreate at the current viewport center. A shape added while Fabric is still
8438
+ // Recreate at the current viewport center. A shape added while the canvas is still
8473
8439
  // 300×150 lands off-screen after the canvas grows to the full page.
8474
8440
  canvasRef.onClearAllObjects?.();
8475
8441
  }
@@ -10858,6 +10824,9 @@
10858
10824
  if (promptImages.length > 0) {
10859
10825
  chatMethods.restoreAttachmentsFromDataUrls?.(promptImages);
10860
10826
  }
10827
+ } else if (promptImages.length > 0 && !hostInitialMessage) {
10828
+ // A draft of only pictures is a draft too (it used to be cleared as if it were empty).
10829
+ chatMethods.restoreAttachmentsFromDataUrls?.(promptImages);
10861
10830
  } else if (hostInitialMessage && !appliedInitialMessage) {
10862
10831
  // The host opened a new widget with a message for it (a link to replicate): it goes into the input first, so
10863
10832
  // a person whose message could not be sent still has it, and is sent after the restore when the host asked.
@@ -11309,7 +11278,7 @@
11309
11278
  if (!openWidgetPanelIds.includes(widgetId)) {
11310
11279
  if (quiet || isConvertOrDraftPanelOpen()) {
11311
11280
  // A draft convert has no widget row and no live iframe yet — the
11312
- // Fabric sketch is genuinely all there is to show.
11281
+ // canvas sketch is genuinely all there is to show.
11313
11282
  if (isDraftConvertId(widgetId)) {
11314
11283
  const draftShapeDataUrl = canvasRef?.getWidgetShapeDataUrl?.(widgetId);
11315
11284
  if (draftShapeDataUrl && canvasRef) {
@@ -11322,7 +11291,7 @@
11322
11291
  // is still on the canvas. Capture from it so both the canvas image
11323
11292
  // and the project-list thumbnail track the latest preview.
11324
11293
  //
11325
- // Without this the Fabric `_imageElement` set at convert time wins
11294
+ // Without this the image set on the canvas shape at convert time wins
11326
11295
  // forever — it is the sketch screenshot frozen at creation, so the
11327
11296
  // Projects list kept showing the initial design after later
11328
11297
  // generations and preview refreshes.
@@ -12981,7 +12950,8 @@ Requirements:
12981
12950
  // A refusal because of a limit (credits used up) is told in the chat alone when the page asked for that
12982
12951
  // (`limitNotices: 'chat'`): the toast would say the same thing a second time. Any other failure keeps its toast.
12983
12952
  const refusedForALimit = await responseIsALimit(error?.response);
12984
- if (!limitRefusalNeedsNoToast(limitNoticeMode, refusedForALimit)) {
12953
+ // In the sketch layout the failure is told in the side chat (`pushCodegenFailureToChat` below), not in a toast.
12954
+ if (!limitRefusalNeedsNoToast(limitNoticeMode, refusedForALimit) && !embeddedSketchShell) {
12985
12955
  showToast('error', $t('creator.codegen.codeGenerationError'), { description: message, duration: 6000 });
12986
12956
  }
12987
12957
  pushCodegenFailureToChat(generationWidgetId, message);
@@ -15588,7 +15558,7 @@ Requirements:
15588
15558
  try {
15589
15559
  canvasSelectedWidgetShapeId = canvasRef?.getSelectedWidgetShapeId?.() ?? null;
15590
15560
  widgetShapeLivePreviewsRef?.sync?.();
15591
- // Hide Fabric screenshots under live iframes (avoids ghost bleed in padding).
15561
+ // Hide the canvas screenshots under live iframes (avoids ghost bleed in padding).
15592
15562
  const rects = canvasRef?.listWidgetShapeScreenRects?.() ?? [];
15593
15563
  const liveWidgetIds = new Set<string>();
15594
15564
  for (const rect of rects) {
@@ -16723,6 +16693,21 @@ Requirements:
16723
16693
  };
16724
16694
  }
16725
16695
  if (!repoId && !hasCode) {
16696
+ if (
16697
+ targetVersion == null &&
16698
+ shouldNudgeSendBeforePublish({
16699
+ hasGeneratedCode: ps.hasGeneratedCode,
16700
+ lastPublishedVersion: ps.lastPublishedVersion,
16701
+ lastCommitId: ps.lastCommitId,
16702
+ })
16703
+ ) {
16704
+ return {
16705
+ disabled: false,
16706
+ label: getPublishButtonLabelFallback(ps),
16707
+ reason: null,
16708
+ showDisabledHint: false,
16709
+ };
16710
+ }
16726
16711
  return {
16727
16712
  disabled: true,
16728
16713
  label: getPublishButtonLabelFallback(ps),
@@ -16761,10 +16746,10 @@ Requirements:
16761
16746
 
16762
16747
  if (!hasCode) {
16763
16748
  return {
16764
- disabled: true,
16749
+ disabled: false,
16765
16750
  label: getPublishButtonLabelFallback(ps),
16766
- reason: $t('creator.publish.generateWidgetCodeBeforePublishing'),
16767
- showDisabledHint: true,
16751
+ reason: null,
16752
+ showDisabledHint: false,
16768
16753
  };
16769
16754
  }
16770
16755
 
@@ -16939,6 +16924,16 @@ Requirements:
16939
16924
  * omit it to publish the newest generated code. The promise ends when the request is over; the buttons that start it do
16940
16925
  * not wait for it, and `publish()` (the host's control) does.
16941
16926
  */
16927
+ let sendNudgeTokenByWidgetId: Record<string, number> = {};
16928
+
16929
+ function requestSendNudgeForPanel(panelWidgetId: string): void {
16930
+ focusWidgetPanel(panelWidgetId);
16931
+ sendNudgeTokenByWidgetId = {
16932
+ ...sendNudgeTokenByWidgetId,
16933
+ [panelWidgetId]: (sendNudgeTokenByWidgetId[panelWidgetId] ?? 0) + 1,
16934
+ };
16935
+ }
16936
+
16942
16937
  function runPublishForPanel(panelWidgetId: string, targetVersion?: number | null): Promise<void> {
16943
16938
  return (async () => {
16944
16939
  if (isPublishing && !publishingWidgetId) {
@@ -16950,6 +16945,19 @@ Requirements:
16950
16945
  return;
16951
16946
  }
16952
16947
 
16948
+ const ps = getPanelDisplayState(panelWidgetId);
16949
+ if (
16950
+ targetVersion == null &&
16951
+ shouldNudgeSendBeforePublish({
16952
+ hasGeneratedCode: ps.hasGeneratedCode,
16953
+ lastPublishedVersion: ps.lastPublishedVersion,
16954
+ lastCommitId: ps.lastCommitId,
16955
+ })
16956
+ ) {
16957
+ requestSendNudgeForPanel(panelWidgetId);
16958
+ return;
16959
+ }
16960
+
16953
16961
  // Gate BEFORE focus/tick — focusing can reconcile HEAD/live SHA mid-click and
16954
16962
  // used to toast "already live" after the button still said "Publish new vN".
16955
16963
  const gateBefore = getPublishGateForPanel(panelWidgetId, targetVersion ?? null);
@@ -17500,46 +17508,6 @@ $: if (selectedWidgetId && canvasRef && conversationsClient && messagesClient &&
17500
17508
  }
17501
17509
  }
17502
17510
 
17503
- // Show "Confirm Generation" dialog for converted widgets that have a prompt + repo
17504
- // but no generated code yet. Separate from DB sync so it triggers on every widget
17505
- // selection and page refresh, not just the first time.
17506
- // Uses setTimeout to allow async prompt loading to finish before evaluating.
17507
- let autoGenDialogCheckedForWidgetId: string | null = null;
17508
- $: if (selectedWidgetId && autoGenDialogCheckedForWidgetId !== selectedWidgetId) {
17509
- // Draft convert panels: chat is already prefilled with the convert prompt —
17510
- // the confirm dialog would be redundant and targets a non-existent widget.
17511
- if (isDraftConvertId(selectedWidgetId)) {
17512
- autoGenDialogCheckedForWidgetId = selectedWidgetId;
17513
- } else {
17514
- autoGenDialogCheckedForWidgetId = selectedWidgetId;
17515
- const capturedWidgetId = selectedWidgetId;
17516
- setTimeout(() => {
17517
- if (capturedWidgetId !== selectedWidgetId) return;
17518
- if (skipAutoGenConfirmWidgetIds.has(capturedWidgetId)) {
17519
- skipAutoGenConfirmWidgetIds.delete(capturedWidgetId);
17520
- return;
17521
- }
17522
- if (isGeneratingCode || confirmGenerateDialogOpen) return;
17523
- const widgetForDialog = getWidgetById(capturedWidgetId);
17524
- const panelSnap = getPanelState(capturedWidgetId);
17525
- const hasRepo = !!normalizeRepositoryId(widgetForDialog);
17526
- const publishedVersion = panelSnap.lastPublishedVersion ?? resolvePublishedVersionFromWidget(widgetForDialog);
17527
- const hasNoCode = !panelSnap.lastCommitId
17528
- && publishedVersion == null
17529
- && (panelSnap.publishHistory?.length ?? 0) === 0;
17530
- const hasPrompt = codeGenerationPrompt !== DEFAULT_PROMPT || promptImages.length > 0;
17531
- const hasPreview = widgetDetails?.hasValidPreview() ?? false;
17532
- if (hasRepo && hasNoCode && !hasPreview && hasPrompt) {
17533
- // console.log('[AutoGenDialog] Widget has repo + prompt but no code — showing confirm generation dialog');
17534
- confirmGenerateWidgetId = capturedWidgetId;
17535
- confirmGenerateDialogOpen = true;
17536
- } else {
17537
- // console.log('[AutoGenDialog] Conditions not met:', { hasRepo, hasNoCode, hasPreview, hasPrompt, lastCommitId, lastPublishedVersion });
17538
- }
17539
- }, 1500);
17540
- }
17541
- }
17542
-
17543
17511
  // Auto-save prompt text to the durable draft when it changes (debounced 500ms)
17544
17512
  let promptSaveDebounceTimer: ReturnType<typeof setTimeout> | null = null;
17545
17513
  $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === selectedWidgetId) {
@@ -17935,7 +17903,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17935
17903
 
17936
17904
  // ─── Canvas Handlers ───────────────────────────────────────────────
17937
17905
 
17938
- /** Debounce Fabric dblclick bursts (same shape can fire twice). */
17906
+ /** Debounce canvas dblclick bursts (same shape can fire twice). */
17939
17907
  let lastWidgetShapeClickAt = 0;
17940
17908
  let lastWidgetShapeClickId = '';
17941
17909
  const WIDGET_SHAPE_CLICK_DEBOUNCE_MS = 450;
@@ -18412,11 +18380,28 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18412
18380
  requestAnimationFrame(() => {
18413
18381
  setTimeout(() => applyPrimarySelectionOnCanvas(primaryId), 80);
18414
18382
  });
18383
+ centerSketchInMainWindowOnce();
18415
18384
  syncWidgetShapeLivePreviews();
18416
18385
  singleWidgetChromeReady = true;
18417
18386
  void ensureSimpleCanvasChat();
18418
18387
  }
18419
18388
 
18389
+ /**
18390
+ * The drawing from the Home page, in the middle of the main window. The fit never zooms in past 100%, so a small
18391
+ * sketch is centred, not blown up. Only the first load after Home: a person who moves the board is left alone.
18392
+ */
18393
+ function centerSketchInMainWindowOnce() {
18394
+ if (!centerSketchOnFirstLoad) return;
18395
+ centerSketchOnFirstLoad = false;
18396
+ requestAnimationFrame(() => {
18397
+ try {
18398
+ canvasRef?.zoomFit?.();
18399
+ } catch (error) {
18400
+ console.warn('[CreatorApp] Could not centre the drawing from Home in the main window', error);
18401
+ }
18402
+ });
18403
+ }
18404
+
18420
18405
  /**
18421
18406
  * Loads saved canvas state from API (or localStorage fallback).
18422
18407
  * Only runs when both canvasId is resolved and the Canvas component is ready.
@@ -18616,7 +18601,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18616
18601
  // Persist remote state to local cache for subsequent instant loads
18617
18602
  saveCanvasState(canvasId, jsonString);
18618
18603
 
18619
- // Only re-hydrate Fabric if remote state differs from what was painted by SWR
18604
+ // Only re-hydrate the canvas if remote state differs from what was painted by SWR
18620
18605
  const shouldRehydrate = !localCachedJson || jsonString !== localCachedJson;
18621
18606
  if (shouldRehydrate) {
18622
18607
  if (loadEpoch !== canvasLoadEpoch || ignoreIncomingCanvasLoads) {
@@ -19790,7 +19775,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
19790
19775
  <LogoWidgeticType class="wc-logo-type h-5 w-auto" />
19791
19776
  <span class="wc-creator-label text-[28px] mt-0.5" style="color: #314F2F;">creator</span>
19792
19777
  </div>
19793
- {#if debugModeAvailable}
19778
+ {#if isDebugTabVisible({ debugEnabled: debugMode, isAdmin: debugModeAvailable })}
19794
19779
  <span
19795
19780
  class="wc-build-info text-[10px] font-mono text-gray-400 leading-none ps-0.5"
19796
19781
  title="Deployed build — remove when beta ends"
@@ -19827,13 +19812,13 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
19827
19812
  : ` · ${trialCounter.days} ${trialCounter.days === 1 ? 'day' : 'days'}`}
19828
19813
  </span>
19829
19814
  {/if}
19830
- {#if debugModeAvailable}
19831
- <HoverTooltip text={debugMode ? 'Debug mode ON — click to disable (hides console tab, widgets panel)' : 'Debug mode OFF — click to enable'}>
19815
+ {#if isDebugTabVisible({ debugEnabled: debugMode, isAdmin: debugModeAvailable })}
19816
+ <HoverTooltip text={'Debug mode ON — click to disable (hides console tab, widgets panel)'}>
19832
19817
  <button
19833
19818
  onclick={toggleDebugMode}
19834
- class="wc-debug-toggle px-2.5 py-1 cursor-pointer text-xs font-medium rounded-lg border transition-colors {debugMode ? 'bg-red-50 border-red-400 text-red-600 hover:bg-red-100' : 'bg-gray-100 border-gray-300 text-gray-500 hover:bg-gray-200'}"
19819
+ class="wc-debug-toggle px-2.5 py-1 cursor-pointer text-xs font-medium rounded-lg border transition-colors bg-red-50 border-red-400 text-red-600 hover:bg-red-100"
19835
19820
  >
19836
- 🐛 Debug {debugMode ? 'ON' : 'OFF'}
19821
+ 🐛 Debug ON
19837
19822
  </button>
19838
19823
  </HoverTooltip>
19839
19824
  {/if}
@@ -19915,11 +19900,11 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
19915
19900
  customizeLabel={$t('creator.sketch.customize')}
19916
19901
  showPublish={sketchBarShowPublish}
19917
19902
  publishLabel={sketchBarPublishLabel}
19918
- publishDisabled={!canvasPrimaryWidgetId || isPublishDisabledForPanel(canvasPrimaryWidgetId)}
19903
+ publishDisabled={!!canvasPrimaryWidgetId && isPublishDisabledForPanel(canvasPrimaryWidgetId)}
19919
19904
  onBack={() => window.dispatchEvent(new CustomEvent('widgetic:host-request-back'))}
19920
19905
  onTitleClick={handleSketchBarTitleClick}
19921
19906
  onCustomize={handleSketchCustomize}
19922
- onPublish={() => window.dispatchEvent(new CustomEvent('widgetic:host-request-publish'))}
19907
+ onPublish={() => void publish()}
19923
19908
  />
19924
19909
  {/if}
19925
19910
  <div
@@ -19935,14 +19920,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
19935
19920
  : ''}"
19936
19921
  aria-hidden={embeddedSketchShell && embeddedSketchMobileTab !== 'canvas' ? 'true' : undefined}
19937
19922
  >
19938
- {#if sketchBoardStatusChip}
19939
- <CanvasBoardStatusChip
19940
- variant={sketchBoardStatusChip.variant}
19941
- label={sketchBoardStatusChip.label}
19942
- actionLabel={'actionLabel' in sketchBoardStatusChip ? sketchBoardStatusChip.actionLabel : ''}
19943
- onAction={'actionLabel' in sketchBoardStatusChip ? () => void handleSketchRetryFailedGeneration() : undefined}
19944
- />
19945
- {/if}
19923
+ <!-- Generating, ready and failed are said in the side chat only: nothing about the generation is drawn over the canvas. -->
19946
19924
  <!-- Embedded: Debug toggle lives in site AppHeader (avoids overlapping Props Panel). -->
19947
19925
  {#if canvasApiLoadError || canvasShapesMissingWarning}
19948
19926
  <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">
@@ -20038,6 +20016,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
20038
20016
  }}
20039
20017
  panZoomPosition={sketchCanvasPanZoomPosition}
20040
20018
  toolbarPosition={toolbarPosition}
20019
+ workspaceId={canvasWorkspaceStorageId}
20020
+ workspaceFonts={canvasWorkspaceFonts ?? []}
20041
20021
  showSaveButton={sketchCanvasShowSaveButton}
20042
20022
  autosaveDelayMs={import.meta.env.DEV ? 15000 : 5000}
20043
20023
  autosaveMaxWaitMs={CANVAS_AUTOSAVE_MAX_WAIT_MS}
@@ -20650,10 +20630,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
20650
20630
  }
20651
20631
 
20652
20632
  if (hasPrompt) {
20653
- // Show confirm generation dialog
20654
- confirmGenerateWidgetId = widgetId;
20655
- confirmGenerateDialogOpen = true;
20656
- // console.log('[RetryRepo] Showing confirm generation dialog for widget:', widgetId);
20633
+ // The chat builds the widget: the prompt waits in its input for the person to send it
20634
+ syncPromptToChatDraft(widgetId);
20657
20635
  } else {
20658
20636
  widgetDetails?.showNoCodeYetState();
20659
20637
  // console.log('[RetryRepo] No prompt available — showing No Code Yet state');
@@ -20687,8 +20665,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
20687
20665
  void fixWidgetCompileError(widgetId, compileErr);
20688
20666
  return;
20689
20667
  }
20690
- confirmGenerateWidgetId = widgetId;
20691
- confirmGenerateDialogOpen = true;
20668
+ // The chat builds the widget: the prompt waits in its input for the person to send it
20669
+ syncPromptToChatDraft(widgetId);
20692
20670
  }}
20693
20671
  on:widgetDetailsToggle={({ detail }) => {
20694
20672
  const isClosing = detail?.open === false || detail?.showWidgetDetails === false;
@@ -21125,7 +21103,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
21125
21103
  showHeader={false}
21126
21104
  showPanelHeader={dockedChatPanel}
21127
21105
  headerTitle={panelWidget?.name || ''}
21128
- showConsoleControl={dockedChatPanel}
21106
+ showConsoleControl={dockedChatPanel && isDebugTabVisible({ debugEnabled: debugMode, isAdmin: debugModeAvailable })}
21107
+ sendNudgeToken={sendNudgeTokenByWidgetId[panelWidgetId] ?? 0}
21129
21108
  consoleOpen={!!panelConsoleOpenByWidgetId[panelWidgetId]}
21130
21109
  onToggleConsole={dockedChatPanel
21131
21110
  ? () => {
@@ -21808,60 +21787,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
21808
21787
  </Dialog.Content>
21809
21788
  </Dialog.Root>
21810
21789
 
21811
- <!-- Confirm Generation Dialog (shown on convert-to-widget before auto-generating) -->
21812
- <Dialog.Root
21813
- open={confirmGenerateDialogOpen}
21814
- onOpenChange={(open) => {
21815
- confirmGenerateDialogOpen = open;
21816
- if (!open) confirmGenerateWidgetId = null;
21817
- }}
21818
- >
21819
- <Dialog.Content closeLabel={$t('creator.common.close')} layerBase={creatorDialogLayerBase} class="confirm-generate-dialog-content max-w-lg bg-white z-9999">
21820
- <Dialog.Header class="confirm-generate-dialog-header">
21821
- <Dialog.Title>{$t('creator.codegen.confirmCodeGeneration')}</Dialog.Title>
21822
- <Dialog.Description>
21823
- {promptImages.length > 0
21824
- ? $t('creator.codegen.reviewThePromptAndReference')
21825
- : $t('creator.codegen.describeTheWidgetYouWant')}
21826
- </Dialog.Description>
21827
- </Dialog.Header>
21828
- <div class="flex flex-col gap-3 py-3 px-1">
21829
- <div class="text-xs font-medium text-gray-500 uppercase tracking-wide">{$t('creator.codegen.prompt')}</div>
21830
- <textarea
21831
- bind:value={codeGenerationPrompt}
21832
- class="w-full min-h-[80px] max-h-[160px] rounded-md border border-gray-300 p-2 text-sm resize-y focus:outline-none focus:ring-2 focus:ring-blue-400 focus:border-transparent"
21833
- placeholder={$t('creator.general.describeWhatYouWant')}
21834
- ></textarea>
21835
- {#if promptImages.length > 0}
21836
- <div class="text-xs font-medium text-gray-500 uppercase tracking-wide">{$t('creator.codegen.referenceImages', { count: promptImages.length })}</div>
21837
- <div class="flex gap-2 flex-wrap">
21838
- {#each promptImages as img, i}
21839
- <div class="relative">
21840
- <span class="absolute top-0.5 start-0.5 z-10 w-4 h-4 flex items-center justify-center rounded-full bg-blue-600 text-white text-[9px] font-bold shadow">{i + 1}</span>
21841
- <img src={img} alt={$t('creator.codegen.referenceNumber', { number: i + 1 })} class="w-16 h-16 rounded border border-gray-200 object-cover" />
21842
- </div>
21843
- {/each}
21844
- </div>
21845
- {/if}
21846
- </div>
21847
- <div class="flex justify-end gap-2 pt-2">
21848
- <Button variant="outline" size="sm" onclick={() => {
21849
- confirmGenerateDialogOpen = false;
21850
- syncPromptToChatDraft();
21851
- }}>
21852
- {$t('creator.codegen.editPromptFirst')}
21853
- </Button>
21854
- <Button variant="default" size="sm" onclick={() => {
21855
- const targetWidgetId = confirmGenerateWidgetId ?? selectedWidgetId ?? undefined;
21856
- confirmGenerateDialogOpen = false;
21857
- confirmGenerateWidgetId = null;
21858
- generateCode({ widgetId: targetWidgetId });
21859
- }}>
21860
- {$t('creator.codegen.generateNow')}
21861
- </Button>
21862
- </div>
21863
- </Dialog.Content>
21864
- </Dialog.Root>
21790
+
21865
21791
 
21866
21792
  <style>
21867
21793
  /* ── Top Bar: only truly non-Tailwind styles ─────────────── */