@widgetic/chat 0.1.36 → 0.1.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.
@@ -123,6 +123,8 @@
123
123
  showPanelHeader?: boolean;
124
124
  /** When true with `onToggleConsole`, shows the debug console icon in the panel header. */
125
125
  showConsoleControl?: boolean;
126
+ /** Increment to bounce the Send button and show the publish-first tooltip (host-driven). */
127
+ sendNudgeToken?: number;
126
128
  consoleOpen?: boolean;
127
129
  onToggleConsole?: () => void;
128
130
  /** Custom title displayed in the header. If empty/undefined, defaults to context.title or context.id. */
@@ -230,6 +232,8 @@
230
232
  setDraftText: (text: string) => void;
231
233
  /** Get attachment preview data URLs in current order. */
232
234
  getAttachmentDataUrls: () => string[];
235
+ /** Attached pictures as `data:` URLs, the form the draft keeps so they are still attached after a refresh. */
236
+ getDraftAttachmentDataUrls: () => string[];
233
237
  /** Get CDN upload row IDs for image attachments (codegen attachmentIds). */
234
238
  getAttachmentUploadIds: () => string[];
235
239
  /** Replace chat attachments from stored data URLs (restores draft attachments). */
@@ -250,7 +254,7 @@
250
254
  updateLastUserMessageAttachments: (attachments: Array<{ id?: string; url: string; file_type?: string; file_name?: string | null }>) => void;
251
255
  }
252
256
 
253
- let { context, config = {}, class: className = '', locale = null, messages: languageMessages = null, dir = undefined, style = '', isCompleted = false, onStatsUpdate, onChatReady, onCompletionToggle, onSendMessage, onLoadConversations, onLoadMessages, onCreateConversation, onSaveMessage, onRestoreCheckpointBackend, onRateVersion, versionRatings: ratingsFromHost = {}, onTakeScreenshot, onConversationChange, onDraftChange, onRetryMessage, onUpgradePlans, onUploadChatFile, showHeader = true, showPanelHeader = false, showConsoleControl = false, consoleOpen = false, onToggleConsole, headerTitle = '', showDescriptionHeader = true, showLogs = true, resizeExpandsContainer = false, onMessagesResize, onMessagesDrag, onMessagesDragEnd, onLoadOlderMessages, widgetHeadCommitSha = null, versionLabelByCommitSha = {}, versionLabelByPrompt = {}, versionTimeline = [], isGenerating = false, generationStream = '', generationThinking = '', generationPlan = null, onStopGeneration, renderDesignControls, actionBarExtras, completeReplacement, replaceComplete = false, showSelector = false, isSelectorActive = false, selectedElements = [], onToggleSelector, onRemoveSelectedElement, onClearSelectedElements, composerExtras, storedLineLabel, composerModels = [], selectedComposerModelId = null, onSelectComposerModel }: Props = $props();
257
+ let { context, config = {}, class: className = '', locale = null, messages: languageMessages = null, dir = undefined, style = '', isCompleted = false, onStatsUpdate, onChatReady, onCompletionToggle, onSendMessage, onLoadConversations, onLoadMessages, onCreateConversation, onSaveMessage, onRestoreCheckpointBackend, onRateVersion, versionRatings: ratingsFromHost = {}, onTakeScreenshot, onConversationChange, onDraftChange, onRetryMessage, onUpgradePlans, onUploadChatFile, showHeader = true, showPanelHeader = false, showConsoleControl = false, sendNudgeToken = 0, consoleOpen = false, onToggleConsole, headerTitle = '', showDescriptionHeader = true, showLogs = true, resizeExpandsContainer = false, onMessagesResize, onMessagesDrag, onMessagesDragEnd, onLoadOlderMessages, widgetHeadCommitSha = null, versionLabelByCommitSha = {}, versionLabelByPrompt = {}, versionTimeline = [], isGenerating = false, generationStream = '', generationThinking = '', generationPlan = null, onStopGeneration, renderDesignControls, actionBarExtras, completeReplacement, replaceComplete = false, showSelector = false, isSelectorActive = false, selectedElements = [], onToggleSelector, onRemoveSelectedElement, onClearSelectedElements, composerExtras, storedLineLabel, composerModels = [], selectedComposerModelId = null, onSelectComposerModel }: Props = $props();
254
258
 
255
259
  // The words of everything inside the chat, in the language the page chose. The page can change the language while the
256
260
  // chat is open: the settings are read again whenever they change (and setting the same language again does nothing).
@@ -1089,6 +1093,45 @@
1089
1093
 
1090
1094
  let footerLightboxSrc: string | null = $state(null);
