@classic-homes/files-svelte 0.3.0 → 0.4.0

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.
@@ -148,6 +148,8 @@
148
148
  // Server search (only when the source offers it)
149
149
  let searchResults = $state.raw<FileEntry[] | null>(null);
150
150
  let searchStatus = $state<'idle' | 'loading' | 'ready' | 'error'>('idle');
151
+ let searchError = $state.raw<unknown>();
152
+ let searchAttempt = $state(0);
151
153
 
152
154
  let selected = $state<string>();
153
155
  let sort = $state<FileSort | null>(null);
@@ -275,6 +277,8 @@
275
277
  if (controller.signal.aborted || isAbortError(err)) return;
276
278
  listError = err;
277
279
  status = 'error';
280
+ // A failed navigation must not steal focus on some later reload.
281
+ focusAfterLoad = false;
278
282
  announcement = describeFilesError(err).title;
279
283
  report(err);
280
284
  }
@@ -327,14 +331,21 @@
327
331
  const id = rootId;
328
332
  const folder = currentPath;
329
333
  const includeHidden = showHidden;
334
+ void searchAttempt;
330
335
  if (!src.search || !query || id === undefined) {
331
336
  searchResults = null;
332
337
  searchStatus = 'idle';
333
338
  return;
334
339
  }
340
+ // Loading from the first keystroke: during the debounce the list would
341
+ // otherwise say "Nothing matches", or keep the previous query's results.
342
+ untrack(() => {
343
+ searchResults = null;
344
+ searchError = undefined;
345
+ searchStatus = 'loading';
346
+ });
335
347
  const controller = new AbortController();
