@widgetic/chat 0.1.17 → 0.1.18

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.
@@ -1,6 +1,8 @@
1
1
  <script lang="ts">
2
2
  import { onMount, onDestroy, untrack } from 'svelte';
3
3
  import type { Snippet } from 'svelte';
4
+ import { writable } from 'svelte/store';
5
+ import { shareTextDirection, type TextDirection } from '@widgetic/design-system/components/textDirection';
4
6
  import { chatStore, getCurrentState, getCurrentMessages } from '../stores/chatStore.js';
5
7
  import { createChatService } from '../services/chatService.js';
6
8
  import { setLogsEnabled, chatLog, chatWarn } from '../utils/logger.js';
@@ -11,12 +13,33 @@
11
13
  import ChatInput from './ChatInput.svelte';
12
14
  import ActionBar from './ActionBar.svelte';
13
15
  import StatusIndicator from './StatusIndicator.svelte';
16
+ import { provideChatLanguage } from '../i18n/language.js';
17
+ import { actionFailureKey, contextTypeLabel } from '../i18n/labels.js';
18
+ import type { ChatMessageKey } from '../i18n/messages.js';
14
19
 
15
20
  // Props
16
21
  interface Props {
17
22
  context: ChatContext;
18
23
  config?: Partial<ChatConfig>;
19
24
  class?: string;
25
+ /**
26
+ * The language of the chat: a BCP 47 tag ("de", "pt-BR"). It sets the plural rules and how numbers are written. Left
27
+ * out, the chat speaks English. Setting it again changes the words of a chat that is already open.
28
+ */
29
+ locale?: string | null;
30
+ /**
31
+ * The page's own words: any of the chat's messages by key (the catalog is `CHAT_MESSAGES`; `checkChatMessages` says
32
+ * what is wrong with a set). A key left out keeps its English text. Setting it again replaces the whole set.
33
+ */
34
+ messages?: Readonly<Record<string, unknown>> | null;
35
+ /**
36
+ * Which way the chat is read: "ltr" or "rtl". With "rtl" the layout is the mirror image (what starts a line starts at the
37
+ * right: your messages are at the left, the send button is at the left of the input), and what a person writes in a
38
+ * message reads by its own first letter. It is NOT worked out from `locale`: a chat on a page that is laid out left to
39
+ * right can speak Arabic and still be left to right. Left out, the chat is read the way the screen around it is, and
40
+ * left to right when nothing around it says. Can change while the chat is open. Code is read left to right on every screen.
41
+ */
42
+ dir?: TextDirection;
20
43
  /** Inline style passed to the root chat container (e.g. `height: 600px`). */
21
44
  style?: string;
22
45
  isCompleted?: boolean;
@@ -63,6 +86,11 @@
63
86
  * so the host can re-run codegen without duplicating the user bubble.
64
87
  */
65
88
  onRetryMessage?: (content: string) => Promise<void>;
89
+ /**
90
+ * What the "Upgrade" button of a failure about the plan or the credits does. Without it the button opens the
91
+ * billing page of the Widgetic site; a host that is a guest on somebody else's page gives its own function.
92
+ */
93
+ onUpgradePlans?: () => void;
66
94
  /**
67
95
  * When provided, attachments are uploaded immediately and stored as CDN URLs
68
96
  * instead of large data URLs in chat history. Host should use TUS for files >10MB.
@@ -123,6 +151,11 @@
123
151
  replaceComplete?: boolean;
124
152
  /** Panel under the action bar, shown when those extras expand. */
125
153
  composerExtras?: Snippet;
154
+ /**
155
+ * Turns a line the host saved in English into what the visitor reads (the widget creator passes
156
+ * `conversationLineLabel`). When omitted, message text is shown as stored.
157
+ */
158
+ storedLineLabel?: (content: string) => string;
126
159
  }
127
160
 
128
161
  // Expose methods to parent component
@@ -162,7 +195,40 @@
162
195
  updateLastUserMessageAttachments: (attachments: Array<{ id?: string; url: string; file_type?: string; file_name?: string | null }>) => void;
163
196
  }
164
197
 
