@swisper.ai/web-file-preview 0.0.2 → 0.0.4

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 (41) hide show
  1. package/dist/components/file-preview/components/renderer-types.d.ts +4 -1
  2. package/dist/components/file-preview/components/renderer-types.d.ts.map +1 -1
  3. package/dist/components/file-preview/components/viewer/viewer-components.stories.d.ts.map +1 -1
  4. package/dist/components/file-preview/file-preview.d.ts.map +1 -1
  5. package/dist/components/file-preview/file-preview.stories.d.ts +49 -2
  6. package/dist/components/file-preview/file-preview.stories.d.ts.map +1 -1
  7. package/dist/components/file-thumbnail/components/previews/html-preview.d.ts.map +1 -1
  8. package/dist/components/file-thumbnail/components/previews/image-preview.d.ts.map +1 -1
  9. package/dist/components/file-thumbnail/components/previews/markdown-preview.d.ts.map +1 -1
  10. package/dist/components/file-thumbnail/components/previews/reveal-class-name.d.ts +4 -2
  11. package/dist/components/file-thumbnail/components/previews/reveal-class-name.d.ts.map +1 -1
  12. package/dist/components/file-thumbnail/components/previews/scaled-page.d.ts +4 -1
  13. package/dist/components/file-thumbnail/components/previews/scaled-page.d.ts.map +1 -1
  14. package/dist/components/file-thumbnail/file-thumbnail.d.ts +2 -0
  15. package/dist/components/file-thumbnail/file-thumbnail.d.ts.map +1 -1
  16. package/dist/components/file-thumbnail/file-thumbnail.stories.d.ts +76 -10
  17. package/dist/components/file-thumbnail/file-thumbnail.stories.d.ts.map +1 -1
  18. package/dist/index.css +1 -1
  19. package/dist/index.es.js +50 -33
  20. package/dist/index.es.js.map +1 -1
  21. package/package.json +14 -6
  22. package/src/__storybook__/parent-block.tsx +21 -0
  23. package/src/components/file-preview/__stories__/fixtures.ts +66 -0
  24. package/src/components/file-preview/components/renderer-types.ts +4 -1
  25. package/src/components/file-preview/components/viewer/viewer-components.stories.tsx +2 -8
  26. package/src/components/file-preview/file-preview.json +15 -0
  27. package/src/components/file-preview/file-preview.stories.tsx +378 -38
  28. package/src/components/file-preview/file-preview.tsx +7 -2
  29. package/src/components/file-thumbnail/__stories__/fixtures.ts +99 -0
  30. package/src/components/file-thumbnail/__stories__/types.ts +26 -0
  31. package/src/components/file-thumbnail/components/previews/html-preview.tsx +5 -1
  32. package/src/components/file-thumbnail/components/previews/image-preview.tsx +3 -1
  33. package/src/components/file-thumbnail/components/previews/markdown-preview.tsx +5 -1
  34. package/src/components/file-thumbnail/components/previews/reveal-class-name.ts +8 -8
  35. package/src/components/file-thumbnail/components/previews/scaled-page.tsx +6 -1
  36. package/src/components/file-thumbnail/file-thumbnail.json +17 -1
  37. package/src/components/file-thumbnail/file-thumbnail.stories.tsx +551 -84
  38. package/src/components/file-thumbnail/file-thumbnail.tsx +24 -7
  39. /package/src/components/file-thumbnail/components/shared/__tests__/{generation-queue.spec.ts → generation-queue.test.ts} +0 -0
  40. /package/src/components/file-thumbnail/hooks/__tests__/{use-object-url.spec.ts → use-object-url.test.ts} +0 -0
  41. /package/src/lib/__tests__/{file-kinds.spec.ts → file-kinds.test.ts} +0 -0
@@ -1,7 +1,28 @@
1
1
  import type { Meta, StoryObj } from '@storybook/react-vite';
2
- import { useEffect, useState } from 'react';
3
- import { fn } from 'storybook/test';
2
+ import { useState } from 'react';
3
+ import { expect, fn, waitFor } from 'storybook/test';
4
4
 
