@widgetic/chat 0.1.45 → 0.1.48

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/README.md +148 -20
  2. package/dist/components/AttachmentDisplay.svelte +22 -130
  3. package/dist/components/AttachmentPreviewDialog.svelte +428 -0
  4. package/dist/components/AttachmentPreviewDialog.svelte.d.ts +14 -0
  5. package/dist/components/Chat.svelte +514 -94
  6. package/dist/components/Chat.svelte.d.ts +19 -2
  7. package/dist/components/ChatComposer.svelte +126 -72
  8. package/dist/components/ChatComposer.svelte.d.ts +13 -3
  9. package/dist/components/ChatDropOverlay.svelte +58 -0
  10. package/dist/components/ChatDropOverlay.svelte.d.ts +8 -0
  11. package/dist/components/ChatInput.svelte +42 -1
  12. package/dist/components/ChatInput.svelte.d.ts +2 -0
  13. package/dist/components/ChatMessages.svelte +322 -98
  14. package/dist/components/ChatMessages.svelte.d.ts +11 -2
  15. package/dist/components/ComposerAttachmentsTray.svelte +144 -56
  16. package/dist/components/ComposerAttachmentsTray.svelte.d.ts +11 -1
  17. package/dist/components/FileGlyphIcon.svelte +34 -0
  18. package/dist/components/FileGlyphIcon.svelte.d.ts +8 -0
  19. package/dist/components/RestoreCheckpointDialog.svelte +66 -0
  20. package/dist/components/RestoreCheckpointDialog.svelte.d.ts +11 -0
  21. package/dist/components/SentAttachments.svelte +118 -0
  22. package/dist/components/SentAttachments.svelte.d.ts +12 -0
  23. package/dist/components/agent/AgentTurn.svelte +17 -2
  24. package/dist/components/agent/CodeCard.svelte +9 -3
  25. package/dist/i18n/messages.d.ts +45 -3
  26. package/dist/i18n/messages.js +51 -5
  27. package/dist/services/index.d.ts +4 -2
  28. package/dist/services/index.js +2 -1
  29. package/dist/services/limitRefusal.d.ts +42 -0
  30. package/dist/services/limitRefusal.js +60 -0
  31. package/dist/services/sketchAssistantClient.d.ts +11 -3
  32. package/dist/services/sketchAssistantClient.js +37 -10
  33. package/dist/services/sketchAssistantErrors.d.ts +16 -1
  34. package/dist/services/sketchAssistantErrors.js +25 -4
  35. package/dist/services/sketchAssistantOrchestrator.d.ts +7 -1
  36. package/dist/services/sketchAssistantOrchestrator.js +2 -2
  37. package/dist/types/attachment.d.ts +11 -0
  38. package/dist/utils/agentTurn.d.ts +32 -1
  39. package/dist/utils/agentTurn.js +46 -3
  40. package/dist/utils/attachmentDuplicates.d.ts +48 -0
  41. package/dist/utils/attachmentDuplicates.js +70 -0
  42. package/dist/utils/attachmentPolicy.d.ts +88 -0
  43. package/dist/utils/attachmentPolicy.js +135 -0
  44. package/dist/utils/attachmentPreview.d.ts +146 -0
  45. package/dist/utils/attachmentPreview.js +224 -0
  46. package/dist/utils/attachmentTray.d.ts +35 -0
  47. package/dist/utils/attachmentTray.js +27 -0
  48. package/dist/utils/chatFileDrag.d.ts +39 -0
  49. package/dist/utils/chatFileDrag.js +29 -0
  50. package/dist/utils/composerPreview.d.ts +33 -0
  51. package/dist/utils/composerPreview.js +31 -0
  52. package/dist/utils/generationArchiveStore.d.ts +5 -1
  53. package/dist/utils/generationArchiveStore.js +9 -4
  54. package/dist/utils/index.d.ts +1 -1
  55. package/dist/utils/index.js +1 -1
  56. package/dist/utils/limitFailureLine.d.ts +20 -0
  57. package/dist/utils/limitFailureLine.js +40 -0
  58. package/dist/utils/panelListPadding.d.ts +20 -0
  59. package/dist/utils/panelListPadding.js +31 -0
  60. package/dist/utils/pasteInsertion.d.ts +43 -0
  61. package/dist/utils/pasteInsertion.js +94 -0
  62. package/dist/utils/pastedContent.d.ts +13 -0
  63. package/dist/utils/pastedContent.js +18 -1
  64. package/dist/utils/referenceItems.js +11 -3
  65. package/dist/utils/sentAttachments.d.ts +43 -0
  66. package/dist/utils/sentAttachments.js +38 -0
  67. package/dist/utils/sentReferenceBadges.d.ts +11 -1
  68. package/dist/utils/sentReferenceBadges.js +47 -2
  69. package/package.json +3 -3