165
- let { context, config = {}, class: className = '', style = '', isCompleted = false, onStatsUpdate, onChatReady, onCompletionToggle, onSendMessage, onLoadConversations, onLoadMessages, onCreateConversation, onSaveMessage, onRestoreCheckpointBackend, onTakeScreenshot, onConversationChange, onDraftChange, onRetryMessage, onUploadChatFile, showHeader = true, headerTitle = '', showDescriptionHeader = true, showLogs = true, resizeExpandsContainer = false, onMessagesResize, widgetHeadCommitSha = null, versionLabelByCommitSha = {}, versionLabelByPrompt = {}, versionTimeline = [], viewingVersion = null, isGenerating = false, onStopGeneration, renderDesignControls, actionBarExtras, completeReplacement, replaceComplete = false, composerExtras }: Props = $props();
198
+ let { context, config = {}, class: className = '', locale = null, messages: languageMessages = null, dir = undefined, style = '', isCompleted = false, onStatsUpdate, onChatReady, onCompletionToggle, onSendMessage, onLoadConversations, onLoadMessages, onCreateConversation, onSaveMessage, onRestoreCheckpointBackend, onTakeScreenshot, onConversationChange, onDraftChange, onRetryMessage, onUpgradePlans, onUploadChatFile, showHeader = true, headerTitle = '', showDescriptionHeader = true, showLogs = true, resizeExpandsContainer = false, onMessagesResize, widgetHeadCommitSha = null, versionLabelByCommitSha = {}, versionLabelByPrompt = {}, versionTimeline = [], viewingVersion = null, isGenerating = false, onStopGeneration, renderDesignControls, actionBarExtras, completeReplacement, replaceComplete = false, composerExtras, storedLineLabel }: Props = $props();
199
+
200
+ // The words of everything inside the chat, in the language the page chose. The page can change the language while the
201
+ // chat is open: the settings are read again whenever they change (and setting the same language again does nothing).
202
+ const language = provideChatLanguage(untrack(() => ({ locale, messages: languageMessages })));
203
+ const { t } = language;
204
+ $effect(() => {
205
+ language.update({ locale, messages: languageMessages });
206
+ });
207
+
208
+ // The direction every part below reads from Svelte's context, and follows when the page changes `dir`.
209
+ const givenDirection = writable<TextDirection | undefined>(untrack(() => dir));
210
+ const textDirection = shareTextDirection(givenDirection);
211
+ $effect(() => {
212
+ givenDirection.set(dir);
213
+ });
214
+
215
+ /** The texts of the failures that trying the load again can mend. The banner offers its button for these only. */
216
+ const loadFailureTexts = new Set<string>();
217
+
218
+ /**
219
+ * Says a failure in the banner over the chat, in the language the chat has at this moment. The sentence is made once and
220
+ * kept as it was made: a banner that is open when the page changes the language keeps its words until it is dismissed.
221
+ */
222
+ function showFailure(key: ChatMessageKey) {
223
+ chatStore.actions.updateUI({ errorMessage: $t(key) });
224
+ }
225
+
226
+ /** Says a failure of loading, and remembers its text so the banner offers to load again (a button is for these only). */
227
+ function showLoadFailure(key: ChatMessageKey) {
228
+ const failureText = $t(key);
229
+ loadFailureTexts.add(failureText);
230
+ chatStore.actions.updateUI({ errorMessage: failureText });
231
+ }
166
232
 
167
233
  function notifyDraftChange() {
168
234
  onDraftChange?.();
@@ -291,9 +357,7 @@
291
357
 
292
358
  const loaded = await loadConversations();
293
359
  if (loaded === null) {
294
- chatStore.actions.updateUI({
295
- errorMessage: 'Could not load chat history.',
296
- });
360
+ showLoadFailure('chat.error.loadHistory');
297
361
  return;
298
362
  }
299
363
 
@@ -315,9 +379,7 @@
315
379
  await initializeForContext(context.id);
316
380
  } catch (error) {
317
381
  console.error('[Chat] Retry load history failed:', error);
318
- chatStore.actions.updateUI({
319
- errorMessage: 'Could not load chat history.',
320
- });
382
+ showLoadFailure('chat.error.loadHistory');
321
383
  }