5
+ import { Typography } from '@swisper.ai/ui';
6
+
7
+ import { ParentBlock } from '../../__storybook__/parent-block';
8
+
9
+ import {
10
+ ATTACHED_FILES,
11
+ CSV_URL,
12
+ GALLERY_DOCUMENTS,
13
+ HTML_URL,
14
+ LIBRARY_DOCUMENTS,
15
+ MARKDOWN_URL,
16
+ PAGE_IMAGE_URL,
17
+ PDF_URL,
18
+ PRESENTATION_URL,
19
+ QUEUED_UPLOADS,
20
+ SCROLLING_FILES,
21
+ SCROLLING_IMAGES,
22
+ SPREADSHEET_URL,
23
+ WORD_URL,
24
+ } from './__stories__/fixtures';
25
+ import type { ThumbnailFile } from './__stories__/types';
5
26
  import {
6
27
  FileThumbnail,
7
28
  FileThumbnailFallback,
@@ -10,18 +31,22 @@ import {
10
31
  type FileThumbnailProps,
11
32
  } from './file-thumbnail';
12
33
 
13
- // Vite serves these same-origin, so the kinds that are fetched need no CORS.
14
- const fixture = (name: string) => new URL(`../../__fixtures__/${name}`, import.meta.url).href;
34
+ // The thumbnail fills its parent, so every story gives it a sized one: 124 x 164px.
35
+ const tileClassName = 'h-41 w-31';
15
36
 
16
- const PAGE_IMAGE_URL = fixture('quarterly-report-page-1.png');
17
- const PDF_URL = fixture('quarterly-report.pdf');
18
- const WORD_URL = fixture('quarterly-report.docx');
19
- const SPREADSHEET_URL = fixture('quarterly-model.xlsx');
20
- const PRESENTATION_URL = fixture('quarterly-deck.pptx');
21
- const MARKDOWN_URL = fixture('quarterly-report.md');
22
- const HTML_URL = fixture('quarterly-report.html');
23
- const CSV_URL = fixture('quarterly-regions.csv');
37
+ function renderThumbnail(args: FileThumbnailProps) {
38
+ return (
39
+ <div className={tileClassName}>
40
+ <FileThumbnail {...args}>
41
+ <FileThumbnailLoader />
42
+ <FileThumbnailPreview />
43
+ <FileThumbnailFallback />
44
+ </FileThumbnail>
45
+ </div>
46
+ );
47
+ }
24
48
 
49
+ /** The three parts in their default form, for the stories that render many tiles. */
25
50
  function Thumbnail(props: Omit<FileThumbnailProps, 'children'>) {
26
51
  return (
27
52
  <FileThumbnail {...(props as FileThumbnailProps)}>
@@ -32,23 +57,31 @@ function Thumbnail(props: Omit<FileThumbnailProps, 'children'>) {
32
57
  );
33
58
  }
34
59
 
35
- const meta: Meta<typeof Thumbnail> = {
60
+ function delay(ms: number) {
61
+ return new Promise<void>((resolve) => setTimeout(resolve, ms));
62
+ }
63
+
64
+ const meta: Meta<typeof FileThumbnail> = {
36
65
  title: 'Files/FileThumbnail',
37
- component: Thumbnail,
66
+ component: FileThumbnail,
67
+ subcomponents: { FileThumbnailLoader, FileThumbnailPreview, FileThumbnailFallback },
38
68
  tags: ['autodocs'],
39
- decorators: [
40
- (Story) => (
41
- <div className="h-[160px] w-[124px]">
42
- <Story />
43
- </div>
44
- ),
45
- ],
46
69
  argTypes: {
47
70
  fileName: {
48
71
  control: 'text',
49
72
  description:
50
73
  'The original file name. Its extension picks how the file is drawn, and labels the fallback.',
51
74
  },
75
+ src: {
76
+ control: 'text',
77
+ description:
78
+ 'URL of the file. Images and HTML pages load from it directly; every other kind is fetched, so it must be same-origin or allow this origin through CORS. Pass either `src` or `fileBlob`, never both.',
79
+ },
80
+ fileBlob: {
81
+ control: false,
82
+ description:
83
+ 'The file already in memory, drawn without a request. `null` while your app is still getting it: the loader shows until it arrives. Pass either `src` or `fileBlob`, never both.',
84
+ },
52
85
  previewImageUrl: {
53
86
  control: 'text',
54
87
  description:
@@ -58,59 +91,92 @@ const meta: Meta<typeof Thumbnail> = {
58
91
  control: 'boolean',
59
92
  description:
60
93
  'Shows the loader, and holds off drawing the file, while your own pipeline produces `previewImageUrl`.',
94
+ table: { defaultValue: { summary: 'false' } },
61
95
  },
62
96
  className: {
63
97
  control: 'text',
64
- description: 'Additional CSS classes to apply',
98
+ description: 'Extra classes merged onto the root.',
99
+ },
100
+ children: {
101
+ control: false,
102
+ description:
103
+ 'The parts: `FileThumbnailLoader`, `FileThumbnailPreview` and `FileThumbnailFallback`. Each renders only in its state.',
104
+ },
105
+ onLoadAvailable: {
106
+ description:
107
+ 'Called the first time the tile is on screen: the moment to start getting a file passed as `fileBlob={null}`.',
108
+ },
109
+ onLoadStarted: {
110
+ description: 'Called when the tile starts drawing the file.',
111
+ },
112
+ onLoaded: {
113
+ description: 'Called once the picture has drawn and the tile shows it.',
114
+ },
115
+ onLoadFailed: {
116
+ description: 'Called with the `Error` whenever the fallback takes over.',
65
117
  },
66
118
  },
119
+ // `src`/`fileBlob` stay out of meta args: each story passes exactly one of them.
67
120
  args: {
68
- src: PAGE_IMAGE_URL,
69
- fileName: 'quarterly-report-page-1.png',
70
121
  onLoadAvailable: fn(),
71
122
  onLoadStarted: fn(),
72
123
  onLoaded: fn(),
73
124
  onLoadFailed: fn(),
74
125
  },
126
+ render: renderThumbnail,
75
127
  };
76
128
 
77
129
  export default meta;
78
- type Story = StoryObj<typeof Thumbnail>;
130
+ type Story = StoryObj<typeof FileThumbnail>;
79
131
 
80
- export const Image: Story = {};
132
+ /** The thumbnail of an image file, loaded from `src`. */
133
+ export const Default: Story = {
134
+ args: { src: PAGE_IMAGE_URL, fileName: 'quarterly-report-page-1.png' },
135
+ };
136
+
137
+ /** An image draws as itself, cropped to cover the tile from its centre. */
138
+ export const Image: Story = {
139
+ args: { src: PAGE_IMAGE_URL, fileName: 'quarterly-report-page-1.png' },
140
+ };
81
141
 
142
+ /** A PDF shows its first page, cropped from the top. */
82
143
  export const Pdf: Story = {
83
144
  name: 'PDF',
84
145
  args: { src: PDF_URL, fileName: 'quarterly-report.pdf' },
85
146
  };
86
147
 
148
+ /** A Word document shows its first page. */
87
149
  export const Word: Story = {
88
150
  args: { src: WORD_URL, fileName: 'quarterly-report.docx' },
89
151
  };
90
152
 
153
+ /** A workbook shows its first sheet, whole, from the top-left corner. */
91
154
  export const Spreadsheet: Story = {
92
155
  args: { src: SPREADSHEET_URL, fileName: 'quarterly-model.xlsx' },
93
156
  };
94
157
 
158
+ /** A deck shows its first slide, whole and centred. */
95
159
  export const Presentation: Story = {
96
160
  name: 'PowerPoint',
97
161
  args: { src: PRESENTATION_URL, fileName: 'quarterly-deck.pptx' },
98
162
  };
99
163
 
164
+ /** A Markdown file shows its rendered text, laid out as a page and scaled to the tile. */
100
165
  export const Markdown: Story = {
101
166
  args: { src: MARKDOWN_URL, fileName: 'quarterly-report.md' },
102
167
  };
103
168
 
169
+ /** An HTML page loads by URL in a sandboxed frame, scaled down from a desktop width. */
104
170
  export const Html: Story = {
105
171
  name: 'HTML',
106
172
  args: { src: HTML_URL, fileName: 'quarterly-report.html' },
107
173
  };
108
174
 
175
+ /** An HTML file passed as `fileBlob` draws from its markup, and its script never runs. */
109
176
  export const HtmlFromBlob: Story = {
110
177
  name: 'HTML from fileBlob',
111
178
  // The script must not run: the heading would read "Script ran".
112
179
  args: {
113
- src: undefined,
114
180
  fileBlob: new Blob(
115
181
  [
116
182
  '<h1 id="title" style="font:48px sans-serif">Uploaded page</h1>' +
@@ -122,11 +188,13 @@ export const HtmlFromBlob: Story = {
122
188
  },
123
189
  };
124
190
 
191
+ /** A CSV shows its first rows as a table. */
125
192
  export const Csv: Story = {
126
193
  name: 'CSV',
127
194
  args: { src: CSV_URL, fileName: 'quarterly-regions.csv' },
128
195
  };
129
196
 
197
+ /** A picture your server already rendered is drawn instead of the file, so no engine loads. */
130
198
  export const PreviewImageUrl: Story = {
131
199
  name: 'PDF with previewImageUrl',
132
200
  args: {
@@ -136,39 +204,68 @@ export const PreviewImageUrl: Story = {
136
204
  },
137
205
  };
138
206
 
139
- /** The host still fetching the file: the loader shows, not the fallback, until the blob arrives. */
140
- function BlobArrivesLaterThumbnail(
141
- props: Omit<FileThumbnailProps, 'children' | 'src' | 'fileBlob'>,
142
- ) {
207
+ interface DocumentThumbnailProps {
208
+ fileName: string;
209
+ /** The app's own request for the file, e.g. an authenticated download. */
210
+ onFetchDocument: () => Promise<Blob>;
211
+ onLoaded?: () => void;
212
+ }
213
+
214
+ /** A document the app downloads itself, starting once its tile is on screen. */
215
+ function DocumentThumbnail({ fileName, onFetchDocument, onLoaded }: DocumentThumbnailProps) {
216
+ // `null` is a file still on its way: the loader shows, not the fallback.
143
217
  const [fileBlob, setFileBlob] = useState<Blob | null>(null);
144
218
 
145
- useEffect(() => {
146
- let isCancelled = false;
147
- const timer = setTimeout(() => {
148
- void fetch(PDF_URL)
149
- .then((response) => response.blob())
150
- .then((blob) => {
151
- if (!isCancelled) {
152
- setFileBlob(blob);
153
- }
154
- });
155
- }, 1500);
156
-
157
- return () => {
158
- isCancelled = true;
159
- clearTimeout(timer);
160
- };
161
- }, []);
162
-
163
- return <Thumbnail {...props} fileBlob={fileBlob} />;
219
+ const handleLoadAvailable = () => {
220
+ void onFetchDocument().then(setFileBlob);
221
+ };
222
+
223
+ return (
224
+ <FileThumbnail
225
+ fileName={fileName}
226
+ fileBlob={fileBlob}
227
+ onLoadAvailable={handleLoadAvailable}
228
+ onLoaded={onLoaded}
229
+ >
230
+ <FileThumbnailLoader />
231
+ <FileThumbnailPreview />
232
+ <FileThumbnailFallback />
233
+ </FileThumbnail>
234
+ );
164
235
  }
165
236
 
166
- export const BlobArrivesLater: Story = {
237
+ type DocumentThumbnailStory = StoryObj<typeof DocumentThumbnail>;
238
+
239
+ /** The host still fetching the file: the loader shows, not the fallback, until the blob arrives. */
240
+ export const BlobArrivesLater: DocumentThumbnailStory = {
167
241
  name: 'fileBlob arriving later',
168
- args: { fileName: 'quarterly-report.pdf' },
169
- render: (args) => <BlobArrivesLaterThumbnail {...args} />,
242
+ args: {
243
+ fileName: 'quarterly-report.pdf',
244
+ onFetchDocument: fn(async () => {
245
+ await delay(1500);
246
+
247
+ return (await fetch(PDF_URL)).blob();
248
+ }),
249
+ onLoaded: fn(),
250
+ },
251
+ argTypes: {
252
+ fileName: {
253
+ control: 'text',
254
+ description: 'The document name; its extension picks the drawing.',
255
+ },
256
+ onFetchDocument: {
257
+ description: 'Called once, when the tile is first on screen. Resolves with the file.',
258
+ },
259
+ onLoaded: { description: 'Called once the picture has drawn.' },
260
+ },
261
+ render: (args) => (
262
+ <div className={tileClassName}>
263
+ <DocumentThumbnail {...args} />
264
+ </div>
265
+ ),
170
266
  };
171
267
 
268
+ /** Your own pipeline still producing the picture: `isLoading` keeps the loader up and nothing is drawn. */
172
269
  export const Loading: Story = {
173
270
  args: {
174
271
  src: PDF_URL,
@@ -177,37 +274,47 @@ export const Loading: Story = {
177
274
  },
178
275
  };
179
276
 
277
+ /** An image that fails to load falls back to its file name, truncated in the middle. */
180
278
  export const BrokenImage: Story = {
181
279
  args: { src: '/files/missing-site-photo.jpg', fileName: 'missing-site-photo.jpg' },
182
280
  };
183
281
 
282
+ /** A PDF that cannot be downloaded falls back the same way; the cause goes to `onLoadFailed`. */
184
283
  export const BrokenPdf: Story = {
185
284
  name: 'Unreachable PDF',
186
285
  args: { src: '/files/missing-report.pdf', fileName: 'missing-report.pdf' },
187
286
  };
188
287
 
288
+ /** A video is never drawn: the fallback is the first paint and nothing is fetched. */
189
289
  export const Video: Story = {
190
290
  args: { src: '/files/onboarding-walkthrough.mp4', fileName: 'onboarding-walkthrough.mp4' },
191
291
  };
192
292
 
293
+ /** A type the tile does not know shows the fallback at once. */
193
294
  export const Unsupported: Story = {
194
295
  args: { src: '/files/archive.zip', fileName: 'archive.zip' },
195
296
  };
196
297
 
298
+ /** Your own fallback content in place of the file name, kept short and free of controls. */
197
299
  export const CustomFallback: Story = {
300
+ parameters: { controls: { disable: true } },
198
301
  render: () => (
199
- <FileThumbnail src="/files/archive.zip" fileName="archive.zip">
200
- <FileThumbnailLoader />
201
- <FileThumbnailPreview />
202
- <FileThumbnailFallback className="flex-col gap-4 text-center">
203
- <span className="text-sm font-medium text-text-primary">ZIP</span>
204
- <span className="text-xs text-text-secondary">No preview</span>
205
- </FileThumbnailFallback>
206
- </FileThumbnail>
302
+ <div className={tileClassName}>
303
+ <FileThumbnail src="/files/archive.zip" fileName="archive.zip">
304
+ <FileThumbnailLoader />
305
+ <FileThumbnailPreview />
306
+ <FileThumbnailFallback className="flex-col gap-4 text-center">
307
+ <span className="text-sm font-medium text-text-primary">ZIP</span>
308
+ <span className="text-xs text-text-secondary">No preview</span>
309
+ </FileThumbnailFallback>
310
+ </FileThumbnail>
311
+ </div>
207
312
  ),
208
313
  };
209
314
 
315
+ /** Every kind and state side by side: drawn files, a server-rendered picture, loading, and the fallbacks. */
210
316
  export const Gallery: Story = {
317
+ parameters: { controls: { disable: true } },
211
318
  decorators: [
212
319
  (Story) => (
213
320
  <div className="grid w-[560px] grid-cols-4 gap-8 [&>*]:h-[160px]">
@@ -237,22 +344,41 @@ export const Gallery: Story = {
237
344
  ),
238
345
  };
239
346
 
240
- const DRAWN_FILES = [
241
- { src: PDF_URL, fileName: 'quarterly-report.pdf' },
242
- { src: WORD_URL, fileName: 'quarterly-report.docx' },
243
- { src: SPREADSHEET_URL, fileName: 'quarterly-model.xlsx' },
244
- { src: PRESENTATION_URL, fileName: 'quarterly-deck.pptx' },
245
- { src: MARKDOWN_URL, fileName: 'quarterly-report.md' },
246
- { src: HTML_URL, fileName: 'quarterly-report.html' },
247
- { src: CSV_URL, fileName: 'quarterly-regions.csv' },
248
- { src: PAGE_IMAGE_URL, fileName: 'quarterly-report-page-1.png' },
249
- ];
250
-
251
- /**
252
- * Tiles load only while on screen: scroll down and the next row starts. Each copy has its own
253
- * `#n` fragment, so it is a different file to the session cache but the same request.
254
- */
255
- export const ScrollingGallery: Story = {
347
+ interface DocumentGalleryProps {
348
+ files: ThumbnailFile[];
349
+ onLoadAvailable?: (fileName: string) => void;
350
+ onLoaded?: (fileName: string) => void;
351
+ }
352
+
353
+ /** A gallery of tiles, reporting which file each callback is for. */
354
+ function DocumentGallery({ files, onLoadAvailable, onLoaded }: DocumentGalleryProps) {
355
+ return (
356
+ <>
357
+ {files.map((file) => (
358
+ <Thumbnail
359
+ key={file.src}
360
+ src={file.src}
361
+ fileName={file.fileName}
362
+ onLoadAvailable={() => onLoadAvailable?.(file.fileName)}
363
+ onLoaded={() => onLoaded?.(file.fileName)}
364
+ />
365
+ ))}
366
+ </>
367
+ );
368
+ }
369
+
370
+ type DocumentGalleryStory = StoryObj<typeof DocumentGallery>;
371
+
372
+ /** Tiles load only while on screen: scroll down and the next row starts. */
373
+ export const ScrollingGallery: DocumentGalleryStory = {
374
+ args: { files: SCROLLING_FILES, onLoadAvailable: fn(), onLoaded: fn() },
375
+ argTypes: {
376
+ files: { control: 'object', description: 'The files, one tile each.' },
377
+ onLoadAvailable: {
378
+ description: 'Called with the file name the first time its tile is on screen.',
379
+ },
380
+ onLoaded: { description: 'Called with the file name once its picture has drawn.' },
381
+ },
256
382
  decorators: [
257
383
  (Story) => (
258
384
  <div className="grid h-[400px] w-[560px] grid-cols-4 gap-8 overflow-auto [&>*]:h-[160px]">
@@ -260,14 +386,355 @@ export const ScrollingGallery: Story = {
260
386
  </div>
261
387
  ),
262
388
  ],
389
+ render: (args) => <DocumentGallery {...args} />,
390
+ };
391
+
392
+ /** Draws the image and fades it in: the tile leaves `loading`, reports each step once and fills its parent. */
393
+ export const DefaultLoadsAndReveals: Story = {
394
+ ...Default,
395
+ tags: ['e2e', '!autodocs'],
396
+ args: {
397
+ ...Default.args,
398
+ onLoadAvailable: fn(),
399
+ onLoadStarted: fn(),
400
+ onLoaded: fn(),
401
+ onLoadFailed: fn(),
402
+ },
403
+ play: async ({ args, canvas, step }) => {
404
+ const tile = canvas.getByRole('img', { name: 'quarterly-report-page-1.png' });
405
+
406
+ await step('Fills the parent that sizes it', async () => {
407
+ const parent = tile.parentElement!.getBoundingClientRect();
408
+ const { width, height } = tile.getBoundingClientRect();
409
+
410
+ await expect(width).toBe(parent.width);
411
+ await expect(height).toBe(parent.height);
412
+ await expect(width).toBe(124);
413
+ });
414
+
415
+ await step('Leaves loading once the picture has drawn', async () => {
416
+ await waitFor(() => expect(tile).toHaveAttribute('data-status', 'loaded'));
417
+ await expect(tile).not.toHaveAttribute('aria-busy');
418
+ await expect(tile.querySelector('[data-slot="file-thumbnail-loader"]')).toBeNull();
419
+ await expect(tile.querySelector('[data-slot="file-thumbnail-fallback"]')).toBeNull();
420
+ });
421
+
422
+ await step('Fades the picture in from its own status', async () => {
423
+ const preview = tile.querySelector<HTMLElement>('[data-slot="file-thumbnail-preview"]')!;
424
+
425
+ await expect(preview).toHaveAttribute('data-status', 'loaded');
426
+ await waitFor(() => expect(getComputedStyle(preview).opacity).toBe('1'));
427
+ });
428
+
429
+ await step('Reports each step of the load once', async () => {
430
+ await expect(args.onLoadAvailable).toHaveBeenCalledTimes(1);
431
+ await expect(args.onLoadStarted).toHaveBeenCalledTimes(1);
432
+ await expect(args.onLoaded).toHaveBeenCalledTimes(1);
433
+ await expect(args.onLoadFailed).not.toHaveBeenCalled();
434
+ });
435
+ },
436
+ };
437
+
438
+ /** While `isLoading` is set the tile stays busy behind the loader and never starts drawing the file. */
439
+ export const LoadingHoldsDrawing: Story = {
440
+ ...Loading,
441
+ tags: ['e2e', '!autodocs'],
442
+ args: {
443
+ ...Loading.args,
444
+ onLoadAvailable: fn(),
445
+ onLoadStarted: fn(),
446
+ onLoaded: fn(),
447
+ onLoadFailed: fn(),
448
+ },
449
+ play: async ({ args, canvas }) => {
450
+ const tile = canvas.getByRole('img', { name: 'quarterly-report.pdf' });
451
+
452
+ await waitFor(() => expect(args.onLoadAvailable).toHaveBeenCalledTimes(1));
453
+ await expect(tile).toHaveAttribute('aria-busy', 'true');
454
+ await expect(tile).toHaveAttribute('data-status', 'loading');
455
+ await expect(tile.querySelector('[data-slot="file-thumbnail-loader"]')).toBeVisible();
456
+ await expect(tile.querySelector('[data-slot="file-thumbnail-preview"]')).toBeNull();
457
+ await expect(args.onLoadStarted).not.toHaveBeenCalled();
458
+ await expect(args.onLoadFailed).not.toHaveBeenCalled();
459
+ },
460
+ };
461
+
462
+ /** A broken image ends on the fallback with the whole file name, and reports the failure once. */
463
+ export const BrokenImageShowsFallback: Story = {
464
+ ...BrokenImage,
465
+ tags: ['e2e', '!autodocs'],
466
+ args: {
467
+ ...BrokenImage.args,
468
+ onLoadAvailable: fn(),
469
+ onLoadStarted: fn(),
470
+ onLoaded: fn(),
471
+ onLoadFailed: fn(),
472
+ },
473
+ play: async ({ args, canvas, step }) => {
474
+ const tile = canvas.getByRole('img', { name: 'missing-site-photo.jpg' });
475
+
476
+ await step('Falls back to the file name', async () => {
477
+ await waitFor(() => expect(tile).toHaveAttribute('data-status', 'error'));
478
+ await expect(tile).not.toHaveAttribute('aria-busy');
479
+ await expect(canvas.getByText('missing-site-photo.')).toBeVisible();
480
+ await expect(canvas.getByText('jpg')).toBeVisible();
481
+ await expect(tile.querySelector('[data-slot="file-thumbnail-preview"]')).toBeNull();
482
+ });
483
+
484
+ await step('Reports the failure, and no load', async () => {
485
+ await expect(args.onLoadFailed).toHaveBeenCalledTimes(1);
486
+ await expect(args.onLoadFailed).toHaveBeenCalledWith(expect.any(Error));
487
+ await expect(args.onLoaded).not.toHaveBeenCalled();
488
+ });
489
+ },
490
+ };
491
+
492
+ /** Asks for the file once when the tile is on screen, stays busy until the blob arrives, then draws it. */
493
+ export const BlobArrivesLaterDrawsOnArrival: DocumentThumbnailStory = {
494
+ ...BlobArrivesLater,
495
+ tags: ['e2e', '!autodocs'],
496
+ // An image, so the test draws without downloading an engine.
497
+ args: {
498
+ fileName: 'quarterly-report-page-1.png',
499
+ onFetchDocument: fn(async () => {
500
+ await delay(300);
501
+
502
+ return (await fetch(PAGE_IMAGE_URL)).blob();
503
+ }),
504
+ onLoaded: fn(),
505
+ },
506
+ play: async ({ args, canvas, step }) => {
507
+ const tile = canvas.getByRole('img', { name: 'quarterly-report-page-1.png' });
508
+
509
+ await step('Shows the loader, not the fallback, while the file is on its way', async () => {
510
+ await waitFor(() => expect(args.onFetchDocument).toHaveBeenCalledTimes(1));
511
+ await expect(tile).toHaveAttribute('aria-busy', 'true');
512
+ await expect(tile.querySelector('[data-slot="file-thumbnail-loader"]')).toBeVisible();
513
+ await expect(tile.querySelector('[data-slot="file-thumbnail-fallback"]')).toBeNull();
514
+ await expect(args.onLoaded).not.toHaveBeenCalled();
515
+ });
516
+
517
+ await step('Draws the file once the blob arrives, without asking again', async () => {
518
+ await waitFor(() => expect(tile).toHaveAttribute('data-status', 'loaded'));
519
+ await expect(tile).not.toHaveAttribute('aria-busy');
520
+ await expect(args.onLoaded).toHaveBeenCalledTimes(1);
521
+ await expect(args.onFetchDocument).toHaveBeenCalledTimes(1);
522
+ });
523
+ },
524
+ };
525
+
526
+ /** A tile below the fold loads nothing until it is scrolled on screen. */
527
+ export const ScrollingGalleryLoadsOnScroll: DocumentGalleryStory = {
528
+ ...ScrollingGallery,
529
+ tags: ['e2e', '!autodocs'],
530
+ // Images only, so the test draws without downloading an engine.
531
+ args: { files: SCROLLING_IMAGES, onLoadAvailable: fn(), onLoaded: fn() },
532
+ play: async ({ args, canvas, step }) => {
533
+ const first = canvas.getByRole('img', { name: 'site-inspection-page-1.png' });
534
+ const last = canvas.getByRole('img', { name: 'site-inspection-page-24.png' });
535
+
536
+ await step('Draws the tiles on screen and leaves the last one waiting', async () => {
537
+ await waitFor(() => expect(first).toHaveAttribute('data-status', 'loaded'));
538
+ await expect(last).toHaveAttribute('aria-busy', 'true');
539
+ await expect(last.querySelector('[data-slot="file-thumbnail-preview"]')).toBeNull();
540
+ await expect(args.onLoadAvailable).not.toHaveBeenCalledWith('site-inspection-page-24.png');
541
+ });
542
+
543
+ await step('Draws the last tile once it is scrolled on screen', async () => {
544
+ last.scrollIntoView();
545
+ await waitFor(() => expect(last).toHaveAttribute('data-status', 'loaded'));
546
+ await expect(args.onLoadAvailable).toHaveBeenCalledWith('site-inspection-page-24.png');
547
+ await expect(args.onLoaded).toHaveBeenCalledWith('site-inspection-page-24.png');
548
+ });
549
+ },
550
+ };
551
+
552
+ const openButtonClassName =
553
+ 'flex w-full flex-col gap-8 rounded-10 border border-component-divider p-8 text-left hover:bg-secondary-states-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-focus-visible';
554
+
555
+ /** The tile in each place it goes: a grid of shared files, an upload queue, an attachment tray and a scrolling gallery. */
556
+ export const Examples: Story = {
557
+ parameters: { controls: { disable: true } },
263
558
  render: () => (
264
- <>
265
- {Array.from({ length: 48 }, (_, index) => {
266
- const file = DRAWN_FILES[index % DRAWN_FILES.length];
267
- const src = `${file.src}#${index}`;
559
+ <div className="flex w-120 flex-col gap-24">
560
+ <ParentBlock parent="grid of uploaded or attached files">
561
+ <ul aria-label="Documents" className="grid grid-cols-3 gap-12">
562
+ {LIBRARY_DOCUMENTS.map((document) => (
563
+ <li key={document.documentId} className="min-w-0">
564
+ {/* The tile is an image, so the control that opens the file wraps the whole of it. */}
565
+ <button
566
+ type="button"
567
+ aria-label={`Open ${document.fileName}`}
568
+ className={openButtonClassName}
569
+ >
570
+ <span className="block h-28 w-full">
571
+ <Thumbnail src={document.src} fileName={document.fileName} />
572
+ </span>
573
+ <Typography variant="body-small-high" className="max-w-full truncate" asChild>
574
+ <span>{document.fileName}</span>
575
+ </Typography>
576
+ <Typography variant="caption-md" className="text-text-tertiary" asChild>
577
+ <span>{document.sharedAt}</span>
578
+ </Typography>
579
+ </button>
580
+ </li>
581
+ ))}
582
+ </ul>
583
+ </ParentBlock>
268
584
 
269
- return <Thumbnail key={src} src={src} fileName={file.fileName} />;
270
- })}
271
- </>
585
+ <ParentBlock parent="upload queue">
586
+ <ul aria-label="Uploads" className="flex flex-col gap-8">
587
+ {QUEUED_UPLOADS.map((upload) => (
588
+ <li
589
+ key={upload.uploadId}
590
+ className="flex items-center gap-12 rounded-10 border border-component-divider p-8"
591
+ >
592
+ <div className="size-48 shrink-0">
593
+ {/* Until the upload has a URL the file is on its way: `null`, so the loader shows. */}
594
+ {upload.src === null ? (
595
+ <Thumbnail fileBlob={null} fileName={upload.fileName} />
596
+ ) : (
597
+ <Thumbnail src={upload.src} fileName={upload.fileName} />
598
+ )}
599
+ </div>
600
+ <div className="flex min-w-0 flex-1 flex-col gap-2">
601
+ <Typography variant="body-small-high" className="truncate">
602
+ {upload.fileName}
603
+ </Typography>
604
+ <Typography variant="caption-md" className="text-text-tertiary">
605
+ {upload.status}
606
+ </Typography>
607
+ </div>
608
+ </li>
609
+ ))}
610
+ </ul>
611
+ </ParentBlock>
612
+
613
+ <ParentBlock parent="attachment tray">
614
+ <ul
615
+ aria-label="Attachments"
616
+ className="flex gap-8 rounded-10 border border-component-divider p-8"
617
+ >
618
+ {ATTACHED_FILES.map((file) => (
619
+ <li key={file.fileName} className="size-18 shrink-0">
620
+ <Thumbnail src={file.src} fileName={file.fileName} />
621
+ </li>
622
+ ))}
623
+ </ul>
624
+ </ParentBlock>
625
+
626
+ <ParentBlock parent="scrolling document gallery">
627
+ <ul
628
+ aria-label="Invoices"
629
+ className="grid h-60 grid-cols-4 gap-8 overflow-auto rounded-10 border border-component-divider p-8"
630
+ >
631
+ {GALLERY_DOCUMENTS.map((document) => (
632
+ <li key={document.documentId} className="h-28">
633
+ {/* The server renders the pictures of a long list, so no engine loads. */}
634
+ <Thumbnail
635
+ src={document.src}
636
+ fileName={document.fileName}
637
+ previewImageUrl={document.previewImageUrl}
638
+ />
639
+ </li>
640
+ ))}
641
+ </ul>
642
+ </ParentBlock>
643
+ </div>
272
644
  ),
273
645
  };
646
+
647
+ interface FileThumbnailPlaygroundProps {
648
+ fileName: string;
649
+ src: string;
650
+ previewImageUrl?: string;
651
+ className?: string;
652
+ previewClassName?: string;
653
+ labelClassName?: string;
654
+ fallback: string;
655
+ isLoading: boolean;
656
+ hasLoader: boolean;
657
+ hasPreview: boolean;
658
+ hasFallback: boolean;
659
+ onLoadAvailable: () => void;
660
+ onLoadStarted: () => void;
661
+ onLoaded: () => void;
662
+ onLoadFailed: (error: Error) => void;
663
+ }
664
+
665
+ function FileThumbnailPlayground({
666
+ previewClassName,
667
+ labelClassName,
668
+ fallback,
669
+ hasLoader,
670
+ hasPreview,
671
+ hasFallback,
672
+ ...rest
673
+ }: FileThumbnailPlaygroundProps) {
674
+ return (
675
+ <div className={tileClassName}>
676
+ <FileThumbnail {...rest}>
677
+ {hasLoader && <FileThumbnailLoader />}
678
+ {hasPreview && <FileThumbnailPreview className={previewClassName} />}
679
+ {hasFallback && (
680
+ <FileThumbnailFallback labelClassName={labelClassName}>
681
+ {fallback || undefined}
682
+ </FileThumbnailFallback>
683
+ )}
684
+ </FileThumbnail>
685
+ </div>
686
+ );
687
+ }
688
+
689
+ /** All three parts at once, with every prop of the root and the parts on the Controls panel. */
690
+ export const Playground: StoryObj<typeof FileThumbnailPlayground> = {
691
+ tags: ['!autodocs'],
692
+ args: {
693
+ fileName: 'quarterly-report.pdf',
694
+ src: PDF_URL,
695
+ previewImageUrl: 'None',
696
+ className: '',
697
+ previewClassName: '',
698
+ labelClassName: '',
699
+ fallback: '',
700
+ isLoading: false,
701
+ hasLoader: true,
702
+ hasPreview: true,
703
+ hasFallback: true,
704
+ onLoadAvailable: fn(),
705
+ onLoadStarted: fn(),
706
+ onLoaded: fn(),
707
+ onLoadFailed: fn(),
708
+ },
709
+ argTypes: {
710
+ previewImageUrl: {
711
+ control: 'select',
712
+ options: ['None', 'Server-rendered page'],
713
+ mapping: { None: undefined, 'Server-rendered page': PAGE_IMAGE_URL },
714
+ description: '`previewImageUrl` on the root: a ready picture drawn instead of the file.',
715
+ },
716
+ previewClassName: {
717
+ control: 'text',
718
+ description:
719
+ '`className` of `FileThumbnailPreview`, e.g. `data-[status=loaded]:opacity-60` to restyle the drawn state.',
720
+ },
721
+ labelClassName: {
722
+ control: 'text',
723
+ description:
724
+ '`labelClassName` of `FileThumbnailFallback`: classes for the default file name. Break `src` to see it.',
725
+ },
726
+ fallback: {
727
+ control: 'text',
728
+ description:
729
+ 'Content of `FileThumbnailFallback`. Empty keeps the default file name; break `src` to see it.',
730
+ },
731
+ hasLoader: { control: 'boolean', description: 'Renders `FileThumbnailLoader`.' },
732
+ hasPreview: {
733
+ control: 'boolean',
734
+ description:
735
+ 'Renders `FileThumbnailPreview`. Without it a drawable file never leaves `loading`.',
736
+ },
737
+ hasFallback: { control: 'boolean', description: 'Renders `FileThumbnailFallback`.' },
738
+ },
739
+ render: (args) => <FileThumbnailPlayground {...args} />,
740
+ };