@widgetic/creator 0.4.36 → 0.4.38

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.
@@ -37,7 +37,7 @@
37
37
  import { widgetBuilderRequestInit } from './utils/widgetBuilderRequest.js';
38
38
  import { gzipRequestBodyMiddleware } from './utils/gzipRequestMiddleware.js';
39
39
  import type { SelectedWidgetElementReference } from './utils/widgetElementSelector.js';
40
- import GenerationOptionsPanel from './components/GenerationOptionsPanel.svelte';
40
+ import BrandKitPanel from './components/BrandKitPanel.svelte';
41
41
  import { brandKitForRequest } from './generation/brandKitForRequest.js';
42
42
 
43
43
  /**
@@ -149,6 +149,7 @@
149
149
 
150
150
  import {
151
151
  normalizeErrorMessage,
152
+ codegenFailureChatLine,
152
153
  toErrorMessage,
153
154
  deriveApiErrorMessage,
154
155
  extractDetailsMessage,
@@ -193,6 +194,13 @@
193
194
  type OperationSnapshot
194
195
  } from './utils/generationSharing.js';
195
196
  import { failureNoticeChanges } from './utils/failureNotice.js';
197
+ import {
198
+ loadRememberedVersionRatings,
199
+ rateVersionThroughApi,
200
+ rememberVersionRating,
201
+ saveRememberedVersionRatings,
202
+ type VersionRating
203
+ } from './utils/versionRatings.js';
196
204
  import { generationVersionAndDocumentFields } from './utils/generationRequestFields.js';
197
205
  import {
198
206
  generationRefusalText,
@@ -226,6 +234,7 @@
226
234
  mayUseAddressBar,
227
235
  mayShowAccountBilling,
228
236
  maySuggestWidgetName,
237
+ mayRateVersions,
229
238
  mayListenToSiteEvents,
230
239
  announceToSite,
231
240
  eventIsFromCreator,
@@ -1516,6 +1525,13 @@
1516
1525
  let widgetLanguage: 'svelte' | 'react' = 'react';
1517
1526
  let librariesEnabled = false;
1518
1527
  let generationLibraries: string[] = [];
1528
+ let brandKitEnabled = false;
1529
+ let brandPrimary = '#314F2F';
1530
+ let brandSecondary = '#7BA668';
1531
+ let brandTitle = '#0F2010';
1532
+ let brandSub = '#5C6B58';
1533
+ let brandFonts: string[] = ['Inter'];
1534
+ let fontUploads: { name: string; content: string; encoding: string }[] = [];
1519
1535
  let libraryGitUrl = '';
1520
1536
  let libraryFileName = '';
1521
1537
  let libraryUploads: { name: string; content: string; encoding: string }[] = [];
@@ -1725,6 +1741,15 @@
1725
1741
  panelDisplayRevision += 1;
1726
1742
  }
1727
1743
 
1744
+ function handleUpdateWidgetElementNote(widgetId: string, elementId: string, note: string): void {
1745
+ if (!widgetId || !elementId) return;
1746
+ const existing = selectedElementsByWidgetId[widgetId] ?? [];
1747
+ selectedElementsByWidgetId = {
1748
+ ...selectedElementsByWidgetId,
1749
+ [widgetId]: existing.map((item) => (item.id === elementId ? { ...item, note } : item)),
1750
+ };
1751
+ }
1752
+
1728
1753
  function handleClearWidgetSelectedElements(widgetId: string): void {
1729
1754
  if (!widgetId) return;
1730
1755
  const { [widgetId]: _cleared, ...rest } = selectedElementsByWidgetId;
@@ -2005,9 +2030,7 @@
2005
2030
 
2006
2031
  function pushCodegenFailureToChat(widgetId: string, errorText: string) {
2007
2032
  const panelChat = getChatMethodsForWidget(widgetId);
2008
- const content = /^Code generation failed/i.test(errorText)
2009
- ? errorText
2010
- : `Code generation failed: ${errorText}`;
2033
+ const content = codegenFailureChatLine(errorText);
2011
2034
  panelChat?.addAssistantMessage?.(content);
2012
2035
  // console.log('[Chat] Codegen failure bubble:', content.slice(0, 160));
2013
2036
  }
@@ -3480,6 +3503,35 @@
3480
3503
  }
3481
3504
  }
3482
3505
 
3506
+ /** One restore at a time. A second click while GitLab is still answering used to be told a generation was running. */
3507
+ let _restoreCheckpointInFlight = false;
3508
+
3509
+ /**
3510
+ * The thumbs the person gave to versions, by the id of the message that announced the version. The API keeps the word for Widget
3511
+ * Lessons (what the code generator learns across people) but has no call that lists them, so the creator remembers them and hands
3512
+ * them back to the chat (`versionRatings`) when it opens again. In a partner's page the storage is memory, and no thumbs is offered.
3513
+ */
3514
+ let versionRatingsByMessageId: Record<string, VersionRating> = loadRememberedVersionRatings();
3515
+
3516
+ /**
3517
+ * A thumbs the person pressed next to a version in the chat: tells the API, then remembers it. It throws when the API could not be
3518
+ * told, and the chat then puts the thumbs back as it was (nothing is remembered). The same conversation and message ids the chat
3519
+ * lists are the ones the API knows: a version is the saved message that announced a commit.
3520
+ */
3521
+ async function handleRateVersion(conversationId: string, messageId: string, rating: VersionRating): Promise<void> {
3522
+ if (!messagesClient || !conversationId || isLocalOnlyConversationId(conversationId)) {
3523
+ console.warn('[Chat→Backend] A version cannot be rated before its conversation is saved', { conversationId, messageId });
3524
+ throw new Error('The conversation of this version is not saved yet');
3525
+ }
3526
+ const outcome = await rateVersionThroughApi(messagesClient, { conversationId, messageId, rating });
3527
+ if (outcome.recorded === false) {
3528
+ // Not a failure: the version has no trace to attach the word to (it is older than the tracing), or the learning is off.
3529
+ console.debug('[Chat→Backend] The API did not keep the thumbs', { messageId, rating, reason: outcome.reason });
3530
+ }
3531
+ versionRatingsByMessageId = rememberVersionRating(versionRatingsByMessageId, messageId, rating);
3532
+ saveRememberedVersionRatings(versionRatingsByMessageId);
3533
+ }
3534
+
3483
3535
  /** Restore conversation to a checkpoint message via backend (deletes messages + git rollback) */