@@ -0,0 +1,428 @@
1
+ <script lang="ts">
2
+ /**
3
+ * The preview of an attached file: a card over the chat with the look and the motion of the File Browser's preview. On top it has
4
+ * the name and the details of the file, the arrows to the file before and after it (when the message or the message box holds
5
+ * more than one) and the close button; below it, the file itself: a picture at its own size, a video that plays, a PDF with its
6
+ * pages, or a text. It opens from a thumbnail or a file chip, in the message box and in a sent message.
7
+ *
8
+ * The card is the design system's `BaseModal`, the one every other dialog uses, so it fades and slides in and out the same way,
9
+ * keeps the focus inside while it is open, and closes with Escape or a click on the dark layer. The page mounts this component
10
+ * while a file is open and unmounts it from `onClose`, which runs after the card has faded out. What does not need a screen (the
11
+ * kind of preview a file gets, the size of the card, what an arrow key does) is in `utils/attachmentPreview.ts`.
12
+ */
13
+ import { onDestroy, untrack } from 'svelte';
14
+ import { BaseModal, EmptyState, IconButton, PDFViewer, WScrollArea } from '@widgetic/design-system/components';
15
+ import { dirForUserText, useTextDirection } from '@widgetic/design-system/components/textDirection';
16
+ import IconAlertTriangle from '@tabler/icons-svelte/icons/alert-triangle';
17
+ import IconChevronLeft from '@tabler/icons-svelte/icons/chevron-left';
18
+ import IconChevronRight from '@tabler/icons-svelte/icons/chevron-right';
19
+ import IconFileUnknown from '@tabler/icons-svelte/icons/file-unknown';
20
+ import IconLoader2 from '@tabler/icons-svelte/icons/loader-2';
21
+ import IconX from '@tabler/icons-svelte/icons/x';
22
+ import { useChatLanguage } from '../i18n/language.js';
23
+ import { fileSizeText } from '../i18n/labels.js';
24
+ import { chatLog, chatWarn } from '../utils/logger.js';
25
+ import {
26
+ computeDocumentFrame,
27
+ computePictureFrame,
28
+ formatPreviewText,
29
+ previewDetailParts,
30
+ previewKeyAction,
31
+ previewKindOf,
32
+ steppedPreviewIndex,
33
+ type PreviewableFile,
34
+ type PreviewFrame,
35
+ type PreviewText
36
+ } from '../utils/attachmentPreview.js';
37
+
38
+ interface Props {
39
+ /** The files the card steps through (the files of one message, or of the message box), in the order they are drawn. */
40
+ files: readonly PreviewableFile[];
41
+ /** The place in `files` of the file that is open. */
42
+ openIndex: number;
43
+ /** The card was closed and has faded out: the page forgets which file was open. */
44
+ onClose: () => void;
45
+ /** An arrow (or an arrow key) moved to another file: the page keeps that place as the open one. */
46
+ onNavigate: (index: number) => void;
47
+ }
48
+
49
+ let { files, openIndex, onClose, onNavigate }: Props = $props();
50
+
51
+ const { t, locale } = useChatLanguage();
52
+ // The way the screen is read: the arrow keys follow it, and a file name reads by its own first letter
53
+ const textDirection = useTextDirection();
54
+
55
+ /** How long the card takes to fade out (the design system's overlay motion): the page is told it closed after that. */
56
+ const CLOSE_ANIMATION_MS = 200;
57
+ /** How long a picture may take before the card shows that it is loading (a picture that is warm opens with no spinner at all). */
58
+ const SLOW_PICTURE_DELAY_MS = 400;
59
+ /** How long the text of a file may take to come before the card gives up on it. */
60
+ const TEXT_FETCH_TIME_LIMIT_MS = 10000;
61
+
62
+ /** What is known about the file that is open; it names that file, so a late answer for the file just left is never taken for this one. */
63
+ interface FileState {
64
+ url: string;
65
+ status: 'loading' | 'ready' | 'failed';
66
+ /** The size in px of the picture or the video, once the file said it. */
67
+ naturalSize: { width: number; height: number } | null;
68
+ durationSeconds: number | null;
69
+ text: PreviewText | null;
70
+ }
71
+
72
+ let isOpen = $state(true);
73
+ let closeRequested = false;
74
+ let closeTimer: ReturnType<typeof setTimeout> | undefined;
75
+ let fileState = $state<FileState>({ url: '', status: 'loading', naturalSize: null, durationSeconds: null, text: null });
76
+ let slowPictureWaitElapsed = $state(false);
77
+ let videoElement = $state<HTMLVideoElement | undefined>(undefined);
78
+ // The size of the window the card has to fit in (it follows when the window is resized)
79
+ let windowWidth = $state(0);
80
+ let windowHeight = $state(0);
81
+
82
+ const currentFile = $derived<PreviewableFile | null>(files[openIndex] ?? null);
83
+ const currentUrl = $derived(currentFile?.url ?? '');
84
+ const currentKind = $derived(
85
+ currentFile ? previewKindOf({ url: currentFile.url, name: currentFile.name, type: currentFile.type }) : null
86
+ );
87
+ const title = $derived(currentFile?.name || $t('chat.attachment.untitled'));
88
+
89
+ // What is known about the file that is open now (a state that is for another file counts as nothing known yet)
90
+ const stateOfCurrentFile = $derived<FileState>(
91
+ fileState.url === currentUrl
92
+ ? fileState
93
+ : { url: currentUrl, status: 'loading', naturalSize: null, durationSeconds: null, text: null }
94
+ );
95
+ const hasFailed = $derived(currentKind === null || stateOfCurrentFile.status === 'failed');
96
+ // A picture shows the loading card only when it is slow, so a picture that arrives at once does not flash one
97
+ const showsPictureLoader = $derived(
98
+ currentKind === 'image' && stateOfCurrentFile.status === 'loading' && slowPictureWaitElapsed
99
+ );
100
+
101
+ /** The size of the card and of the file in it; null while the card has no size to show (a picture whose size is not known yet). */
102
+ const frame = $derived.by<PreviewFrame | { width: number; height: number } | null>(() => {
103
+ const host = { width: windowWidth, height: windowHeight };
104
+ if (hasFailed) return computeDocumentFrame('error', host);
105
+ const known = stateOfCurrentFile.naturalSize;
106
+ switch (currentKind) {
107
+ case 'image':
108
+ if (known) return computePictureFrame(known.width, known.height, host);
109
+ return showsPictureLoader ? computeDocumentFrame('loading', host) : null;
110
+ case 'video':
111
+ // The card is a 16:9 one until the video tells how wide and tall it is, then it eases to the video
112
+ return computePictureFrame(known?.width ?? 1280, known?.height ?? 720, host);
113
+ case 'pdf':
114
+ return computeDocumentFrame('pdf', host);
115
+ case 'text':
116
+ return computeDocumentFrame('text', host);
117
+ default:
118
+ return computeDocumentFrame('error', host);
119
+ }
120
+ });
121
+ const pictureFrame = $derived(frame && 'pictureWidth' in frame ? frame : null);
122
+
123
+ // The card eases from a size to another (the loading card to the picture, a video to its own size); a picture that is shown
124
+ // for the first time opens at its size, with no move.
125
+ const easesItsSize = $derived(currentKind === 'video' || (currentKind === 'image' && slowPictureWaitElapsed));
126
+
127
+ const detailsLine = $derived(
128
+ currentFile && !hasFailed && (currentKind !== 'image' || stateOfCurrentFile.status === 'ready')
129
+ ? previewDetailParts(
130
+ {
131
+ name: currentFile.name,
132
+ kind: currentKind,
133
+ size: currentFile.size,
134
+ dimensions: stateOfCurrentFile.naturalSize,
135
+ durationSeconds: stateOfCurrentFile.durationSeconds
136
+ },
137
+ (bytes) => fileSizeText(bytes, $t, $locale)
138
+ ).join(' · ')
139
+ : ''
140
+ );
141
+
142
+ const previousIndex = $derived(steppedPreviewIndex(openIndex, 'previous', files.length));
143
+ const nextIndex = $derived(steppedPreviewIndex(openIndex, 'next', files.length));
144
+ const hasNeighbours = $derived(files.length > 1);
145
+
146
+ /** Every picture of the group has been asked for once, so the arrow to the next one opens it at once. */
147
+ const warmedPictureUrls = new Set<string>();
148
+
149
+ /** Asks the browser for the pictures next to the open one, so stepping to them shows no wait. */
150
+ function warmNeighbouringPictures(): void {
151
+ try {
152
+ for (const neighbourIndex of [previousIndex, nextIndex]) {
153
+ if (neighbourIndex === null) continue;
154
+ const neighbour = files[neighbourIndex];
155
+ if (!neighbour || warmedPictureUrls.has(neighbour.url)) continue;
156
+ if (previewKindOf({ url: neighbour.url, name: neighbour.name, type: neighbour.type }) !== 'image') continue;
157
+ warmedPictureUrls.add(neighbour.url);
158
+ const warmer = new Image();
159
+ warmer.decoding = 'async';
160
+ warmer.src = neighbour.url;
161
+ }
162
+ } catch (error) {
163
+ chatWarn('[AttachmentPreview] The pictures next to the open one could not be warmed:', error);
164
+ }
165
+ }
166
+
167
+ // A file that is opened (or stepped to) starts its own state, and loads what its kind needs: a picture is measured (the card
168
+ // takes its size), a text is read. A video and a PDF load inside their own player. The cleanup makes a file that was left
169
+ // before it finished load nothing into the card of the file that is open now.
170
+ $effect(() => {
171
+ const url = currentUrl;
172
+ const kind = currentKind;
173
+ if (url === '') return;
174
+ const file = untrack(() => currentFile);
175
+
176
+ fileState = { url, status: kind === 'image' || kind === 'text' ? 'loading' : 'ready', naturalSize: null, durationSeconds: null, text: null };
177
+ slowPictureWaitElapsed = false;
178
+ chatLog('[AttachmentPreview] A file was opened:', file?.name, kind);
179
+
180
+ let leftThisFile = false;
181
+ const cleanups: Array<() => void> = [];
182
+
183
+ if (kind === 'image') {
184
+ const measuring = new Image();
185
+ measuring.decoding = 'async';
186
+ measuring.onload = () => {
187
+ if (leftThisFile) return;
188
+ fileState = { ...fileState, url, status: 'ready', naturalSize: { width: measuring.naturalWidth, height: measuring.naturalHeight } };
189
+ warmNeighbouringPictures();
190
+ };
191
+ measuring.onerror = () => {
192
+ if (leftThisFile) return;
193
+ chatWarn('[AttachmentPreview] The picture could not be loaded:', file?.name);
194
+ fileState = { ...fileState, url, status: 'failed' };
195
+ };
196
+ measuring.src = url;
197
+ const slowTimer = setTimeout(() => {
198
+ if (!leftThisFile) slowPictureWaitElapsed = true;
199
+ }, SLOW_PICTURE_DELAY_MS);
200
+ cleanups.push(() => {
201
+ measuring.onload = null;
202
+ measuring.onerror = null;
203
+ clearTimeout(slowTimer);
204
+ });
205
+ } else if (kind === 'text') {
206
+ const controller = new AbortController();
207
+ const timeLimit = setTimeout(() => controller.abort(), TEXT_FETCH_TIME_LIMIT_MS);
208
+ void (async () => {
209
+ try {
210
+ const response = await fetch(url, { signal: controller.signal });
211
+ if (!response.ok) throw new Error(`The file answered with ${response.status}.`);
212
+ const rawText = await response.text();
213
+ if (leftThisFile) return;
214
+ fileState = { ...fileState, url, status: 'ready', text: formatPreviewText(rawText, file?.name) };
215
+ } catch (error) {
216
+ if (leftThisFile) return;
217
+ chatWarn('[AttachmentPreview] The text of the file could not be read:', file?.name, error);
218
+ fileState = { ...fileState, url, status: 'failed' };
219
+ } finally {
220
+ clearTimeout(timeLimit);
221
+ }
222
+ })();
223
+ cleanups.push(() => {
224
+ controller.abort();
225
+ clearTimeout(timeLimit);
226
+ });
227
+ } else {
228
+ // (Untracked: the effect must start over for another file only, not whenever the list of files is rebuilt)
229
+ untrack(() => warmNeighbouringPictures());
230
+ }
231
+
232
+ return () => {
233
+ leftThisFile = true;
234
+ for (const cleanup of cleanups) cleanup();
235
+ };
236
+ });
237
+
238
+ onDestroy(() => {
239
+ if (closeTimer) clearTimeout(closeTimer);
240
+ });
241
+
242
+ /** Closes the card: it fades out first, and the page is told after that (the same two steps the File Browser's preview takes). */
243
+ function handleClose(): void {
244
+ if (closeRequested) return;
245
+ closeRequested = true;
246
+ try {
247
+ // A video that was playing stops with its card
248
+ videoElement?.pause();
249
+ } catch (error) {
250
+ chatWarn('[AttachmentPreview] The video could not be paused:', error);
251
+ }
252
+ isOpen = false;
253
+ chatLog('[AttachmentPreview] The preview was closed.');
254
+ closeTimer = setTimeout(() => {
255
+ closeTimer = undefined;
256
+ onClose();
257
+ }, CLOSE_ANIMATION_MS);
258
+ }
259
+
260
+ /** Moves to the file at a place of the group (an arrow button or an arrow key). */
261
+ function goToIndex(targetIndex: number | null): void {
262
+ if (targetIndex === null || closeRequested) return;
263
+ chatLog('[AttachmentPreview] Moving to the file at place:', targetIndex);
264
+ onNavigate(targetIndex);
265
+ }
266
+
267
+ /** Whether a key was pressed in a field a person types in (the arrows move the caret there, not the card). */
268
+ function isTypingTarget(target: EventTarget | null): boolean {
269
+ if (!(target instanceof HTMLElement)) return false;
270
+ const tagName = target.tagName;
271
+ return tagName === 'INPUT' || tagName === 'TEXTAREA' || tagName === 'SELECT' || target.isContentEditable;
272
+ }
273
+
274
+ function handleKeydown(event: KeyboardEvent): void {
275
+ if (!isOpen || !hasNeighbours || isTypingTarget(event.target)) return;
276
+ // The arrow keys follow the reading direction: the left arrow is "previous" in English and "next" in Arabic
277
+ const action = previewKeyAction(event.key, $textDirection);
278
+ if (action === null) return;
279
+ event.preventDefault();
280
+ goToIndex(action === 'previous' ? previousIndex : nextIndex);
281
+ }
282
+
283
+ /** The video told how wide and tall it is (and how long): the card eases to its size. */
284
+ function handleVideoMetadata(event: Event): void {
285
+ const video = event.currentTarget as HTMLVideoElement;
286
+ if (fileState.url !== currentUrl || !video.videoWidth || !video.videoHeight) return;
287
+ fileState = {
288
+ ...fileState,
289
+ naturalSize: { width: video.videoWidth, height: video.videoHeight },
290
+ durationSeconds: Number.isFinite(video.duration) ? video.duration : null
291
+ };
292
+ }
293
+
294
+ /** The file could not be played or shown: the card says so. */
295
+ function handleFileFailed(reason: string): void {
296
+ chatWarn('[AttachmentPreview] The file could not be shown:', currentFile?.name, reason);
297
+ if (fileState.url === currentUrl) fileState = { ...fileState, status: 'failed' };
298
+ }
299
+
300
+ /** The PDF viewer says why it failed in an event; the card only needs that it did. */
301
+ function handlePdfError(event: CustomEvent<{ message?: string }>): void {
302
+ handleFileFailed(event.detail?.message ?? 'The PDF could not be loaded.');
303
+ }
304
+ </script>
305
+
306
+ <svelte:window bind:innerWidth={windowWidth} bind:innerHeight={windowHeight} onkeydown={handleKeydown} />
307
+
308
+ <!-- A bare modal: the card draws its own top row (the name and details, the arrows, the close button) and its own padding. A picture
309
+ stays hidden until its size is known, so the card never opens large and then shrinks. -->
310
+ <BaseModal
311
+ bind:open={isOpen}
312
+ bare
313
+ ariaLabel={title}
314
+ width="{frame?.width ?? 410}px"
315
+ height="{frame?.height ?? 256}px"
316
+ animateSize={easesItsSize}
317
+ shown={frame !== null}
318
+ showScroll={false}
319
+ target="chat-attachment-preview-modal"
320
+ modalType="chatAttachmentPreview"
321
+ on:close={handleClose}
322
+ >
323
+ <div class="chat-attachment-preview flex w-full flex-col p-6" data-testid="chat-attachment-preview">
324
+ <!-- The top row: the same one the File Browser's preview has -->
325
+ <div class="chat-attachment-preview-header mb-4 flex items-center gap-2">
326
+ <div class="flex min-w-0 flex-1 flex-col gap-0 text-start">
327
+ <p class="text-heading-section text-foreground truncate" dir={dirForUserText($textDirection)} {title} data-testid="chat-attachment-preview-title">{title}</p>
328
+ {#if detailsLine}
329
+ <p class="text-caption text-muted-foreground truncate" title={detailsLine} data-testid="chat-attachment-preview-details">{detailsLine}</p>
330
+ {/if}
331
+ </div>
332
+ {#if hasNeighbours}
333
+ <div class="flex shrink-0 items-center gap-1">
334
+ <IconButton variant="ghost" label={$t('chat.preview.previous')} disabled={previousIndex === null} onclick={() => goToIndex(previousIndex)}>
335
+ <IconChevronLeft class="size-4 stroke-2 rtl:rotate-180" />
336
+ </IconButton>
337
+ <IconButton variant="ghost" label={$t('chat.preview.next')} disabled={nextIndex === null} onclick={() => goToIndex(nextIndex)}>
338
+ <IconChevronRight class="size-4 stroke-2 rtl:rotate-180" />
339
+ </IconButton>
340
+ </div>
341
+ {/if}
342
+ <IconButton variant="ghost" label={$t('chat.attachment.close')} onclick={handleClose}>
343
+ <IconX class="size-4 stroke-2" />
344
+ </IconButton>
345
+ </div>
346
+
347
+ {#if currentFile}
348
+ {#if currentKind === null}
349
+ <!-- A file with no preview (the page opens only files that have one, so this is a safety net) -->
350
+ <div class="flex h-[12.5rem] w-full items-center justify-center" data-testid="chat-attachment-preview-unavailable">
351
+ <EmptyState message={$t('chat.preview.unavailable')} showActions={false} icon={IconFileUnknown} height="auto" />
352
+ </div>
353
+ {:else if hasFailed}
354
+ <div class="flex h-40 w-full items-center justify-center" data-testid="chat-attachment-preview-error">
355
+ <EmptyState message={$t('chat.preview.failed')} showActions={false} icon={IconAlertTriangle} height="auto" />
356
+ </div>
357
+ {:else if currentKind === 'image'}
358
+ {#if pictureFrame && stateOfCurrentFile.status === 'ready'}
359
+ <div class="relative flex w-full shrink-0 justify-center" data-testid="chat-attachment-preview-picture">
360
+ {#key currentUrl}
361
+ <img
362
+ src={currentFile.url}
363
+ alt={currentFile.name}
364
+ class="bg-muted rounded-xl object-contain"
365
+ style="width: {pictureFrame.pictureWidth}px; height: {pictureFrame.pictureHeight}px"
366
+ draggable="false"
367
+ onerror={() => handleFileFailed('The picture could not be drawn.')}
368
+ />
369
+ {/key}
370
+ </div>
371
+ {:else if showsPictureLoader}
372
+ <div class="flex h-[9.75rem] w-full flex-col items-center justify-center" role="status" aria-label={$t('chat.preview.loading')}>
373
+ <IconLoader2 class="text-primary size-8 animate-spin stroke-[1.333] motion-reduce:animate-none" />
374
+ <span class="sr-only">{$t('chat.preview.loading')}</span>
375
+ </div>
376
+ {/if}
377
+ {:else if currentKind === 'video'}
378
+ <div class="relative flex w-full shrink-0 justify-center" data-testid="chat-attachment-preview-video">
379
+ {#key currentUrl}
380
+ <!-- svelte-ignore a11y_media_has_caption -->
381
+ <video
382
+ bind:this={videoElement}
383
+ src={currentFile.url}
384
+ class="bg-muted rounded-xl object-contain"
385
+ style="width: {pictureFrame?.pictureWidth ?? 0}px; height: {pictureFrame?.pictureHeight ?? 0}px"
386
+ controls
387
+ autoplay
388
+ playsinline
389
+ preload="metadata"
390
+ onloadedmetadata={handleVideoMetadata}
391
+ onerror={() => handleFileFailed('The video could not be played.')}
392
+ ></video>
393
+ {/key}
394
+ </div>
395
+ {:else if currentKind === 'pdf'}
396
+ {#key currentUrl}
397
+ <PDFViewer
398
+ class="chat-attachment-preview-pdf bg-muted w-full rounded-lg"
399
+ url={currentFile.url}
400
+ enableCacheClearing={false}
401
+ loadingLabel={$t('chat.preview.pdfLoading')}
402
+ failedLabel={$t('chat.preview.pdfFailed')}
403
+ pageLabel={$t('chat.preview.pdfPage', { page: '{page}', total: '{total}' })}
404
+ previousPageLabel={$t('chat.preview.pdfPreviousPage')}
405
+ nextPageLabel={$t('chat.preview.pdfNextPage')}
406
+ on:error={handlePdfError}
407
+ />
408
+ {/key}
409
+ {:else if currentKind === 'text'}
410
+ {#if stateOfCurrentFile.status === 'ready' && stateOfCurrentFile.text}
411
+ <div class="w-full" data-testid="chat-attachment-preview-text">
412
+ <WScrollArea class="h-[22.5rem] w-full" viewPortClass="rounded-lg bg-muted" scrollOutside={true} type="always">
413
+ <pre class="text-code text-foreground m-0 w-full whitespace-pre-wrap break-words p-4" dir="auto">{stateOfCurrentFile.text.text}</pre>
414
+ </WScrollArea>
415
+ {#if stateOfCurrentFile.text.truncated}
416
+ <p class="text-caption text-muted-foreground mt-2 text-start">{$t('chat.preview.truncated')}</p>
417
+ {/if}
418
+ </div>
419
+ {:else}
420
+ <div class="text-caption text-muted-foreground flex min-h-[16rem] w-full items-center justify-center gap-3" role="status">
421
+ <IconLoader2 class="size-5 animate-spin stroke-[1.6] motion-reduce:animate-none" />
422
+ {$t('chat.preview.loading')}
423
+ </div>
424
+ {/if}
425
+ {/if}
426
+ {/if}
427
+ </div>
428
+ </BaseModal>
@@ -0,0 +1,14 @@
1
+ import { type PreviewableFile } from '../utils/attachmentPreview.js';
2
+ interface Props {
3
+ /** The files the card steps through (the files of one message, or of the message box), in the order they are drawn. */
4
+ files: readonly PreviewableFile[];
5
+ /** The place in `files` of the file that is open. */
6
+ openIndex: number;
7
+ /** The card was closed and has faded out: the page forgets which file was open. */
8
+ onClose: () => void;
9
+ /** An arrow (or an arrow key) moved to another file: the page keeps that place as the open one. */
10
+ onNavigate: (index: number) => void;
11
+ }
12
+ declare const AttachmentPreviewDialog: import("svelte").Component<Props, {}, "">;
13
+ type AttachmentPreviewDialog = ReturnType<typeof AttachmentPreviewDialog>;
14
+ export default AttachmentPreviewDialog;