322
384
  }
323
385
 
@@ -328,9 +390,7 @@
328
390
  await initializeForContext(context.id);
329
391
  } catch (error) {
330
392
  console.error('[Chat] Failed to initialize:', error);
331
- chatStore.actions.updateUI({
332
- errorMessage: 'Failed to initialize chat. Please try again.',
333
- });
393
+ showFailure('chat.error.initialize');
334
394
  } finally {
335
395
  isInitialized = true;
336
396
  }
@@ -388,9 +448,7 @@
388
448
  return loaded;
389
449
  } catch (error) {
390
450
  console.error('Failed to load conversations:', error);
391
- chatStore.actions.updateUI({
392
- errorMessage: 'Failed to load conversations.'
393
- });
451
+ showLoadFailure('chat.error.loadConversations');
394
452
  return null;
395
453
  } finally {
396
454
  chatStore.actions.updateUI({ isLoading: false });
@@ -399,7 +457,7 @@
399
457
 
400
458
  async function createNewConversation(title?: string) {
401
459
  try {
402
- const defaultTitle = title || `Chat about ${context.title || context.id}`;
460
+ const defaultTitle = title || $t('chat.conversation.defaultTitle', { name: context.title || context.id });
403
461
  const conversation = onCreateConversation
404
462
  ? await onCreateConversation(context.id, defaultTitle)
405
463
  : await chatService.createConversation(context.id, { title: defaultTitle });
@@ -435,9 +493,7 @@
435
493
  markWidgetHeadAtLatestCommit();
436
494
  } catch (error) {
437
495
  console.error('Failed to load conversation:', error);
438
- chatStore.actions.updateUI({
439
- errorMessage: 'Failed to load conversation.'
440
- });
496
+ showLoadFailure('chat.error.loadConversation');
441
497
  } finally {
442
498
  chatStore.actions.updateUI({ isLoading: false });
443
499
  }
@@ -564,9 +620,7 @@
564
620
 
565
621
  } catch (error) {
566
622
  console.error('Failed to send message:', error);
567
- chatStore.actions.updateUI({
568
- errorMessage: 'Failed to send message. Please try again.'
569
- });
623
+ showFailure('chat.error.sendMessage');
570
624
  } finally {
571
625
  localIsSending = false;
572
626
  }
@@ -683,7 +737,7 @@
683
737
 
684
738
  if (!screenshotDataUrl) {
685
739
  chatWarn('[Chat] Screenshot capture returned null');
686
- chatStore.actions.updateUI({ errorMessage: 'Screenshot capture failed — no preview available.' });
740
+ showFailure('chat.error.screenshotUnavailable');
687
741
  return;
688
742
  }
689
743
 
@@ -715,9 +769,7 @@
715
769
  // chatLog('Screenshot captured and added to attachments');
716
770
  } catch (error) {
717
771
  console.error('Screenshot capture failed:', error);
718
- chatStore.actions.updateUI({
719
- errorMessage: 'Failed to capture screenshot'
720
- });
772
+ showFailure('chat.error.screenshotFailed');
721
773
  }
722
774
  }
723
775
 
@@ -733,9 +785,7 @@
733
785
  } catch (error) {
734
786
  console.error('Failed to start recording:', error);
735
787
  localIsRecording = false;
736
- chatStore.actions.updateUI({
737
- errorMessage: 'Failed to start recording'
738
- });
788
+ showFailure('chat.error.recordingStartFailed');
739
789
  }
740
790
  }
741
791
 
@@ -765,9 +815,7 @@
765
815
 
766
816
  } catch (error) {
767
817
  console.error('Failed to stop recording:', error);
768
- chatStore.actions.updateUI({
769
- errorMessage: 'Failed to stop recording'
770
- });
818
+ showFailure('chat.error.recordingStopFailed');
771
819
  }
772
820
  }
773
821
 
@@ -954,17 +1002,13 @@
954
1002
  }
955
1003
  } catch (error) {
956
1004
  console.error('Failed to update conversation status:', error);
957
- chatStore.actions.updateUI({
958
- errorMessage: 'Failed to update conversation status'
959
- });
1005
+ showFailure('chat.error.statusUpdateFailed');
960
1006
  }