336
348
  const timer = setTimeout(() => {
337
- searchStatus = 'loading';
338
349
  src.search!(id, query, {
339
350
  path: folder,
340
351
  includeHidden,
@@ -349,8 +360,8 @@
349
360
  },
350
361
  (err) => {
351
362
  if (controller.signal.aborted || isAbortError(err)) return;
363
+ searchError = err;
352
364
  searchStatus = 'error';
353
- searchResults = [];
354
365
  report(err);
355
366
  }
356
367
  );
@@ -485,6 +496,7 @@
485
496
  const loaded = entries.length;
486
497
  const all = total ?? loaded;
487
498
  if (searching) {
499
+ if (searchStatus === 'error') return '';
488
500
  return searchStatus === 'loading'
489
501
  ? 'Searching…'
490
502
  : `${nf.format(shown.length)} result${shown.length === 1 ? '' : 's'} in ${folderName}`;
@@ -651,6 +663,8 @@
651
663
  rootLabel={currentPath ? rootLabel : undefined}
652
664
  class="py-12"
653
665
  />
666
+ {:else if searching && searchStatus === 'error'}
667
+ <FileErrorState error={searchError} onretry={() => searchAttempt++} class="py-12" />
654
668
  {:else}
655
669
  <FileList
656
670
  bind:this={list}
@@ -660,13 +674,13 @@
660
674
  loading={rootsStatus === 'loading' ||
661
675
  status === 'loading' ||
662
676
  status === 'idle' ||
663
- (searching && searchStatus === 'loading' && !searchResults)}
677
+ (searching && searchStatus === 'loading')}
664
678
  {loadingMore}
665
679
  {hasMore}
666
680
  {autoLoad}
667
681
  onloadmore={loadMore}
668
682
  onopen={open}
669
- {total}
683
+ total={filter.trim() ? undefined : total}
670
684
  showCount={false}
671
685
  label={listLabel}
672
686
  {locale}
@@ -729,6 +743,7 @@
729
743
  ondownload={(_, err) => {
730
744
  if (err) report(err);
731
745
  }}
746
+ onerror={report}
732
747
  class="min-h-0 flex-1"
733
748
  />
734
749
  </Dialog>
@@ -89,6 +89,7 @@
89
89
 
90
90
  let grid = $state<HTMLTableElement>();
91
91
  let sentinel = $state<HTMLElement>();
92
+ let root = $state<HTMLElement>();
92
93
 
93
94
  const rows = $derived(sort ? sortEntries(entries, sort) : entries);
94
95
  const activeIndex = $derived.by(() => {
@@ -136,15 +137,38 @@
136
137
  onopen?.(entry);
137
138
  }
138
139
 
139
- /** Focus the selected row (or the first), e.g. after a folder loads. */
140
+ /**
141
+ * Focus the selected row (or the first), e.g. after a folder loads. An empty
142
+ * list focuses itself, so focus never falls back to the page.
143
+ */
140
144
  export function focus() {
141
- rowEl(activeIndex)?.focus();
145
+ const row = rowEl(activeIndex);
146
+ if (row) row.focus();
147
+ else root?.focus();
142
148
  }
143
149
 
150
+ /** "Load more" clicked: move to the first new row once it lands (the button may go). */
151
+ let focusFrom = $state<number>();
152
+ function loadMoreClicked() {
153
+ focusFrom = entries.length;
154
+ onloadmore?.();
155
+ }
156
+ $effect(() => {
157
+ const from = focusFrom;
158
+ if (from === undefined || loadingMore) return;
159
+ focusFrom = undefined;
160
+ const first = entries[from];
161
+ if (!first) return; // failed or nothing new: the button is still there
162
+ const index = rows.findIndex((e) => e.path === first.path);
163
+ if (index >= 0) void select(index);
164
+ });
165
+
144
166
  let typeahead = '';
145
167
  let typeaheadTimer: ReturnType<typeof setTimeout> | undefined;
146
168
 
147
169
  function onRowKeydown(event: KeyboardEvent, index: number) {
170
+ // Keys inside a row action (a button) belong to it.
171
+ if (event.target !== event.currentTarget) return;
148
172
  const entry = rows[index];
149
173
  const page = 10;
150
174
  switch (event.key) {
@@ -215,8 +239,12 @@
215
239
  }
216
240
 
217
241
  // Infinite scroll: load the next page when the sentinel comes into view.
242
+ // Re-created after every page (loadingMore, entries.length): an observer only
243
+ // reports changes, so a sentinel still in view would otherwise stall.
218
244
  $effect(() => {
219
- if (!autoLoad || !sentinel || !hasMore || typeof IntersectionObserver === 'undefined') return;
245
+ void entries.length;
246
+ if (!autoLoad || !sentinel || !hasMore || loadingMore) return;
247
+ if (typeof IntersectionObserver === 'undefined') return;
220
248
  const observer = new IntersectionObserver((items) => {
221
249
  if (items.some((i) => i.isIntersecting) && !loadingMore) onloadmore?.();
222
250
  });
@@ -227,7 +255,15 @@
227
255
  const nf = $derived(new Intl.NumberFormat(locale));
228
256
  </script>
229
257
 
230
- <div class={cn('flex min-h-0 flex-col', className)} data-file-list>
258
+ <!-- Empty: the wrapper takes focus (named), so keyboard focus isn't dropped. -->
259
+ <div
260
+ bind:this={root}
261
+ tabindex={entries.length === 0 ? -1 : undefined}
262
+ role={entries.length === 0 ? 'group' : undefined}
263
+ aria-label={entries.length === 0 ? label : undefined}
264
+ class={cn('flex min-h-0 flex-col outline-none', className)}
265
+ data-file-list
266
+ >
231
267
  {#if loading && entries.length === 0}
232
268
  <div class="divide-y divide-border" aria-hidden="true" data-file-list-skeleton>
233
269
  {#each { length: 8 } as _, i (i)}
@@ -314,10 +350,12 @@
314
350
  isLink
315
351
  ? 'cursor-not-allowed text-muted-foreground'
316
352
  : 'cursor-pointer hover:bg-muted/60',
317
- entry.hidden && 'opacity-70'
353
+ // Hidden: muted and italic, not faded (opacity fails contrast).
354
+ entry.hidden && 'italic text-muted-foreground'
318
355
  )}
319
- onclick={() => {
356
+ onclick={(e) => {
320
357
  void select(index, false);
358
+ if ((e.target as Element).closest('[data-row-actions]')) return;
321
359
  open(entry);
322
360
  }}
323
361
  onkeydown={(e) => onRowKeydown(e, index)}
@@ -345,7 +383,8 @@
345
383
  {/if}
346
384
  </div>
347
385
  <!-- Phones: size · modified under the name -->
348
- <div class="truncate text-xs text-muted-foreground sm:hidden" aria-hidden="true">
386
+ <!-- Not aria-hidden: below sm it is the only place size and date are shown. -->
387
+ <div class="truncate text-xs text-muted-foreground sm:hidden">
349
388
  {[size, modified].filter(Boolean).join(' · ')}
350
389
  </div>
351
390
  </div>
@@ -354,7 +393,9 @@
354
393
  <td role="gridcell" class="hidden px-3 py-2 text-muted-foreground sm:table-cell">
355
394
  {#if modified}
356
395
  <time datetime={entry.modified} title={modifiedFull}
357
- >{modified}<span class="sr-only">, {modifiedFull}</span></time
396
+ >{modified}{#if !modifiedFull.startsWith(modified)}<span class="sr-only"
397
+ >, {modifiedFull}</span
398
+ >{/if}</time
358
399
  >
359
400
  {/if}
360
401
  </td>
@@ -365,7 +406,9 @@
365
406
  {size}
366
407
  </td>
367
408
  {#if rowActions}
368
- <td role="gridcell" class="px-3 py-1 text-right">{@render rowActions(entry)}</td>
409
+ <td role="gridcell" class="px-3 py-1 text-right" data-row-actions>
410
+ {@render rowActions(entry)}
411
+ </td>
369
412
  {/if}
370
413
  </tr>
371
414
  {/each}
@@ -383,7 +426,7 @@
383
426
  {/if}
384
427
  {#if hasMore}
385
428
  <div bind:this={sentinel}>
386
- <Button variant="outline" size="sm" loading={loadingMore} onclick={() => onloadmore?.()}>
429
+ <Button variant="outline" size="sm" loading={loadingMore} onclick={loadMoreClicked}>
387
430
  Load more
388
431
  </Button>
389
432
  </div>
@@ -3,6 +3,7 @@
3
3
  import { Alert, Button, EmptyState, Icon, Spinner } from '@classic-homes/theme-svelte';
4
4
  import { DocumentViewer, type ViewerRegistry } from '@classic-homes/viewer-svelte';
5
5
  import {
6
+ fileExtension,
6
7
  formatBytes,
7
8
  isAbortError,
8
9
  previewRoute,
@@ -36,9 +37,22 @@
36
37
  locale?: string | string[];
37
38
  /** Called after a download starts, or with the error when it fails. */
38
39
  ondownload?: (entry: FileEntry, error?: unknown) => void;
40
+ /** The file couldn't be loaded for preview (a 401 included), for logging or re-login. */
41
+ onerror?: (error: unknown) => void;
39
42
  class?: string;
40
43
  }
41
44
 
45
+ /** Image types by extension: the preview never trusts the server's Content-Type. */
46
+ const IMAGE_TYPES: Record<string, string> = {
47
+ png: 'image/png',
48
+ jpg: 'image/jpeg',
49
+ jpeg: 'image/jpeg',
50
+ gif: 'image/gif',
51
+ webp: 'image/webp',
52
+ bmp: 'image/bmp',
53
+ avif: 'image/avif',
54
+ };
55
+
42
56
  let {
43
57
  source,
44
58
  rootId,
@@ -49,11 +63,16 @@
49
63
  showTitle = true,
50
64
  locale,
51
65
  ondownload,
66
+ onerror,
52
67
  class: className,
53
68
  }: Props = $props();
54
69
 
70
+ /** Real size when the bytes exceed the cap (the listing's size was stale or missing). */
71
+ let oversize = $state<number>();
55
72
  const route = $derived(previewRoute(entry, Object.keys(viewers)));
56
- const tooLarge = $derived(route.kind !== 'none' && entry.size > maxBytes);
73
+ const tooLarge = $derived(
74
+ route.kind !== 'none' && (entry.size > maxBytes || oversize !== undefined)
75
+ );
57
76
  const willPreview = $derived(route.kind !== 'none' && !tooLarge);
58
77
 
59
78
  let status = $state<'idle' | 'loading' | 'ready' | 'error'>('idle');
@@ -71,32 +90,45 @@
71
90
  const root = rootId;
72
91
  const src = source;
73
92
  void attempt;
74
- if (!willPreview) {
75
- status = 'idle';
76
- return;
77
- }
78
- const controller = new AbortController();
93
+ // Clear the previous file's state first, previewable or not.
79
94
  untrack(() => {
80
- status = 'loading';
81
95
  error = undefined;
82
96
  blob = undefined;
83
97
  downloadError = undefined;
98
+ status = willPreview ? 'loading' : 'idle';
84
99
  });
100
+ if (!willPreview) return;
101
+ const controller = new AbortController();
102
+ const kind = route.kind;
103
+ const max = maxBytes;
85
104
  src.read(root, path, { signal: controller.signal }).then(
86
105
  (b) => {
87
106
  if (controller.signal.aborted) return;
88
- blob = b;
107
+ if (b.size > max) {
108
+ oversize = b.size;
109
+ return;
110
+ }
111
+ // Images render from this blob: type it from the extension.
112
+ const type = kind === 'image' ? IMAGE_TYPES[fileExtension(path)] : undefined;
113
+ blob = type ? new Blob([b], { type }) : b;
89
114
  status = 'ready';
90
115
  },
91
116
  (err) => {
92
117
  if (controller.signal.aborted || isAbortError(err)) return;
93
118
  error = err;
94
119
  status = 'error';
120
+ onerror?.(err);
95
121
  }
96
122
  );
97
123
  return () => controller.abort();
98
124
  });
99
125
 
126
+ // A new file starts with no size verdict.
127
+ $effect.pre(() => {
128
+ void entry.path;
129
+ untrack(() => (oversize = undefined));
130
+ });
131
+
100
132
  // Images go through an object URL, revoked when the file changes or the preview closes.
101
133
  $effect(() => {
102
134
  if (route.kind !== 'image' || !blob) {
@@ -169,7 +201,7 @@
169
201
  {#if tooLarge}
170
202
  <EmptyState
171
203
  title="Too large to preview"
172
- description={`This file is ${formatBytes(entry.size, { locale })}. Previews stop at ${formatBytes(maxBytes, { locale })}: download it instead.`}
204
+ description={`This file is ${formatBytes(oversize ?? entry.size, { locale })}. Previews stop at ${formatBytes(maxBytes, { locale })}: download it instead.`}
173
205
  icon="download"
174
206
  size="sm"
175
207
  headingLevel="h4"
@@ -19,6 +19,8 @@ interface Props {
19
19
  locale?: string | string[];
20
20
  /** Called after a download starts, or with the error when it fails. */
21
21
  ondownload?: (entry: FileEntry, error?: unknown) => void;
22
+ /** The file couldn't be loaded for preview (a 401 included), for logging or re-login. */
23
+ onerror?: (error: unknown) => void;
22
24
  class?: string;
23
25
  }
24
26
  declare const FilePreview: import("svelte").Component<Props, {}, "">;
@@ -8,4 +8,5 @@ export { default as FileDetails } from './FileDetails.svelte';
8
8
  export { default as FileErrorState } from './FileErrorState.svelte';
9
9
  export type { FileBrowserContext } from './types.js';
10
10
  export { downloadEntry } from './utils.js';
11
- export { createChapiFilesSource, createMemoryFilesSource, FilesError, isFilesError, describeFilesError, writeCapabilities, formatBytes, formatDateTime, formatRelativeTime, joinPath, parentPath, normalizePath, pathSegments, displayPath, kindForName, kindForEntry, previewRoute, saveBlob, type FileEntry, type FileEntryType, type FileKind, type FileListPage, type FileRoot, type FileSort, type FileSortKey, type FilesErrorCode, type FilesSource, type ChapiFilesSourceOptions, type MemoryFile, type MemoryRoot, type MemoryFilesSourceOptions, } from '@classic-homes/files-core';
11
+ export { createChapiFilesSource, createMemoryFilesSource, FilesError, isFilesError, describeFilesError, writeCapabilities, formatBytes, formatDateTime, formatRelativeTime, joinPath, parentPath, normalizePath, pathSegments, displayPath, baseName, kindForName, kindForEntry, fileExtension, KIND_LABELS, previewRoute, sortEntries, filterEntries, compareEntries, isAbortError, saveBlob, type FileEntry, type FileEntryType, type FileKind, type FileListPage, type FileRoot, type FileSort, type FileSortKey, type FilesErrorCode, type FilesSource, type ListOptions, type SearchOptions, type WriteCapabilities, type PreviewRoute, type ChapiFilesSourceOptions, type MemoryFile, type MemoryRoot, type MemoryFilesSourceOptions, } from '@classic-homes/files-core';
12
+ export type { ViewerRegistry } from '@classic-homes/viewer-svelte';
package/dist/lib/index.js CHANGED
@@ -8,4 +8,4 @@ export { default as FileDetails } from './FileDetails.svelte';
8
8
  export { default as FileErrorState } from './FileErrorState.svelte';
9
9
  export { downloadEntry } from './utils.js';
10
10
  // Core re-exports most consumers need alongside the components
11
- export { createChapiFilesSource, createMemoryFilesSource, FilesError, isFilesError, describeFilesError, writeCapabilities, formatBytes, formatDateTime, formatRelativeTime, joinPath, parentPath, normalizePath, pathSegments, displayPath, kindForName, kindForEntry, previewRoute, saveBlob, } from '@classic-homes/files-core';
11
+ export { createChapiFilesSource, createMemoryFilesSource, FilesError, isFilesError, describeFilesError, writeCapabilities, formatBytes, formatDateTime, formatRelativeTime, joinPath, parentPath, normalizePath, pathSegments, displayPath, baseName, kindForName, kindForEntry, fileExtension, KIND_LABELS, previewRoute, sortEntries, filterEntries, compareEntries, isAbortError, saveBlob, } from '@classic-homes/files-core';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@classic-homes/files-svelte",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Svelte network-drive file browser for Classic Theme: FileBrowser plus FileList, FileBreadcrumbs, FileIcon, FilePreview and FileDetails, with previews through the document viewers",
5
5
  "type": "module",
6
6
  "svelte": "./dist/lib/index.js",