@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.
package/README.md CHANGED
@@ -223,6 +223,110 @@ const customConfig = {
223
223
  };
224
224
  ```
225
225
 
226
+ ## Languages
227
+
228
+ The chat shows English until it is told otherwise. Two props of `Chat` change that, and both can change while the chat
229
+ is open:
230
+
231
+ ```svelte
232
+ <Chat
233
+ {context}
234
+ locale="de"
235
+ messages={{
236
+ 'chat.input.placeholder': 'Schreiben Sie Ihre Nachricht...',
237
+ 'chat.input.send': 'Senden',
238
+ 'chat.attachment.more': '{count, plural, one {+# weitere Datei} other {+# weitere Dateien}}',
239
+ }}
240
+ />
241
+ ```
242
+
243
+ - **`locale`** is a BCP 47 language tag (`de`, `pt-BR`, `ar-EG`). It decides the plural rules and how the numbers of a
244
+ file size are written (`1.5 MB` or `1,5 MB`), all through `Intl`. It translates nothing. Blank or left out is
245
+ English. A tag the browser does not know is said once in the console and numbers stay English.
246
+ - **`messages`** replaces words. Every word the chat shows is a message with a key; give the keys you
247
+ want to change and every key you leave out stays English, so a language can be added one screen at a time. A key that
248
+ does not exist is ignored and the console says which key you probably meant.
249
+ - **`dir`** is a third prop, for a language written right to left: `'rtl'` lays the chat out from the right, `'ltr'` (or
250
+ the prop left out) leaves it as it was. It is not taken from `locale`: it says which way the screen is read, and the page
251
+ decides that (`resolveTextDirection(locale)` from `@widgetic/design-system/i18n` answers it for a language tag). Left out,
252
+ the chat follows the screen it sits in (a component above it that calls `provideTextDirection(store)` from
253
+ `@widgetic/design-system/components/textDirection`). What a person types in the box is read by its own first letter on a
254
+ right to left screen, and an empty box takes the direction of the screen (`dir="auto"` on an empty field reads left to
255
+ right, which would put the hint and the caret at the wrong edge).
256
+
257
+ `CHAT_MESSAGES` is the list: an object of every key and its English text, and it is the list to hand to a translator:
258
+
259
+ ```ts
260
+ import { CHAT_MESSAGES } from '@widgetic/chat';
261
+
262
+ console.log(Object.keys(CHAT_MESSAGES).length); // every word of the chat
263
+ console.log(CHAT_MESSAGES['chat.attachment.more']); // '{count, plural, one {+# more file} other {+# more files}}'
264
+ ```
265
+
266
+ | Keys start with | The words of |
267
+ | --- | --- |
268
+ | `chat.header.`, `chat.contextPreview.`, `chat.contextType.`, `chat.conversation.` | the header, the list of conversations, the collapsed chat, the name of what a chat is about ("frame", "text"), and the title of a new conversation |
269
+ | `chat.messages.` | the list of messages: the empty state, "thinking", checkpoints, "You are here", versions and commit ids |
270
+ | `chat.input.`, `chat.actions.` | the box you type in, and the screenshot, record, upload and "mark complete" buttons |
271
+ | `chat.suggestions.` | the ideas offered to start with (five for each kind of thing a chat is about) and their headings |
272
+ | `chat.attachment.`, `chat.size.` | attachments, and file sizes ("1.5 MB") |
273
+ | `chat.status.`, `chat.code.`, `chat.resize.` | the status of a conversation, the code blocks and the drag handle |
274
+ | `chat.error.` | the sentences of the red banner, and its "Retry load history" button |
275
+
276
+ ### Writing a message
277
+
278
+ A message is text. Two kinds of `{...}` have a meaning:
279
+
280
+ | Write | It shows |
281
+ | --- | --- |
282
+ | `{name}` | a value the chat puts in (`'chat.header.typeChat': '{type} chat'`). A number is written the way the locale writes numbers. |
283
+ | `{count, plural, one {# file} other {# files}}` | the branch that fits the number in the page's language. `other` is required; `=0 {none}` matches exactly 0; `#` is the number. A language with more forms says so: Polish uses `one`, `few`, `many` and `other`. |
284
+
285
+ `\{`, `\}`, `\#` and `\\` write that character itself. Each English message names the values it is given: a
286
+ translation may leave one out, and it may use a value in any order, but it cannot ask for a value the message is never
287
+ given (it would show as written, `{kind}`).
288
+
289
+ ### Finding a mistake before a visitor does
290
+
291
+ `checkChatMessages(messages)` checks a `messages` object without showing anything, and `describeMessageProblem`
292
+ (from `@widgetic/design-system/i18n`) turns each problem into a sentence. It finds a key that does not exist (with the
293
+ nearest real one), a value that is not text, a template that does not parse, and a message that asks for a value it is
294
+ never given. An empty list means every message will be used. Put it in a test of your page:
295
+
296
+ ```ts
297
+ import { checkChatMessages } from '@widgetic/chat';
298
+ import { describeMessageProblem } from '@widgetic/design-system/i18n';
299
+ import german from './chat.de.json';
300
+
301
+ expect(checkChatMessages(german).map(describeMessageProblem)).toEqual([]);
302
+ ```
303
+
304
+ While the chat runs, a message that cannot be used is never thrown: the English text of that key is shown and the
305
+ console says `[Chat] ...` once.
306
+
307
+ ### What stays as it is
308
+
309
+ - **Words that belong to someone else.** The title of a conversation (the one your page or the server gave it), what
310
+ the assistant wrote, what people typed, file names, and the text a platform adapter returns are shown as they are.
311
+ The title of a conversation the chat makes itself ("Chat about …") is a message, and is saved in the language it was
312
+ made in.
313
+ - **A banner keeps the language it was made in.** A sentence in the red banner is made when something fails; if the page
314
+ changes language while it is showing, it stays as it was said until it is closed.
315
+ - **Lines the chat saves and reads back.** `Code generation completed! Commit: …`, `Restored from …` and `Commit: …`
316
+ are saved into the conversation, and the chat finds them again by those words (to know which turn made which
317
+ commit), so they are saved in English whatever the language of the page and drawn in the page's language.
318
+ - **Version names.** `versionLabelByCommitSha` and `versionLabelByPrompt` take English labels: `Version 4`. The chat
319
+ reads the number out of that, and says the label in the page's language when it draws it (`chat.messages.version`).
320
+ A label of any other shape (one you made up) is shown as you gave it.
321
+ - **Right to left.** The layout turns around when `Chat` is given `dir="rtl"` (see above). For a language written right to left a name that is put inside a sentence sits between two invisible marks (Unicode isolates U+2068 and U+2069, made by the shared translator), so the words around it cannot turn it around; a test that compares text has to leave them out.
322
+ - **The demo adapter.** The made-up screenshots and elements of `createWidgeticAdapter()` are English: they are
323
+ answers to your code, not words of a screen.
324
+ - **The design system.** The chat needs `@widgetic/design-system` **0.5.16 or newer**: the translator comes from
325
+ `@widgetic/design-system/i18n`, the same one the File Browser and the editor use.
326
+
327
+ A part of the chat used on its own (an `ActionBar` or a `ChatInput` outside a `Chat`) speaks English; inside a `Chat`
328
+ it reads the language of that chat, so two chats on one page can speak two languages.
329
+
226
330
  ## File Handling
227
331
 
228
332
  ### Supported File Types
@@ -1,6 +1,10 @@
1
1
  <script lang="ts">
2
2
  import type { Snippet } from 'svelte';
3
3
  import type { ChatContext } from '../types/context.js';
4
+ import { useChatLanguage } from '../i18n/language.js';
5
+
6
+ // The words of the buttons, in the language of the chat above
7
+ const { t } = useChatLanguage();
4
8
 
5
9
  // Props
6
10
  interface Props {
@@ -98,14 +102,14 @@
98
102
  class="action-button screenshot-button"
99
103
  onclick={handleScreenshot}
100
104
  disabled={disabled}
101
- title="Take Screenshot"
102
- aria-label="Take screenshot of current content"
105
+ title={$t('chat.actions.screenshotTitle')}
106
+ aria-label={$t('chat.actions.screenshotLabel')}
103
107
  >
104
108
  <svg viewBox="0 0 24 24" class="action-icon">
105
109
  <path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/>
106
110
  <circle cx="12" cy="13" r="4"/>
107
111
  </svg>
108
- <span class="action-label">Screenshot</span>
112
+ <span class="action-label">{$t('chat.actions.screenshot')}</span>
109
113
  </button>
110
114
  {/if}
111
115
 
@@ -116,21 +120,21 @@
116
120
  class:recording={isRecording}
117
121
  onclick={handleRecording}
118
122
  disabled={disabled || !conversationId}
119
- title={isRecording ? 'Stop Recording' : 'Start Recording'}
120
- aria-label={isRecording ? 'Stop recording' : 'Start recording'}
123
+ title={isRecording ? $t('chat.actions.stopRecordingTitle') : $t('chat.actions.startRecordingTitle')}
124
+ aria-label={isRecording ? $t('chat.actions.stopRecordingLabel') : $t('chat.actions.startRecordingLabel')}
121
125
  >
122
126
  {#if isRecording}
123
127
  <svg viewBox="0 0 24 24" class="action-icon">
124
128
  <rect x="6" y="6" width="12" height="12" rx="2"/>
125
129
  </svg>
126
- <span class="action-label">Stop</span>
130
+ <span class="action-label">{$t('chat.actions.stop')}</span>
127
131
  <div class="recording-indicator"></div>
128
132
  {:else}
129
133
  <svg viewBox="0 0 24 24" class="action-icon">
130
134
  <circle cx="12" cy="12" r="10"/>
131
135
  <circle cx="12" cy="12" r="6" fill="currentColor"/>
132
136
  </svg>
133
- <span class="action-label">Record</span>
137
+ <span class="action-label">{$t('chat.actions.record')}</span>
134
138
  {/if}
135
139
  </button>
136
140
  {/if}
@@ -141,13 +145,13 @@
141
145
  class="action-button upload-button"
142
146
  onclick={handleUpload}
143
147
  disabled={disabled}
144
- title="Upload File"
145
- aria-label="Upload file"
148
+ title={$t('chat.actions.uploadTitle')}
149
+ aria-label={$t('chat.actions.uploadLabel')}
146
150
  >
147
151
  <svg viewBox="0 0 24 24" class="action-icon">
148
152
  <path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66L9.64 16.2a2 2 0 0 1-2.83-2.83l8.49-8.49"/>
149
153
  </svg>
150
- <span class="action-label">Upload</span>
154
+ <span class="action-label">{$t('chat.actions.upload')}</span>
151
155
  </button>
152
156
  {/if}
153
157
 
@@ -160,20 +164,20 @@
160
164
  class:completed={isCompleted}
161
165
  onclick={handleCompletionToggle}
162
166
  disabled={disabled || !conversationId}
163
- title={isCompleted ? 'Mark as Active — you can keep iterating either way' : 'Mark this chat as done. You can still send messages and iterate on the widget.'}
164
- aria-label={isCompleted ? 'Mark conversation as active' : 'Mark conversation as complete'}
167
+ title={isCompleted ? $t('chat.actions.markActiveTitle') : $t('chat.actions.markCompleteTitle')}
168
+ aria-label={isCompleted ? $t('chat.actions.markActiveLabel') : $t('chat.actions.markCompleteLabel')}
165
169
  >
166
170
  {#if isCompleted}
167
171
  <svg viewBox="0 0 24 24" class="action-icon">
168
172
  <polyline points="20,6 9,17 4,12"/>
169
173
  </svg>
170
- <span class="action-label">Completed</span>
174
+ <span class="action-label">{$t('chat.actions.completed')}</span>
171
175
  {:else}
172
176
  <svg viewBox="0 0 24 24" class="action-icon">
173
177
  <circle cx="12" cy="12" r="10"/>
174
178
  <path d="m9 12 2 2 4-4"/>
175
179
  </svg>
176
- <span class="action-label">Complete</span>
180
+ <span class="action-label">{$t('chat.actions.complete')}</span>
177
181
  {/if}
178
182
  </button>
179
183
  {/if}
@@ -293,7 +297,7 @@
293
297
  .recording-indicator {
294
298
  position: absolute;
295
299
  top: 0.25rem;
296
- right: 0.25rem;
300
+ inset-inline-end: 0.25rem;
297
301
  width: 0.5rem;
298
302
  height: 0.5rem;
299
303
  background-color: #ef4444;
@@ -1,5 +1,14 @@
1
1
  <script lang="ts">
2
2
  import type { ContentItemOutput } from '../types/message.js';
3
+ import { useChatLanguage } from '../i18n/language.js';
4
+ import { fileSizeText } from '../i18n/labels.js';
5
+ import { dirForUserText, useTextDirection } from '@widgetic/design-system/components/textDirection';
6
+
7
+ // The words of the attachments, and the language the numbers of a size are written in
8
+ const { t, locale } = useChatLanguage();
9
+
10
+ // The way the screen is read: a file name is what a person called it, 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 {
@@ -20,8 +29,21 @@
20
29
  onView
21
30
  }: Props = $props();
22
31
 
32
+ /**
33
+ * Moves the node up to the top of the page it is on, so that it covers everything (a lightbox, say). That is the page's
34
+ * <body> — unless the chat is in a shadow root, on a partner's page: the styles reach only what is inside the shadow
35
+ * root, and the partner's <body> is not ours, so there it goes to the top of the shadow root (into the element that
36
+ * holds the whole chat, which also keeps the colors and the fonts that element gives).
37
+ */
23
38
  function portalToBody(node: HTMLElement) {
24
- document.body.appendChild(node);
39
+ const root = node.getRootNode();
40
+ if (root instanceof ShadowRoot) {
41
+ let topElement: Node = node;
42
+ while (topElement.parentNode && topElement.parentNode !== root) topElement = topElement.parentNode;
43
+ (topElement !== node ? topElement : root).appendChild(node);
44
+ } else {
45
+ document.body.appendChild(node);
46
+ }
25
47
  return {
26
48
  destroy() {
27
49
  node.remove();
@@ -40,12 +62,9 @@
40
62
  return '📎';
41
63
  }
42
64
 
65
+ // A size as the biggest unit that keeps it above 1 ("1.5 MB"), in the language of the chat
43
66
  function formatFileSize(bytes: number | null | undefined): string {
44
- if (!bytes || bytes === 0) return '';
45
- const k = 1024;
46
- const sizes = ['B', 'KB', 'MB', 'GB'];
47
- const i = Math.floor(Math.log(bytes) / Math.log(k));
48
- return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
67
+ return fileSizeText(bytes, $t, $locale);
49
68
  }
50
69
 
51
70
  function isImageType(fileType: string, url?: string): boolean {
@@ -119,7 +138,7 @@
119
138
  <!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
120
139
  <img
121
140
  src={attachment.url}
122
- alt={attachment.file_name || 'Attachment'}
141
+ alt={attachment.file_name || $t('chat.attachment.alt')}
123
142
  class="attachment-image"
124
143
  loading="lazy"
125
144
  onclick={() => handleView(attachment)}
@@ -132,17 +151,19 @@
132
151
  preload="metadata"
133
152
  >
134
153
  <track kind="captions" />
135
- Your browser does not support video playback.
154
+ {$t('chat.attachment.noVideo')}
136
155
  </video>
137
156
  {:else}
138
157
  <button
139
158
  class="attachment-file"
140
159
  onclick={() => handleView(attachment)}
141
- title="Click to view {attachment.file_name || 'file'}"
160
+ title={attachment.file_name
161
+ ? $t('chat.attachment.view', { name: attachment.file_name })
162
+ : $t('chat.attachment.viewFile')}
142
163
  >
143
164
  <span class="file-icon">{getFileIcon(attachment.file_type)}</span>
144
165
  <div class="file-info">
145
- <span class="file-name">{attachment.file_name || 'Untitled'}</span>
166
+ <span class="file-name" dir={dirForUserText($textDirection)}>{attachment.file_name || $t('chat.attachment.untitled')}</span>
146
167
  {#if attachment.file_size}
147
168
  <span class="file-size">{formatFileSize(attachment.file_size)}</span>
148
169
  {/if}
@@ -154,7 +175,7 @@
154
175
 
155
176
  {#if hiddenCount > 0}
156
177
  <div class="more-attachments">
157
- +{hiddenCount} more file{hiddenCount !== 1 ? 's' : ''}
178
+ {$t('chat.attachment.more', { count: hiddenCount })}
158
179
  </div>
159
180
  {/if}
160
181
  </div>
@@ -168,7 +189,7 @@
168
189
  <div class="preview-image-container">
169
190
  <img
170
191
  src={attachment.url}
171
- alt={attachment.file_name || 'Attachment'}
192
+ alt={attachment.file_name || $t('chat.attachment.alt')}
172
193
  class="preview-image"
173
194
  loading="lazy"
174
195
  />
@@ -176,7 +197,8 @@
176
197
  <button
177
198
  class="remove-button"
178
199
  onclick={() => handleRemove(attachment)}
179
- title="Remove attachment"
200
+ title={$t('chat.attachment.remove')}
201
+ aria-label={$t('chat.attachment.remove')}
180
202
  >
181
203
  ✕
182
204
  </button>
@@ -191,13 +213,14 @@
191
213
  preload="metadata"
192
214
  >
193
215
  <track kind="captions" />
194
- Your browser does not support video playback.
216
+ {$t('chat.attachment.noVideo')}
195
217
  </video>
196
218
  {#if onRemove}
197
219
  <button
198
220
  class="remove-button"
199
221
  onclick={() => handleRemove(attachment)}
200
- title="Remove attachment"
222
+ title={$t('chat.attachment.remove')}
223
+ aria-label={$t('chat.attachment.remove')}
201
224
  >
202
225
  ✕
203
226
  </button>
@@ -208,7 +231,7 @@
208
231
  <div class="preview-file">
209
232
  <span class="file-icon">{getFileIcon(attachment.file_type)}</span>
210
233
  <div class="file-info">
211
- <span class="file-name">{attachment.file_name || 'Untitled'}</span>
234
+ <span class="file-name" dir={dirForUserText($textDirection)}>{attachment.file_name || $t('chat.attachment.untitled')}</span>
212
235
  {#if attachment.file_size}
213
236
  <span class="file-size">{formatFileSize(attachment.file_size)}</span>
214
237
  {/if}
@@ -218,7 +241,8 @@
218
241
  <button
219
242
  class="remove-button"
220
243
  onclick={() => handleRemove(attachment)}
221
- title="Remove attachment"
244
+ title={$t('chat.attachment.remove')}
245
+ aria-label={$t('chat.attachment.remove')}
222
246
  >
223
247
  ✕
224
248
  </button>
@@ -236,10 +260,10 @@
236
260
  <button
237
261
  class="compact-attachment-item"
238
262
  onclick={() => handleView(attachment)}
239
- title="{attachment.file_name || 'Untitled'} ({formatFileSize(attachment.file_size)})"
263
+ title="{attachment.file_name || $t('chat.attachment.untitled')} ({formatFileSize(attachment.file_size)})"
240
264
  >
241
265
  <span class="file-icon">{getFileIcon(attachment.file_type)}</span>
242
- <span class="file-name">{attachment.file_name || 'File'}</span>
266
+ <span class="file-name" dir={dirForUserText($textDirection)}>{attachment.file_name || $t('chat.attachment.fileFallback')}</span>
243
267
  </button>
244
268
  {/each}
245
269
 
@@ -256,25 +280,29 @@
256
280
  <!-- svelte-ignore a11y_click_events_have_key_events -->
257
281
  <!-- svelte-ignore a11y_no_static_element_interactions -->
258
282
  <div class="lightbox-overlay" use:portalToBody onclick={closeLightbox}>
259
- <button class="lightbox-close" onclick={closeLightbox} title="Close">✕</button>
283
+ <button
284
+ class="lightbox-close"
285
+ onclick={closeLightbox}
286
+ title={$t('chat.attachment.close')}
287
+ aria-label={$t('chat.attachment.close')}>✕</button>
260
288
  <!-- svelte-ignore a11y_click_events_have_key_events -->
261
289
  <!-- svelte-ignore a11y_no_static_element_interactions -->
262
290
  <div class="lightbox-content" onclick={(e) => e.stopPropagation()}>
263
291
  {#if isImageType(lightboxAttachment.file_type, lightboxAttachment.url)}
264
292
  <img
265
293
  src={lightboxAttachment.url}
266
- alt={lightboxAttachment.file_name || 'Attachment'}
294
+ alt={lightboxAttachment.file_name || $t('chat.attachment.alt')}
267
295
  class="lightbox-image"
268
296
  />
269
297
  {:else if lightboxAttachment.file_type.includes('pdf')}
270
298
  <iframe
271
299
  src={lightboxAttachment.url}
272
300
  class="lightbox-pdf"
273
- title={lightboxAttachment.file_name || 'PDF Document'}
301
+ title={lightboxAttachment.file_name || $t('chat.attachment.pdfTitle')}
274
302
  ></iframe>
275
303
  {/if}
276
304
  {#if lightboxAttachment.file_name}
277
- <div class="lightbox-caption">{lightboxAttachment.file_name}</div>
305
+ <div class="lightbox-caption" dir={dirForUserText($textDirection)}>{lightboxAttachment.file_name}</div>
278
306
  {/if}
279
307
  </div>
280
308
  </div>
@@ -338,7 +366,7 @@
338
366
  border-radius: 0.375rem;
339
367
  cursor: pointer;
340
368
  transition: background-color 0.2s;
341
- text-align: left;
369
+ text-align: start;
342
370
  width: 100%;
343
371
  color: inherit;
344
372
  }
@@ -403,7 +431,7 @@
403
431
  .remove-button {
404
432
  position: absolute;
405
433
  top: -0.25rem;
406
- right: -0.25rem;
434
+ inset-inline-end: -0.25rem;
407
435
  width: 1.25rem;
408
436
  height: 1.25rem;
409
437
  background: #ef4444;
@@ -514,7 +542,7 @@
514
542
  .lightbox-close {
515
543
  position: absolute;
516
544
  top: 16px;
517
- right: 16px;
545
+ inset-inline-end: 16px;
518
546
  width: 36px;
519
547
  height: 36px;
520
548
  border-radius: 50%;