961
1007
  }
962
1008
 
963
1009
  function handleActionError(detail: { type: string; error: unknown }) {
964
1010
  console.error(`ActionBar ${detail.type} error:`, detail.error);
965
- chatStore.actions.updateUI({
966
- errorMessage: `${detail.type} action failed. Please try again.`
967
- });
1011
+ showFailure(actionFailureKey(detail.type));
968
1012
  }
969
1013
 
970
1014
  async function handleSuggestionSelected(suggestion: string) {
@@ -1004,9 +1048,7 @@
1004
1048
  });
1005
1049
  } catch (err) {
1006
1050
  console.error('[Chat] Clarification suggestion send failed:', err);
1007
- chatStore.actions.updateUI({
1008
- errorMessage: 'Failed to send the selected suggestion. Please try again.'
1009
- });
1051
+ showFailure('chat.error.sendSuggestion');
1010
1052
  }
1011
1053
  }
1012
1054
 
@@ -1075,6 +1117,8 @@
1075
1117
 
1076
1118
  const checkpointUser = currentMessages.find((msg: any) => msg.id === checkpointUserId);
1077
1119
  const headAssistant = currentMessages.find((msg: any) => msg.id === headAssistantId);
1120
+ // The line saved below ("Restored from Version 3") is read back by its words, so it is written in English whatever the
1121
+ // page's language is; `versionLabelText` says it again in the page's language when the turn is drawn.
1078
1122
  const sourceLabel = versionLabelForCommitContent(headAssistant?.messageContent) || 'a previous version';
1079
1123
  const promptCopy = String(checkpointUser?.messageContent || '').trim();
1080
1124
 
@@ -1097,9 +1141,7 @@
1097
1141
 
1098
1142
  } catch (error) {
1099
1143
  console.error('Failed to restore checkpoint:', error);
1100
- chatStore.actions.updateUI({
1101
- errorMessage: 'Failed to restore checkpoint. Please try again.'
1102
- });
1144
+ showFailure('chat.error.restoreFailed');
1103
1145
  }
1104
1146
  }
1105
1147
 
@@ -1634,6 +1676,7 @@
1634
1676
  <div
1635
1677
  bind:this={chatContainer}
1636
1678
  class="{className ? className : 'prompt-chat-ct'} relative flex flex-col overflow-hidden bg-white border border-gray-300 {className ? '' : 'rounded-medium'} h-full min-h-0"
1679
+ dir={$textDirection}
1637
1680
  style={style}
1638
1681
  >