1091
1095
 
1096
+ /** Biggest image kept in the draft: a draft is written to the browser's storage on every change. */
1097
+ const MAX_PERSISTED_IMAGE_BYTES = 6 * 1024 * 1024;
1098
+
1099
+ /** Reads an attached image into a `data:` URL for the draft; resolves to '' when it cannot or should not be kept. */
1100
+ function readImageAsDataUrl(file: File): Promise<string> {
1101
+ return new Promise((resolve) => {
1102
+ if (!file.type.startsWith('image/') || file.size > MAX_PERSISTED_IMAGE_BYTES) {
1103
+ resolve('');
1104
+ return;
1105
+ }
1106
+ try {
1107
+ const reader = new FileReader();
1108
+ reader.onload = () => resolve(typeof reader.result === 'string' ? reader.result : '');
1109
+ reader.onerror = () => {
1110
+ chatWarn('[Chat] Could not read the image for the draft:', file.name);
1111
+ resolve('');
1112
+ };
1113
+ reader.readAsDataURL(file);
1114
+ } catch (error) {
1115
+ chatWarn('[Chat] Could not read the image for the draft:', error);
1116
+ resolve('');
1117
+ }
1118
+ });
1119
+ }
1120
+
1121
+ /** Keeps an attached image in the draft, so it is still attached after a refresh. */
1122
+ async function rememberImageForDraft(entry: AttachmentInput): Promise<void> {
1123
+ const dataUrl = await readImageAsDataUrl(entry.file);
1124
+ if (!dataUrl) return;
1125
+ entry.persistedDataUrl = dataUrl;
1126
+ // The attachment may have been removed while the file was read: only a tray that still holds it is saved.
1127
+ // It is set on the object the tray holds now, not on a copy: the upload keeps writing to that object.
1128
+ const inTray = localAttachments.find((att) => att.file === entry.file);
1129
+ if (!inTray) return;
1130
+ inTray.persistedDataUrl = dataUrl;
1131
+ localAttachments = [...localAttachments];
1132
+ notifyDraftChange();
1133
+ }
1134
+
1092
1135
  async function addFilesAsAttachments(files: File[]) {
1093
1136
  const usableFiles = (files || []).filter((file) => file && file.size > 0);
1094
1137
  if (usableFiles.length === 0) return;
@@ -1110,6 +1153,8 @@
1110
1153
  expandChatForAttachmentGrowth(previousCount);
1111
1154
  chatStore.actions.updateUI({ errorMessage: null });
1112
1155
  console.log('[Chat] attachments now', localAttachments.length);
1156
+ // The draft keeps each picture as it is attached, before the upload ends (a refresh can come at any time).
1157
+ for (const entry of newAttachments) void rememberImageForDraft(entry);
1113
1158
 
1114
1159
  try {
1115
1160
  localIsUploading = true;
@@ -1171,12 +1216,12 @@
1171
1216
  showFailure(actionFailureKey(detail.type));
1172
1217
  }
1173
1218
 
1174
- async function handleSuggestionSelected(suggestion: string) {
1175
- // chatLog('Suggestion selected in Chat — autocompleting into input:', suggestion);
1176
- // Autocomplete into input instead of sending immediately — lets user review,
1177
- // edit, and attach an image before sending (e.g. "Generate code from this design"
1178
- // is useless without an attached screenshot).
1179
- setDraftText(suggestion);
1219
+ function handleSuggestionSelected(suggestion: string) {
1220
+ const trimmed = suggestion.trim();
1221
+ if (!trimmed) return;
1222
+ // A suggestion (the empty-state cards and the "Try next" follow-ups of the panel alike) goes into the input and is
1223
+ // not sent: the person reviews it, edits it, attaches a picture, and presses Send.
1224
+ setDraftText(trimmed);
1180
1225
  }
1181
1226
 
1182
1227
  /** Tapping a suggestion chip attached to an assistant clarification card sends it
@@ -1410,6 +1455,17 @@
1410
1455
  .filter((url) => !!url);
1411
1456
  }
1412
1457
 
1458
+ /**
1459
+ * The attached pictures in the one form a refresh can rebuild them from: `data:` URLs. This is what the draft keeps;
1460
+ * `getAttachmentDataUrls` stays the list of addresses to send with a message (a CDN address when the upload ended).
1461
+ */
1462
+ function getDraftAttachmentDataUrls(): string[] {
1463
+ return localAttachments
1464
+ .filter((att) => att.type === 'image' || att.file?.type?.startsWith('image/'))
1465
+ .map((att) => att.persistedDataUrl || (att.preview?.startsWith('data:') ? att.preview : '') || '')
1466
+ .filter((url) => !!url);
1467
+ }
1468
+
1413
1469
  function getAttachmentUploadIds(): string[] {
1414
1470
  return localAttachments
1415
1471
  .filter((att) => Boolean(att.uploadId))
@@ -1786,6 +1842,7 @@
1786
1842
  getDraftText,
1787
1843
  setDraftText,
1788
1844
  getAttachmentDataUrls,
1845
+ getDraftAttachmentDataUrls,
1789
1846
  getAttachmentUploadIds,
1790
1847
  restoreAttachmentsFromDataUrls,
1791
1848
  clearDraft,
@@ -1920,18 +1977,24 @@
1920
1977
 
1921
1978
  <div
1922
1979
  bind:this={chatContainer}
1923
- class="{className ? className : 'prompt-chat-ct'} border-border bg-background relative flex h-full min-h-0 w-chat-panel max-w-full flex-col overflow-hidden border {className ? '' : 'rounded-panel'}"
1980
+ class="{className ? className : 'prompt-chat-ct'} border-border bg-background relative flex h-full min-h-0 max-w-full flex-col overflow-hidden border {showPanelHeader ? 'w-full' : 'w-chat-panel'} {className ? '' : 'rounded-panel'}"
1924
1981
  dir={$textDirection}
1925
1982
  style={style}
1926
1983
  >
1927
1984
  {#if showPanelHeader}
1985
+ {@const panelTitle =
1986
+ (currentMessages?.length ?? 0) > 0 || isGenerating
1987
+ ? (headerTitle?.trim() || context.title || '')
1988
+ : ''}
1928
1989
  <PanelChatHeader
1929
- title={headerTitle || context.title || context.id}
1990
+ title={panelTitle}
1930
1991
  showConsole={showConsoleControl}
1931
1992
  {consoleOpen}
1932
1993
  onToggleConsole={onToggleConsole}
1933
1994
  onNewConversation={onCreateConversation || onLoadConversations ? () => void createNewConversation() : undefined}
1934
- onOpenHistory={onLoadConversations ? () => void loadConversations() : undefined}
1995
+ conversations={availableConversations}
1996
+ currentConversationId={currentConversationId}
1997
+ onSelectConversation={(id) => void loadConversation(id)}
1935
1998
  />
1936
1999
  {:else if showHeader}
1937
2000
  <!-- Simple Chat Header -->
@@ -1965,7 +2028,7 @@
1965
2028
 
1966
2029
  <!-- Chat Interface -->
1967
2030
  <div
1968
- class="prompt-chat-messages-area flex min-h-0 flex-col overflow-hidden"
2031
+ class="prompt-chat-messages-area flex min-h-0 flex-col overflow-hidden {showPanelHeader ? 'flex-1' : ''}"
1969
2032
  style="{messagesAreaHeight !== null
1970
2033
  ? `flex: 0 0 ${messagesAreaHeight}px; height: ${messagesAreaHeight}px;`
1971
2034
  : 'flex: 1 1 auto; min-height: 0;'}"
@@ -1975,7 +2038,8 @@
1975
2038
  messages={currentMessages || []}
1976
2039
  isLoading={isLoading}
1977
2040
  isInitialized={isInitialized}
1978
- {showEmptyState}
2041
+ showEmptyState={showEmptyState && localAttachments.length === 0}
2042
+ panelLayout={showPanelHeader}
1979
2043
  {context}
1980
2044
  isCompleted={isCompleted}
1981
2045
  enableAutoCodeDetection={config?.features?.autoCodeDetection === true}
@@ -2003,6 +2067,7 @@
2003
2067
  />
2004
2068
  </div>
2005
2069
 
2070
+ {#if !showPanelHeader}
2006
2071
  <div
2007
2072
  class="prompt-chat-messages-resize-handle flex items-center justify-center cursor-ns-resize select-none border-t border-b border-gray-300 bg-gray-100"
2008
2073
  class:bg-blue-100={isResizingMessages}
@@ -2016,8 +2081,11 @@
2016
2081
  >
2017
2082
  <div class="drag-grip w-14 h-1 rounded-full bg-gray-500 {isResizingMessages ? 'bg-blue-400' : ''}"></div>
2018
2083
  </div>
2084
+ {/if}
2019
2085
 
2020
- <div class="prompt-chat-footer-ct shrink-0 flex flex-col">
2086
+ <div
2087
+ class="prompt-chat-footer-ct shrink-0 flex flex-col {showPanelHeader ? 'px-4 pb-4 max-lg:px-3' : ''}"
2088
+ >
2021
2089
  {#if showActionBar}
2022
2090
  <ActionBar
2023
2091
  {context}
@@ -2131,6 +2199,13 @@
2131
2199
  {/if}
2132
2200
 
2133
2201
  <ChatComposer
2202
+ {sendNudgeToken}
2203
+ panelLayout={showPanelHeader}
2204
+ placeholder={showPanelHeader
2205
+ ? (currentMessages?.length ?? 0) > 0
2206
+ ? $t('chat.input.placeholderFollowUp')
2207
+ : $t('chat.input.placeholderCreate')
2208
+ : undefined}
2134
2209
  bind:value={() => localInputText, (nextInputText) => {
2135
2210
  localInputText = nextInputText;
2136
2211
  notifyDraftChange();
@@ -29,6 +29,8 @@ interface ChatMethods {
29
29
  setDraftText: (text: string) => void;
30
30
  /** Get attachment preview data URLs in current order. */
31
31
  getAttachmentDataUrls: () => string[];
32
+ /** Attached pictures as `data:` URLs, the form the draft keeps so they are still attached after a refresh. */
33
+ getDraftAttachmentDataUrls: () => string[];
32
34
  /** Get CDN upload row IDs for image attachments (codegen attachmentIds). */
33
35
  getAttachmentUploadIds: () => string[];
34
36
  /** Replace chat attachments from stored data URLs (restores draft attachments). */
@@ -160,6 +162,8 @@ interface Props {
160
162
  showPanelHeader?: boolean;
161
163
  /** When true with `onToggleConsole`, shows the debug console icon in the panel header. */
162
164
  showConsoleControl?: boolean;
165
+ /** Increment to bounce the Send button and show the publish-first tooltip (host-driven). */
166
+ sendNudgeToken?: number;
163
167
  consoleOpen?: boolean;
164
168
  onToggleConsole?: () => void;
165
169
  /** Custom title displayed in the header. If empty/undefined, defaults to context.title or context.id. */
@@ -4,6 +4,7 @@
4
4
  import { dirForUserText, useTextDirection } from '@widgetic/design-system/components/textDirection';
5
5
  import { Composer, IconButton } from '@widgetic/design-system/components/chat/index';
6
6
  import { chatLog } from '../utils/logger.js';
7
+ import { reduceSendNudge, SEND_NUDGE_VISIBLE_MS, type SendNudgePhase } from '../sendNudgeState.js';
7
8
 
8
9
  const { t } = useChatLanguage();
9
10
  const textDirection = useTextDirection();
@@ -27,6 +28,12 @@
27
28
  onFilesDropped?: (files: File[]) => void;
28
29
  /** Opens the file picker. The "+" of the toolbar is drawn only when the page can attach files. */
29
30
  onAttach?: () => void;
31
+ /** Figma side-panel composer: no top border on the shell; DS Composer keeps its own border. */
32
+ panelLayout?: boolean;
33
+ /** Figma panel composer (65:31): arrow-up send icon instead of paper-plane. */
34
+ sendIcon?: 'send' | 'arrow-up';
35
+ /** Increment from the host to nudge Send before publish. */
36
+ sendNudgeToken?: number;
30
37
  }
31
38
 
32
39
  let {
@@ -44,10 +51,68 @@
44
51
  onStop,
45
52
  onInputChange,
46
53
  onFilesDropped,
47
- onAttach
54
+ onAttach,
55
+ panelLayout = false,
56
+ sendIcon = 'send',
57
+ sendNudgeToken = 0,
48
58
  }: Props = $props();
49
59
 
60
+ const composerSendIcon = $derived(panelLayout ? 'arrow-up' : sendIcon);
61
+
50
62
  let isFileDragOver = $state(false);
63
+ let sendNudgePhase = $state<SendNudgePhase>('idle');
64
+ let sendNudgeBounce = $state(false);
65
+ let sendNudgeHideTimer: ReturnType<typeof setTimeout> | null = null;
66
+ let sendNudgeBounceTimer: ReturnType<typeof setTimeout> | null = null;
67
+ let lastNudgeToken = $state(0);
68
+
69
+ const publishNudgeText = $derived($t('chat.input.publishNudge'));
70
+ const sendAttention = $derived(
71
+ sendNudgePhase === 'active'
72
+ ? {
73
+ bounce: sendNudgeBounce,
74
+ hintOpen: true,
75
+ hintText: publishNudgeText,
76
+ }
77
+ : sendNudgeBounce
78
+ ? { bounce: true, hintOpen: false, hintText: '' }
79
+ : undefined,
80
+ );
81
+
82
+ function clearSendNudgeTimers() {
83
+ if (sendNudgeHideTimer) {
84
+ clearTimeout(sendNudgeHideTimer);
85
+ sendNudgeHideTimer = null;
86
+ }
87
+ if (sendNudgeBounceTimer) {
88
+ clearTimeout(sendNudgeBounceTimer);
89
+ sendNudgeBounceTimer = null;
90
+ }
91
+ }
92
+
93
+ function armSendNudge() {
94
+ clearSendNudgeTimers();
95
+ sendNudgePhase = reduceSendNudge(sendNudgePhase, 'trigger');
96
+ const reducedMotion =
97
+ typeof window !== 'undefined' &&
98
+ window.matchMedia('(prefers-reduced-motion: reduce)').matches;
99
+ sendNudgeBounce = !reducedMotion;
100
+ if (sendNudgeBounce) {
101
+ sendNudgeBounceTimer = setTimeout(() => {
102
+ sendNudgeBounce = false;
103
+ }, 750);
104
+ }
105
+ sendNudgeHideTimer = setTimeout(() => {
106
+ sendNudgePhase = reduceSendNudge(sendNudgePhase, 'autoHide');
107
+ }, SEND_NUDGE_VISIBLE_MS);
108
+ }
109
+
110
+ $effect(() => {
111
+ if (sendNudgeToken > 0 && sendNudgeToken !== lastNudgeToken) {
112
+ lastNudgeToken = sendNudgeToken;
113
+ armSendNudge();
114
+ }
115
+ });
51
116
 
52
117
  const busy = $derived(isGenerating || isSending);
53
118
  const allowEmptySend = $derived(canSendWithoutText);
@@ -91,6 +156,11 @@
91
156
  const trimmed = text.trim();
92
157
  if (!trimmed && !allowEmptySend) return;
93
158
  if (isSending && !isGenerating) return;
159
+ if (sendNudgePhase === 'active') {
160
+ sendNudgePhase = reduceSendNudge(sendNudgePhase, 'userInteract');
161
+ clearSendNudgeTimers();
162
+ sendNudgeBounce = false;
163
+ }
94
164
  onSend(trimmed, undefined);
95
165
  }
96
166
  </script>
@@ -100,6 +170,7 @@
100
170
  {#if onAttach}
101
171
  <IconButton
102
172
  variant="ghost"
173
+ data-testid="chat-composer-attach"
103
174
  label={$t('chat.actions.uploadLabel')}
104
175
  disabled={isSending && !isGenerating}
105
176
  onclick={() => onAttach?.()}
@@ -123,7 +194,7 @@
123
194
 
124
195
  <!-- svelte-ignore a11y_no_static_element_interactions -->
125
196
  <div
126
- class="chat-composer-shell border-border bg-background shrink-0 border-t {className} {isFileDragOver
197
+ class="chat-composer-shell border-border bg-background shrink-0 {panelLayout ? '' : 'border-t'} {className} {isFileDragOver
127
198
  ? 'outline-primary outline-2 outline-dashed'
128
199
  : ''}"
129
200
  {style}
@@ -133,7 +204,8 @@
133
204
  ondrop={handleFileDrop}
134
205
  >
135
206
  <Composer
136
- class="rounded-none border-0"
207
+ class={panelLayout ? 'w-full max-w-full' : 'rounded-none border-0'}
208
+ sendIcon={composerSendIcon}
137
209
  bind:value
138
210
  busy={isGenerating}
139
211
  disabled={isSending && !isGenerating}
@@ -152,5 +224,6 @@
152
224
  onSend={handleComposerSend}
153
225
  onStop={() => onStop?.()}
154
226
  leading={attachControl}
227
+ {sendAttention}
155
228
  />
156
229
  </div>
@@ -20,6 +20,12 @@ interface Props {
20
20
  onFilesDropped?: (files: File[]) => void;
21
21
  /** Opens the file picker. The "+" of the toolbar is drawn only when the page can attach files. */
22
22
  onAttach?: () => void;
23
+ /** Figma side-panel composer: no top border on the shell; DS Composer keeps its own border. */
24
+ panelLayout?: boolean;
25
+ /** Figma panel composer (65:31): arrow-up send icon instead of paper-plane. */
26
+ sendIcon?: 'send' | 'arrow-up';
27
+ /** Increment from the host to nudge Send before publish. */
28
+ sendNudgeToken?: number;
23
29
  }
24
30
  declare const ChatComposer: import("svelte").Component<Props, {}, "value">;
25
31
  type ChatComposer = ReturnType<typeof ChatComposer>;