3484
3536
  async function handleRestoreCheckpoint(
3485
3537
  conversationId: string,
@@ -3489,6 +3541,14 @@
3489
3541
  // The widget whose code the restore puts back, as the panel looks at it when the request is made (the person may look at
3490
3542
  // another panel while it runs).
3491
3543
  const widgetIdAtRestore = restoreWidgetId || focusedPanelWidgetId || selectedWidgetId || null;
3544
+ if (_restoreCheckpointInFlight) {
3545
+ showToast('warning', $t('creator.version.failedToRestoreCheckpoint'), {
3546
+ description: $t('creator.version.restoreAlreadyRunning'),
3547
+ duration: 6000,
3548
+ });
3549
+ return null;
3550
+ }
3551
+ _restoreCheckpointInFlight = true;
3492
3552
  try {
3493
3553
  if (!messagesClient) {
3494
3554
  console.warn('[Chat→Backend] messagesClient not initialized');
@@ -3538,6 +3598,7 @@
3538
3598
  // Version 1 is the board before a generation replaced the drawing.
3539
3599
  // Later versions put that generation's code back on the shape.
3540
3600
  const restoreSketch = !targetCommit || restoredVersion === 1;
3601
+ sketchToolbarAfterRestore = restoreSketch;
3541
3602
  if (panelWidgetId && restoreSketch) {
3542
3603
  const sketchFromWidget = (getWidgetById(panelWidgetId) as { content?: { sketchCanvasJson?: string } } | null)?.content?.sketchCanvasJson;
3543
3604
  const sketch = sketchSnapshotsByWidgetId.get(panelWidgetId) || sketchFromWidget;
@@ -3634,6 +3695,15 @@
3634
3695
  _isRestoringCheckpoint = false;
3635
3696
  };
3636
3697
  void scheduleBuildRetry();
3698
+ } else if (gitRollback && gitRollback.success === false) {
3699
+ const rollbackError = String(gitRollback.error || '').trim();
3700
+ const gitlabLimited = /429|too many requests|rate limit/i.test(rollbackError);
3701
+ console.warn('[Restore] The code was not rolled back', { widgetId: panelWidgetId, rollbackError });
3702
+ showToast('warning', gitlabLimited ? $t('creator.general.rateLimited') : $t('creator.version.failedToRestoreCheckpoint'), {
3703
+ description: rollbackError || $t('creator.version.codeWasNotRolledBack'),
3704
+ duration: 9000,
3705
+ });
3706
+ return null;
3637
3707
  } else {
3638
3708
  console.warn('[Chat→Backend] Git rollback not detected in response, refreshing preview anyway...');
3639
3709
  showToast('warning', $t('creator.version.restoreCompletedWithWarnings'), {
@@ -3668,6 +3738,8 @@
3668
3738
  description: error instanceof Error ? error.message : $t('creator.general.unknownError'),
3669
3739
  });
3670
3740
  return null;
3741
+ } finally {
3742
+ _restoreCheckpointInFlight = false;
3671
3743
  }
3672
3744
  }
3673
3745
 
@@ -3760,6 +3832,9 @@
3760
3832
  if (!selectedId?.startsWith('v:')) return null;
3761
3833
  const version = Number(selectedId.slice(2));
3762
3834
  if (!Number.isFinite(version)) return null;
3835
+ // Restore already put this version on the board. Its commit is a new sha, so it does not match the history row.
3836
+ // Asking GitLab to roll back again only reads the trees and can 429.
3837
+ if (restoredViewingVersionByWidgetId[widgetId] === version) return null;
3763
3838
  const record = getShapePublishHistory(widgetId).find((row) => Number(row.version) === version);
3764
3839
  const sha = String(record?.commitSha ?? record?.commit_sha ?? '').trim();
3765
3840
  if (!/^[0-9a-f]{7,40}$/i.test(sha)) return null;
@@ -6030,6 +6105,7 @@
6030
6105
  function toggleDebugMode() {
6031
6106
  if (!debugModeAvailable) return;
6032
6107
  debugMode = !debugMode;
6108
+ if (!debugMode) brandKitEnabled = false;
6033
6109
  try {
6034
6110
  creatorStorage.setItem('widgetic:site-debug-on', debugMode ? '1' : '0');
6035
6111
  } catch (err) {
@@ -6050,7 +6126,26 @@
6050
6126
  let canvasWireframeMode = true;
6051
6127
  /** Extra canvas chrome — default off. Not tied to debugMode. */
6052
6128
  let canvasAdvancedFeatures = !!initialAdvancedFeatures;
6129
+ /**
6130
+ * More than one widget on this canvas. There is no env switch for it.
6131
+ * The Advanced button turns it on and off with the rest of the advanced chrome.
6132
+ */
6133
+ let multipleWidgetsAllowed = !!initialAdvancedFeatures;
6053
6134
  let canvasPrimaryWidgetId: string | null = null;
6135
+ /** Restore Checkpoint back to the sketch brings the drawing tools back until the next generation. */
6136
+ let sketchToolbarAfterRestore = false;
6137
+
6138
+ function primaryWidgetHasGeneratedCode(): boolean {
6139
+ if (!canvasPrimaryWidgetId || isDraftConvertId(canvasPrimaryWidgetId)) return false;
6140
+ const panel = getPanelState(canvasPrimaryWidgetId);
6141
+ return !!(panel.hasGeneratedCode || panel.lastCommitId || panel.lastPublishedVersion != null);
6142
+ }
6143
+
6144
+ $: showDrawingTools = sketchToolbarAfterRestore || !(
6145
+ panelDisplayRevision >= 0
6146
+ && !!canvasPrimaryWidgetId
6147
+ && primaryWidgetHasGeneratedCode()
6148
+ );
6054
6149
 
6055
6150
  function emitCreatorWireframeChanged() {
6056
6151
  announceToSite(CREATOR_WIREFRAME_CHANGED_EVENT, { wireframeMode: canvasWireframeMode });
@@ -6068,6 +6163,7 @@
6068
6163
 
6069
6164
  function handleHostToggleAdvancedEvent() {
6070
6165
  canvasAdvancedFeatures = !canvasAdvancedFeatures;
6166
+ multipleWidgetsAllowed = canvasAdvancedFeatures;
6071
6167
  emitCreatorAdvancedChanged();
6072
6168
  console.log('[CreatorApp] Advanced', canvasAdvancedFeatures ? 'ON' : 'OFF',
6073
6169
  '— composition steps', canvasAdvancedFeatures ? 'visible' : 'hidden');
@@ -6101,6 +6197,10 @@
6101
6197
  }
6102
6198
 
6103
6199
  async function handleHostDuplicateWidgetEvent(): Promise<void> {
6200
+ if (simpleCanvasHasItsWidget()) {
6201
+ showToast('info', $t('creator.widget.oneWidgetAlready'));
6202
+ return;
6203
+ }
6104
6204
  const widgetId = canvasPrimaryWidgetId || resolveHostTargetWidgetId();
6105
6205
  if (!widgetId || isDraftConvertId(widgetId)) {
6106
6206
  showToast('warning', $t('creator.widget.selectAWidgetFirst'), {
@@ -8130,7 +8230,13 @@
8130
8230
  }
8131
8231
 
8132
8232
  const linked = canvasRef.getLinkedWidgetIds?.() ?? new Set<string>();
8133
- const missing = sortWidgetSummaries(widgets.filter((w) => w.id && !linked.has(w.id))).reverse();
8233
+ let missing = sortWidgetSummaries(widgets.filter((w) => w.id && !linked.has(w.id))).reverse();
8234
+ if (embedded && !multipleWidgetsAllowed) {
8235
+ const primaryId = (canvasPrimaryWidgetId || '').trim();
8236
+ missing = primaryId
8237
+ ? missing.filter((widget) => widget.id === primaryId)
8238
+ : [];
8239
+ }
8134
8240
  if (missing.length === 0) return 0;
8135
8241
 
8136
8242
  // console.log('[CanvasDebug] Restoring', missing.length, 'widget shapes from canvas_id list');
@@ -9297,6 +9403,10 @@
9297
9403
 
9298
9404
 
9299
9405
  async function createNewWidgetRecord() {
9406
+ if (simpleCanvasHasItsWidget()) {
9407
+ showToast('info', $t('creator.widget.oneWidgetAlready'));
9408
+ return;
9409
+ }
9300
9410
  if (!$userSession.user || !hasValidToken) {
9301
9411
  authStatus = 'Please login first.';
9302
9412
  return;
@@ -10797,6 +10907,9 @@ Requirements:
10797
10907
  generationOperationByWidgetId.delete(generationWidgetId);
10798
10908
 
10799
10909
  generatingWidgetIds = { ...generatingWidgetIds, [generationWidgetId]: true };
10910
+ // The preview address does not change between builds. Without this, the next build
10911
+ // is treated as the one already on the shape, and the shape keeps the previous document.
10912
+ lastRunningPreviewKey = '';
10800
10913
  if (previewUnblockedByWidgetId[generationWidgetId]) {
10801
10914
  const { [generationWidgetId]: _dropPreview, ...restPreview } = previewUnblockedByWidgetId;
10802
10915
  previewUnblockedByWidgetId = restPreview;
@@ -10807,11 +10920,8 @@ Requirements:
10807
10920
  cancelQuietScreenshots();
10808
10921
  cancelIdleThumbnailPersist();
10809
10922
  widgetShapeLivePreviewsRef?.cancelReloads?.();
10810
- if (options.fromChat) {
10811
- console.log('[Chat→Preview] Reloading preview iframe on send', generationWidgetId.substring(0, 8));
10812
- widgetShapeLivePreviewsRef?.requestReload?.(generationWidgetId, { immediate: true });
10813
- void getWidgetDetailsRef(generationWidgetId)?.refreshPreview?.();
10814
- }
10923
+ // The preview stays on the current widget until a build actually lands.
10924
+ // Reloading here only flashed the same frame at the moment of Send.
10815
10925
  holdPublishForGeneration(generationWidgetId);
10816
10926
  if (restoredViewingVersionByWidgetId[generationWidgetId] != null) {
10817
10927
  const { [generationWidgetId]: _droppedRestore, ...restRestored } = restoredViewingVersionByWidgetId;
@@ -11079,6 +11189,15 @@ Requirements:
11079
11189
  debugMode,
11080
11190
  libraries: generationLibraries,
11081
11191
  libraryUploads,
11192
+ brandKitEnabled,
11193
+ colors: {
11194
+ primary: brandPrimary,
11195
+ secondary: brandSecondary,
11196
+ title: brandTitle,
11197
+ sub: brandSub,
11198
+ },
11199
+ fonts: brandFonts,
11200
+ fontUploads,
11082
11201
  }),
11083
11202
  ...(options.selectedElements && options.selectedElements.length > 0
11084
11203
  ? {
@@ -11087,7 +11206,9 @@ Requirements:
11087
11206
  selector: el.selector,
11088
11207
  idAttr: el.idAttr,
11089
11208
  classList: el.classList,
11090
- textSnippet: el.textSnippet,
11209
+ textSnippet: [el.textSnippet, el.note?.trim() ? `Note: ${el.note.trim()}` : '']
11210
+ .filter(Boolean)
11211
+ .join(' — ') || undefined,
11091
11212
  dataContent: el.dataContent,
11092
11213
  parentTag: el.parentTag,
11093
11214
  outerHtmlSnippet: el.outerHtmlSnippet,
@@ -11329,7 +11450,8 @@ Requirements:
11329
11450
  });
11330
11451
  clearActiveOperationId(generationWidgetId);
11331
11452
 
11332
- const isServiceError = errorMsg.includes('temporarily unavailable') ||
11453
+ const isGitlabLimit = /gitlab rate limit|gitlab refused the (save|rollback)|last status code:\s*429/i.test(errorMsg);
11454
+ const isServiceError = isGitlabLimit || errorMsg.includes('temporarily unavailable') ||
11333
11455
  errorMsg.includes('Our team has been notified') ||
11334
11456
  errorMsg.includes('Too many generation requests');
11335
11457
  const isSvelteSyntaxError = errorMsg.includes('Svelte') ||
@@ -11348,7 +11470,7 @@ Requirements:
11348
11470
  ? $t('creator.codegen.aiGeneratedInvalidSvelteSyntax')
11349
11471
  : errorMsg;
11350
11472
 
11351
- showToast('error', isServiceError ? $t('creator.general.serviceTemporarilyUnavailable') : $t('creator.status.failed'), {
11473
+ showToast('error', isGitlabLimit ? $t('creator.general.rateLimited') : isServiceError ? $t('creator.general.serviceTemporarilyUnavailable') : $t('creator.status.failed'), {
11352
11474
  description: toastDescription,
11353
11475
  duration: isServiceError ? 10000 : 8000
11354
11476
  });
@@ -11594,6 +11716,7 @@ Requirements:
11594
11716
  const shownFailure = [completedPreviewBuildErr, !completedCommitSha ? unsavedText : null]
11595
11717
  .filter((part): part is string => !!part)
11596
11718
  .join('\n');
11719
+ sketchToolbarAfterRestore = false;
11597
11720
  patchCodegenUiState(generationWidgetId, {
11598
11721
  hasGeneratedCode: true,
11599
11722
  ...(completedCommitSha ? { lastCommitId: completedCommitSha } : {}),
@@ -11925,13 +12048,8 @@ Requirements:
11925
12048
  // Update global flag: true only if the CURRENT widget is still generating
11926
12049
  isGeneratingCode = !!(focusedPanelWidgetId && generatingWidgetIds[focusedPanelWidgetId]);
11927
12050
  setCrossTabGenerating(false, generationWidgetId);
11928
- // A finished run already loads the new preview. Reloading here as well
11929
- // flashed the shape a second time. A failed run still needs the one reload.
11930
- if (getPanelState(generationWidgetId).lastGenerationFailed) {
11931
- void tick().then(() => {
11932
- widgetShapeLivePreviewsRef?.requestReload?.(generationWidgetId, { immediate: true });
11933
- });
11934
- }
12051
+ // A finished run already loads the new preview when the worker build lands.
12052
+ // A failed run kept the previous frame, so reloading it only flashes the same picture.
11935
12053
  // The API refused this run and the widget is free of it now: follow the person's own generation, or catch up with the
11936
12054
  // newer code that was saved. (Not awaited: a followed run can take minutes, and the queue behind this one must not wait.)
11937
12055
  if (afterRefusal) {
@@ -12308,6 +12426,7 @@ Requirements:
12308
12426
  codeGenerationStatus,
12309
12427
  agentHarnessOutput,
12310
12428
  dynamicWorkerPreviewStatus,
12429
+ deferredVersionRecorded,
12311
12430
  setAuthToken as setWsAuthToken,
12312
12431
  setWebsocketApiUrl,
12313
12432
  resetRealtimeState
@@ -14004,10 +14123,9 @@ Requirements:
14004
14123
  const ps = getPanelDisplayState(widgetId);
14005
14124
  const liveVersion =
14006
14125
  ps.lastPublishedVersion ?? resolvePublishedVersionFromWidget(getWidgetById(widgetId));
14007
- // Newest first. Versions are one ascending sequence, so the number orders
14008
- // them correctly on its own; sorting by time is a stable tiebreak.
14126
+ // Oldest first, same as the chat: the first version is the top row, the latest is the bottom.
14009
14127
  const history = [...getShapePublishHistory(widgetId)].sort(
14010
- (a, b) => Number(b.version) - Number(a.version),
14128
+ (a, b) => Number(a.version) - Number(b.version),
14011
14129
  );
14012
14130
  const options: Array<{
14013
14131
  id: string;
@@ -14143,6 +14261,8 @@ Requirements:
14143
14261
  // draft/restore look like the last publish even when git had moved.
14144
14262
  if (versionId.startsWith('v:')) {
14145
14263
  const version = Number(versionId.slice(2));
14264
+ // Leaving the sketch. The drawing tools stay only while version 1 is the board.
14265
+ if (version !== 1) sketchToolbarAfterRestore = false;
14146
14266
  const record = getShapePublishHistory(widgetId).find((row) => Number(row.version) === version);
14147
14267
  const isPublished = !!(record?.publishedAt ?? record?.published_at);
14148
14268
  const newestDraft = getNewestDraftVersionId(widgetId);
@@ -15938,6 +16058,30 @@ $: if ($dynamicWorkerPreviewStatus.widgetId && $dynamicWorkerPreviewStatus.previ
15938
16058
  }
15939
16059
  }
15940
16060
 
16061
+ // A 429 left the preview up and the version menu empty. When GitLab accepts the same commit, the version lands here.
16062
+ let lastDeferredVersionEventKey: string | null = null;
16063
+ $: if ($deferredVersionRecorded.widgetId && $deferredVersionRecorded.commitId) {
16064
+ const deferredWidgetId = $deferredVersionRecorded.widgetId;
16065
+ const deferredCommitId = $deferredVersionRecorded.commitId;
16066
+ const deferredEventKey = `${deferredWidgetId}:${deferredCommitId}:${$deferredVersionRecorded.timestamp ?? ''}`;
16067
+ if (deferredEventKey !== lastDeferredVersionEventKey) {
16068
+ lastDeferredVersionEventKey = deferredEventKey;
16069
+ const deferredVersion = $deferredVersionRecorded.version;
16070
+ const deferredTitle = $deferredVersionRecorded.commitTitle;
16071
+ setTimeout(() => {
16072
+ console.log('[CreatorApp] Version recorded after GitLab accepted the save', deferredWidgetId.substring(0, 8), deferredVersion);
16073
+ patchCodegenUiState(deferredWidgetId, {
16074
+ lastCommitId: deferredCommitId,
16075
+ lastGenerationFailed: false,
16076
+ lastGenerationError: null,
16077
+ generateCodeStatus: deferredVersion ? `Version ${deferredVersion} saved` : 'Version saved',
16078
+ });
16079
+ stampCodegenTitleIntoPanelHistory(deferredWidgetId, deferredCommitId, deferredTitle);
16080
+ void loadPublishHistoryForPanel(deferredWidgetId, { silent: true, fresh: true });
16081
+ }, 0);
16082
+ }
16083
+ }
16084
+
15941
16085
  // ===================== Publish History =====================
15942
16086
 
15943
16087
  /**
@@ -17163,6 +17307,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17163
17307
  ? widgetIdsOnCanvas
17164
17308
  : [...(canvasRef?.getLinkedWidgetIds?.() ?? [])];
17165
17309
  const primaryId = await hydrateCanvasPrimaryWidget(linkedIds);
17310
+ await lockSimpleCanvasToOneWidget(primaryId);
17166
17311
  applyPrimarySelectionOnCanvas(primaryId);
17167
17312
  requestAnimationFrame(() => {
17168
17313
  setTimeout(() => applyPrimarySelectionOnCanvas(primaryId), 80);
@@ -17653,6 +17798,10 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17653
17798
  showToast('error', $t('creator.session.pleaseLoginFirst'));
17654
17799
  return;
17655
17800
  }
17801
+ if (simpleCanvasHasItsWidget()) {
17802
+ showToast('info', $t('creator.widget.oneWidgetAlready'));
17803
+ return;
17804
+ }
17656
17805
  if (isWidgetOperationInProgress) {
17657
17806
  console.warn('[WidgetCreator] Another widget operation in progress, skipping convert');
17658
17807
  showToast('warning', $t('creator.general.pleaseWaitForTheCurrent'));
@@ -17782,6 +17931,11 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17782
17931
  */
17783
17932
  async function finalizeDraftConversion(draftId: string, prompt: string, extraImageUrls: string[] = []): Promise<string | null> {
17784
17933
  if (!draftId.startsWith(DRAFT_CONVERT_ID_PREFIX)) return null;
17934
+ if (simpleCanvasHasItsWidget()) {
17935
+ showToast('info', $t('creator.widget.oneWidgetAlready'));
17936
+ console.warn('[CreatorApp] Simple canvas already has a widget — not creating another');
17937
+ return null;
17938
+ }
17785
17939
  if (finalizingDraftConversions.has(draftId)) return null;
17786
17940
  finalizingDraftConversions.add(draftId);
17787
17941
  // Keep Widget Details open while the canvas sketch is replaced (selection
@@ -18012,6 +18166,35 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18012
18166
  }
18013
18167
  }
18014
18168
 
18169
+ /** Advanced off: the canvas already has its one widget, so another must not be created. */
18170
+ function simpleCanvasHasItsWidget(): boolean {
18171
+ if (!embedded || multipleWidgetsAllowed) return false;
18172
+ const primaryId = (canvasPrimaryWidgetId || '').trim();
18173
+ return !!primaryId && !isDraftConvertId(primaryId);
18174
+ }
18175
+
18176
+ /**
18177
+ * Simple canvas: leave the primary widget's shape, drop the others, and place
18178
+ * the primary when the board is still showing a different widget.
18179
+ */
18180
+ async function lockSimpleCanvasToOneWidget(primaryId: string | null): Promise<void> {
18181
+ if (!embedded || multipleWidgetsAllowed || !canvasRef || !primaryId) return;
18182
+ const removed = canvasRef.keepOnlyWidgetShape?.(primaryId) ?? 0;
18183
+ const linked = canvasRef.getLinkedWidgetIds?.() ?? new Set<string>();
18184
+ let placed = false;
18185
+ if (!linked.has(primaryId)) {
18186
+ const widget = getWidgetById(primaryId) as { name?: string; thumbnailUrl?: string | null; thumbnail_url?: string | null } | null;
18187
+ const preview = widget?.thumbnailUrl ?? widget?.thumbnail_url ?? null;
18188
+ canvasRef.addWidgetShape?.(primaryId, widget?.name, 0, 1, preview);
18189
+ placed = true;
18190
+ console.log('[CreatorApp] Simple canvas placed the one widget', primaryId.slice(0, 8));
18191
+ }
18192
+ if (removed > 0 || placed) {
18193
+ canvasRef.saveNow?.();
18194
+ syncWidgetShapeLivePreviews();
18195
+ }
18196
+ }
18197
+
18015
18198
  /** Draft panel id helper — true when the id is a synthetic convert draft. */
18016
18199
  function isDraftConvertId(widgetId: string | null | undefined): boolean {
18017
18200
  return !!widgetId && widgetId.startsWith(DRAFT_CONVERT_ID_PREFIX);
@@ -18741,6 +18924,25 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18741
18924
  void captureListThumbnail(widgetId, true);
18742
18925
  }}
18743
18926
  onSetPrimaryWidget={handleSetPrimaryWidget}
18927
+ showElementSelector={!!canvasPrimaryWidgetId && !isDraftConvertId(canvasPrimaryWidgetId)}
18928
+ showDrawingTools={showDrawingTools}
18929
+ elementSelectorActive={!!(canvasPrimaryWidgetId && selectorEnabledByWidgetId[canvasPrimaryWidgetId])}
18930
+ selectorGuide={{
18931
+ click: $t('creator.elementSelector.clickPartToReference'),
18932
+ parentChild: $t('creator.elementSelector.parentChild'),
18933
+ hold: $t('creator.elementSelector.hold'),
18934
+ cmd: $t('creator.elementSelector.cmdCtrl'),
18935
+ interact: $t('creator.elementSelector.toInteract'),
18936
+ esc: $t('creator.elementSelector.esc'),
18937
+ done: $t('creator.elementSelector.done'),
18938
+ }}
18939
+ onToggleElementSelector={() => {
18940
+ if (!canvasPrimaryWidgetId || isDraftConvertId(canvasPrimaryWidgetId)) return;
18941
+ handleToggleWidgetSelector(
18942
+ canvasPrimaryWidgetId,
18943
+ !selectorEnabledByWidgetId[canvasPrimaryWidgetId],
18944
+ );
18945
+ }}
18744
18946
  onAfterRender={syncWidgetShapeLivePreviews}
18745
18947
  getWidgetName={getWidgetNameById}
18746
18948
  widgetNameRevision={widgetNamesRevision}
@@ -18820,9 +19022,11 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18820
19022
  isGenerating={isAnyWidgetGenerating()}
18821
19023
  onLiveFrameShown={noteShapePreviewShown}
18822
19024
  resolveSelectorEnabled={(widgetId) => !!selectorEnabledByWidgetId[widgetId]}
19025
+ showUnderShapeSelectorHint={false}
18823
19026
  resolveSelectedElements={(widgetId) => selectedElementsByWidgetId[widgetId] ?? []}
18824
19027
  onSelectWidgetElement={(widgetId, element) => handleSelectWidgetElement(widgetId, element)}
18825
19028
  onRemoveWidgetElement={(widgetId, elementId) => handleRemoveWidgetElement(widgetId, elementId)}
19029
+ onUpdateWidgetElementNote={(widgetId, elementId, note) => handleUpdateWidgetElementNote(widgetId, elementId, note)}
18826
19030
  onCloseWidgetSelector={(widgetId) => {
18827
19031
  handleToggleWidgetSelector(widgetId, false);
18828
19032
  canvasRef?.setWidgetShapeBodyDragAllowed?.(widgetId, false);
@@ -19536,7 +19740,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
19536
19740
  runPublishForPanel(panelWidgetId, Number(viewingVersion));
19537
19741
  }}
19538
19742
  disabled={!canPublishDraftVersionForPanel(panelWidgetId, viewingVersion) || getPublishGateForPanel(panelWidgetId, Number(viewingVersion)).disabled}
19539
- title={$t('creator.common.buildThisDraftVersionAnd')}
19743
+ title={$t('creator.livePreviews.publishThisDraft')}
19540
19744
  class="wc-version-publish-btn shrink-0 inline-flex items-center justify-center min-w-[4.75rem] w-[4.75rem] text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-emerald-600 bg-emerald-600 text-white hover:bg-emerald-700 disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
19541
19745
  >
19542
19746
  {isPublishing && publishingWidgetId === panelWidgetId ? '...' : $t('creator.common.publish')}
@@ -19582,7 +19786,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
19582
19786
  class="wc-version-history-scroll flex flex-col gap-1 overflow-x-hidden {hasChatScroll ? 'overflow-y-auto' : 'overflow-y-visible'}"
19583
19787
  style="{hasChatScroll ? 'max-height: 185px; margin-inline-end: -4px; padding-inline-end: 4px;' : 'max-height: none;'} scrollbar-width: thin; scrollbar-color: rgba(0,0,0,0.2) transparent;"
19584
19788
  >
19585
- {#each ps.publishHistory as record (record.id)}
19789
+ {#each [...ps.publishHistory].sort((a, b) => Number(a.version) - Number(b.version)) as record (record.id)}
19586
19790
  {@const rowVersion = Number(record.version)}
19587
19791
  {@const rowIsDraft = !(record.publishedAt ?? record.published_at)}
19588
19792
  {@const rowIsViewing = rowVersion === Number(viewingVersion)}
@@ -19781,9 +19985,17 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
19781
19985
  />
19782
19986
  {/snippet}
19783
19987
  {#snippet generationOptionChecks()}
19784
- <GenerationOptionsPanel
19988
+ <BrandKitPanel
19785
19989
  part="checks"
19786
19990
  showPresetLibraries={debugMode}
19991
+ showBrandKit={debugMode}
19992
+ bind:brandKitEnabled
19993
+ bind:primary={brandPrimary}
19994
+ bind:secondary={brandSecondary}
19995
+ bind:title={brandTitle}
19996
+ bind:sub={brandSub}
19997
+ bind:fonts={brandFonts}
19998
+ bind:fontUploads
19787
19999
  bind:librariesEnabled
19788
20000
  bind:libraries={generationLibraries}
19789
20001
  bind:libraryGitUrl
@@ -19833,7 +20045,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
19833
20045
  versionLabelByPrompt={versionPromptLabelsByWidgetId[panelWidgetId] ?? emptyVersionLabels}
19834
20046
  versionTimeline={versionTimelineByWidgetId[panelWidgetId] ?? emptyVersionTimeline}
19835
20047
  viewingVersion={viewingVersionByWidgetId[panelWidgetId] ?? null}
19836
- showSelector={!isDraftConvertId(panelWidgetId)}
20048
+ showSelector={false}
19837
20049
  isSelectorActive={!!selectorEnabledByWidgetId[panelWidgetId]}
19838
20050
  selectedElements={selectedElementsByWidgetId[panelWidgetId] ?? []}
19839
20051
  onToggleSelector={(active) => handleToggleWidgetSelector(panelWidgetId, active)}
@@ -19857,6 +20069,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
19857
20069
  onRestoreCheckpointBackend={(conversationId, checkpointMessageId) =>
19858
20070
  handleRestoreCheckpoint(conversationId, checkpointMessageId, panelWidgetId)
19859
20071
  }
20072
+ onRateVersion={mayRateVersions() ? handleRateVersion : undefined}
20073
+ versionRatings={versionRatingsByMessageId}
19860
20074
  onChatReady={(methods) => handleChatReady(methods, panelWidgetId)}
19861
20075
  onDraftChange={() => handleChatDraftChange(panelWidgetId)}
19862
20076
  onConversationChange={(conversationId) => handleChatConversationChange(conversationId, panelWidgetId)}