1639
1682
  {#if showHeader}
@@ -1651,7 +1694,7 @@
1651
1694
  {#if context.type === 'frame'}📱{:else if context.type === 'text'}📄{:else if context.type === 'image'}🖼️{:else if context.type === 'document'}📋{:else}💬{/if}
1652
1695
  </span>
1653
1696
  <span class="text-xs text-gray-500">
1654
- {context.type} chat
1697
+ {$t('chat.header.typeChat', { type: contextTypeLabel(context.type, $t) })}
1655
1698
  </span>
1656
1699
  <StatusIndicator
1657
1700
  status={isCompleted ? 'completed' : (isLoading ? 'loading' : 'active')}
@@ -1692,8 +1735,10 @@
1692
1735
  onSuggestionSelected={handleSuggestionSelected}
1693
1736
  onRestoreCheckpoint={handleRestoreCheckpoint}
1694
1737
  onRetryMessage={handleRetryMessage}
1738
+ {onUpgradePlans}
1695
1739
  onClarificationSuggestionSelected={handleClarificationSuggestionSelected}
1696
1740
  {renderDesignControls}
1741
+ {storedLineLabel}
1697
1742
  />
1698
1743
  </div>
1699
1744
 
@@ -1705,8 +1750,8 @@
1705
1750
  onpointerdown={handleMessagesResizeStart}
1706
1751
  role="separator"
1707
1752
  aria-orientation="horizontal"
1708
- aria-label="Resize messages area"
1709
- title="Drag to resize messages area"
1753
+ aria-label={$t('chat.resize.label')}
1754
+ title={$t('chat.resize.title')}
1710
1755
  >
1711
1756
  <div class="drag-grip w-14 h-1 rounded-full bg-gray-500 {isResizingMessages ? 'bg-blue-400' : ''}"></div>
1712
1757
  </div>
@@ -1745,13 +1790,13 @@
1745
1790
  <div class="prompt-chat-attachments-tray-ct flex flex-wrap gap-2 p-3 border-t border-gray-100 bg-white shrink-0">
1746
1791
  {#each localAttachments as attachment, index (attachment.preview || attachment.uploadedUrl || attachment.file?.name || index)}
1747
1792
  <div class="prompt-chat-attachment-item-ct relative bg-gray-50 rounded-lg overflow-hidden">
1748
- <span class="prompt-chat-attachment-index-badge absolute top-0.5 left-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">{index + 1}</span>
1793
+ <span class="prompt-chat-attachment-index-badge 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">{index + 1}</span>
1749
1794
  {#if isImageAttachment(attachment)}
1750
1795
  <!-- svelte-ignore a11y_click_events_have_key_events -->
1751
1796
  <!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
1752
1797
  <img
1753
1798
  src={getFooterAttachmentPreviewUrl(attachment)}
1754
- alt={attachment.file?.name || 'attachment'}
1799
+ alt={attachment.file?.name || $t('chat.attachment.namelessAlt')}
1755
1800
  class="prompt-chat-attachment-image-preview w-16 h-16 object-cover cursor-pointer"
1756
1801
  onclick={() => {
1757
1802
  const previewUrl = getFooterAttachmentPreviewUrl(attachment);
@@ -1761,21 +1806,21 @@
1761
1806
  {:else}
1762
1807
  <div class="prompt-chat-attachment-file-preview flex items-center gap-2 p-3 w-32">
1763
1808
  <span class="text-lg">📄</span>
1764
- <span class="text-xs text-gray-600 truncate flex-1">{attachment.file?.name || 'attachment'}</span>
1809
+ <span class="text-xs text-gray-600 truncate flex-1">{attachment.file?.name || $t('chat.attachment.namelessAlt')}</span>
1765
1810
  </div>
1766
1811
  {/if}
1767
1812
 
1768
1813
  <button
1769
1814
  type="button"
1770
- class="prompt-chat-remove-attachment-btn absolute top-1 right-1 w-5 h-5 bg-red-500 text-white rounded-full flex items-center justify-center text-xs hover:bg-red-600 cursor-pointer"
1815
+ class="prompt-chat-remove-attachment-btn absolute top-1 end-1 w-5 h-5 bg-red-500 text-white rounded-full flex items-center justify-center text-xs hover:bg-red-600 cursor-pointer"
1771
1816
  onclick={() => removeFooterAttachment(index)}
1772
- aria-label="Remove attachment"
1817
+ aria-label={$t('chat.attachment.remove')}
1773
1818
  >
1774
1819
  ✕
1775
1820
  </button>
1776
1821
 
1777
1822
  {#if attachment.uploadProgress && attachment.uploadProgress > 0 && attachment.uploadProgress < 100}
1778
- <div class="prompt-chat-attachment-upload-bar absolute bottom-0 left-0 right-0 h-1 bg-gray-200">
1823
+ <div class="prompt-chat-attachment-upload-bar absolute bottom-0 start-0 end-0 h-1 bg-gray-200">
1779
1824
  <div class="h-full bg-blue-500 transition-all duration-300" style="width: {attachment.uploadProgress}%"></div>
1780
1825
  </div>
1781
1826
  {/if}
@@ -1821,9 +1866,10 @@
1821
1866
  >
1822
1867
  <button
1823
1868
  type="button"
1824
- class="prompt-chat-footer-lightbox-close-btn absolute top-4 right-4 w-9 h-9 rounded-full bg-white/15 text-white text-lg flex items-center justify-center cursor-pointer hover:bg-white/30"
1869
+ class="prompt-chat-footer-lightbox-close-btn absolute top-4 end-4 w-9 h-9 rounded-full bg-white/15 text-white text-lg flex items-center justify-center cursor-pointer hover:bg-white/30"
1825
1870
  onclick={() => (footerLightboxSrc = null)}
1826
- title="Close"
1871
+ title={$t('chat.attachment.close')}
1872
+ aria-label={$t('chat.attachment.close')}
1827
1873
  >
1828
1874
  ✕
1829
1875
  </button>
@@ -1832,7 +1878,7 @@
1832
1878
  <div class="prompt-chat-footer-lightbox-content max-w-[90vw] max-h-[90vh]" onclick={(e) => e.stopPropagation()}>
1833
1879
  <img
1834
1880
  src={footerLightboxSrc}
1835
- alt="Attachment preview"
1881
+ alt={$t('chat.attachment.previewAlt')}
1836
1882
  class="prompt-chat-footer-lightbox-image max-w-[90vw] max-h-[85vh] object-contain rounded-lg"
1837
1883
  />
1838
1884
  </div>
@@ -1841,21 +1887,23 @@
1841
1887
 
1842
1888
  <!-- Error Display -->
1843
1889
  {#if ui?.errorMessage}
1844
- <div class="error-message-ct absolute top-0 left-0 right-0 bg-red-50 border-l-4 border-red-400 p-3 flex items-center justify-between gap-2 text-sm text-red-700 rounded-none z-10">
1890
+ <div class="error-message-ct absolute top-0 start-0 end-0 bg-red-50 border-s-4 border-red-400 p-3 flex items-center justify-between gap-2 text-sm text-red-700 rounded-none z-10">
1845
1891
  <span class="error-message-text min-w-0 flex-1">{ui.errorMessage}</span>
1846
1892
  <div class="error-message-actions flex items-center gap-2 shrink-0">
1847
- {#if ui.errorMessage.startsWith('Could not load chat history') || ui.errorMessage.startsWith('Failed to load')}
1893
+ {#if loadFailureTexts.has(ui.errorMessage)}
1848
1894
  <button
1849
1895
  type="button"
1850
1896
  class="retry-load-history-btn px-2 py-1 text-xs font-semibold rounded border border-red-300 bg-white text-red-700 hover:bg-red-100"
1851
1897
  onclick={() => void retryLoadHistory()}
1852
1898
  >
1853
- Retry load history
1899
+ {$t('chat.error.retryLoad')}
1854
1900
  </button>
1855
1901
  {/if}
1856
1902
  <button
1857
- class="ml-0 text-red-400 hover:text-red-600 font-semibold w-5 h-5 flex items-center justify-center"
1903
+ class="ms-0 text-red-400 hover:text-red-600 font-semibold w-5 h-5 flex items-center justify-center"
1858
1904
  onclick={() => chatStore.actions.updateUI({ errorMessage: null })}
1905
+ title={$t('chat.error.dismiss')}
1906
+ aria-label={$t('chat.error.dismiss')}
1859
1907
  >
1860
1908
  ✕
1861
1909
  </button>
@@ -1,4 +1,5 @@
1
1
  import type { Snippet } from 'svelte';
2
+ import { type TextDirection } from '@widgetic/design-system/components/textDirection';
2
3
  import type { ChatConfig, ChatContext } from '../types/index.js';
3
4
  import type { ClarificationSuggestion, DesignControlRequest } from '../types/message.js';
4
5
  import type { AttachmentInput } from '../types/attachment.js';
@@ -55,6 +56,24 @@ interface Props {
55
56
  context: ChatContext;
56
57
  config?: Partial<ChatConfig>;
57
58
  class?: string;
59
+ /**
60
+ * The language of the chat: a BCP 47 tag ("de", "pt-BR"). It sets the plural rules and how numbers are written. Left
61
+ * out, the chat speaks English. Setting it again changes the words of a chat that is already open.
62
+ */
63
+ locale?: string | null;
64
+ /**
65
+ * The page's own words: any of the chat's messages by key (the catalog is `CHAT_MESSAGES`; `checkChatMessages` says
66
+ * what is wrong with a set). A key left out keeps its English text. Setting it again replaces the whole set.
67
+ */
68
+ messages?: Readonly<Record<string, unknown>> | null;
69
+ /**
70
+ * Which way the chat is read: "ltr" or "rtl". With "rtl" the layout is the mirror image (what starts a line starts at the
71
+ * right: your messages are at the left, the send button is at the left of the input), and what a person writes in a
72
+ * message reads by its own first letter. It is NOT worked out from `locale`: a chat on a page that is laid out left to
73
+ * right can speak Arabic and still be left to right. Left out, the chat is read the way the screen around it is, and
74
+ * left to right when nothing around it says. Can change while the chat is open. Code is read left to right on every screen.
75
+ */
76
+ dir?: TextDirection;
58
77
  /** Inline style passed to the root chat container (e.g. `height: 600px`). */
59
78
  style?: string;
60
79
  isCompleted?: boolean;
@@ -103,6 +122,11 @@ interface Props {
103
122
  * so the host can re-run codegen without duplicating the user bubble.
104
123
  */
105
124
  onRetryMessage?: (content: string) => Promise<void>;
125
+ /**
126
+ * What the "Upgrade" button of a failure about the plan or the credits does. Without it the button opens the
127
+ * billing page of the Widgetic site; a host that is a guest on somebody else's page gives its own function.
128
+ */
129
+ onUpgradePlans?: () => void;
106
130
  /**
107
131
  * When provided, attachments are uploaded immediately and stored as CDN URLs
108
132
  * instead of large data URLs in chat history. Host should use TUS for files >10MB.
@@ -173,6 +197,11 @@ interface Props {
173
197
  replaceComplete?: boolean;
174
198
  /** Panel under the action bar, shown when those extras expand. */
175
199
  composerExtras?: Snippet;
200
+ /**
201
+ * Turns a line the host saved in English into what the visitor reads (the widget creator passes
202
+ * `conversationLineLabel`). When omitted, message text is shown as stored.
203
+ */
204
+ storedLineLabel?: (content: string) => string;
176
205
  }
177
206
  declare const Chat: import("svelte").Component<Props, {}, "">;
178
207
  type Chat = ReturnType<typeof Chat>;
@@ -1,5 +1,14 @@
1
1
  <script lang="ts">
2
2
  import type { ChatContext, ChatConversation } from '../types/index.js';
3
+ import { useChatLanguage } from '../i18n/language.js';
4
+ import { contextTypeLabel } from '../i18n/labels.js';
5
+ import { dirForUserText, useTextDirection } from '@widgetic/design-system/components/textDirection';
6
+
7
+ // The words of the header, in the language of the chat above
8
+ const { t } = useChatLanguage();
9
+
10
+ // The way the screen is read: a title is what a person began the conversation with, and reads by its own first letter on a right to left screen.
11
+ const textDirection = useTextDirection();
3
12
 
4
13
  // Props
5
14
  interface Props {
@@ -28,15 +37,6 @@
28
37
  onSwitchConversation(conversationId);
29
38
  }
30
39
 
31
- function formatContextType(type: string): string {
32
- switch (type) {
33
- case 'frame': return '🖼️ Frame';
34
- case 'text': return '📄 Document';
35
- case 'canvas': return '🎨 Canvas';
36
- default: return '💬 Chat';
37
- }
38
- }
39
-
40
40
  function truncateTitle(title: string, maxLength: number = 30): string {
41
41
  return title.length > maxLength ? title.substring(0, maxLength) + '...' : title;
42
42
  }
@@ -65,7 +65,7 @@
65
65
  {context.title || context.id}
66
66
  </h3>
67
67
  <p class="text-xs text-gray-500 dark:text-gray-400">
68
- {context.type} chat
68
+ {$t('chat.header.typeChat', { type: contextTypeLabel(context.type, $t) })}
69
69
  </p>
70
70
  </div>
71
71
  </div>
@@ -78,8 +78,8 @@
78
78
  <button
79
79
  class="w-8 h-8 rounded-md flex items-center justify-center text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
80
80
  onclick={() => showConversationMenu = !showConversationMenu}
81
- title="Switch conversation"
82
- aria-label="Switch conversation"
81
+ title={$t('chat.header.switchConversation')}
82
+ aria-label={$t('chat.header.switchConversation')}
83
83
  >
84
84
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="w-4 h-4">
85
85
  <circle cx="12" cy="12" r="1"/>
@@ -97,10 +97,10 @@
97
97
  onclick={() => showConversationMenu = false}
98
98
  ></div>
99
99
 
100
- <div class="absolute top-full right-0 mt-1 w-64 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-600 rounded-lg shadow-lg z-50 max-h-80 overflow-hidden">
100
+ <div class="absolute top-full end-0 mt-1 w-64 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-600 rounded-lg shadow-lg z-50 max-h-80 overflow-hidden">
101
101
  <!-- Menu Header -->
102
102
  <div class="flex items-center justify-between p-3 border-b border-gray-200 dark:border-gray-600">
103
- <span class="font-medium text-gray-900 dark:text-gray-100 text-sm">Conversations</span>
103
+ <span class="font-medium text-gray-900 dark:text-gray-100 text-sm">{$t('chat.header.conversations')}</span>
104
104
  <button
105
105
  class="flex items-center gap-1 px-2 py-1 text-xs font-medium text-blue-600 hover:text-blue-800 hover:bg-blue-50 rounded transition-colors"
106
106
  onclick={onNewConversation}
@@ -109,7 +109,7 @@
109
109
  <path d="M12 5v14"/>
110
110
  <path d="M5 12h14"/>
111
111
  </svg>
112
- New
112
+ {$t('chat.header.new')}
113
113
  </button>
114
114
  </div>
115
115
 
@@ -117,14 +117,14 @@
117
117
  <div class="max-h-60 overflow-y-auto">
118
118
  {#each conversations as conversation (conversation.id)}
119
119
  <button
120
- class="w-full flex items-center justify-between p-3 text-left hover:bg-gray-50 dark:hover:bg-gray-700 border-b border-gray-100 dark:border-gray-600 last:border-b-0 transition-colors"
120
+ class="w-full flex items-center justify-between p-3 text-start hover:bg-gray-50 dark:hover:bg-gray-700 border-b border-gray-100 dark:border-gray-600 last:border-b-0 transition-colors"
121
121
  class:active={conversation.id === currentConversationId}
122
122
  onclick={() => {
123
123
  onSwitchConversation(conversation.id);
124
124
  showConversationMenu = false;
125
125
  }}
126
126
  >
127
- <span class="font-medium text-sm truncate text-gray-900 dark:text-gray-100">{conversation.title || 'Untitled'}</span>
127
+ <span class="font-medium text-sm truncate text-gray-900 dark:text-gray-100" dir={dirForUserText($textDirection)}>{conversation.title || $t('chat.header.untitled')}</span>
128
128
  <div class="flex items-center gap-2">
129
129
  {#if conversation._unreadCount && conversation._unreadCount > 0}
130
130
  <span class="bg-blue-600 text-white text-xs px-1.5 py-0.5 rounded-full min-w-[1.25rem] h-5 flex items-center justify-center">
@@ -143,8 +143,8 @@
143
143
  <button
144
144
  class="w-8 h-8 rounded-md flex items-center justify-center text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
145
145
  onclick={onNewConversation}
146
- title="New conversation"
147
- aria-label="Start new conversation"
146
+ title={$t('chat.header.newConversationTitle')}
147
+ aria-label={$t('chat.header.newConversation')}
148
148
  >
149
149
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="w-4 h-4">
150
150
  <path d="M12 5v14"/>
@@ -157,8 +157,8 @@
157
157
  <button
158
158
  class="w-8 h-8 rounded-md flex items-center justify-center text-gray-500 dark:text-gray-400 hover:text-red-600 dark:hover:text-red-400 hover:bg-red-50 dark:hover:bg-red-900 transition-colors"
159
159
  onclick={onClose}
160
- title="Close chat"
161
- aria-label="Close chat"
160
+ title={$t('chat.header.close')}
161
+ aria-label={$t('chat.header.close')}
162
162
  >
163
163
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="w-4 h-4">
164
164
  <path d="M18 6L6 18"/>