@classic-homes/files-svelte 0.2.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.
@@ -47,6 +47,13 @@
47
47
  onrootchange?: (rootId: string) => void;
48
48
  /** The user opened another folder. */
49
49
  onpathchange?: (path: string) => void;
50
+ /**
51
+ * The location changed (drive, folder or both), in one call. Use this to
52
+ * keep the location in the URL: on a drive change `onrootchange` and
53
+ * `onpathchange` fire back to back, and a URL built from the current page
54
+ * in each would lose the first change.
55
+ */
56
+ onnavigate?: (location: { rootId: string; path: string }) => void;
50
57
  /** Document viewers for previews, as lazy imports keyed by format. */
51
58
  viewers?: ViewerRegistry;
52
59
  /** Entries per page. Default 200. */
@@ -94,6 +101,7 @@
94
101
  path = $bindable(''),
95
102
  onrootchange,
96
103
  onpathchange,
104
+ onnavigate,
97
105
  viewers = {},
98
106
  pageSize = 200,
99
107
  autoLoad = false,
@@ -140,6 +148,8 @@
140
148
  // Server search (only when the source offers it)
141
149
  let searchResults = $state.raw<FileEntry[] | null>(null);
142
150
  let searchStatus = $state<'idle' | 'loading' | 'ready' | 'error'>('idle');
151
+ let searchError = $state.raw<unknown>();
152
+ let searchAttempt = $state(0);
143
153
 
144
154
  let selected = $state<string>();
145
155
  let sort = $state<FileSort | null>(null);
@@ -211,6 +221,7 @@
211
221
  rootId = list[0].id;
212
222
  if (current !== undefined) path = '';
213
223
  onrootchange?.(list[0].id);
224
+ onnavigate?.({ rootId: list[0].id, path: untrack(() => currentPath) });
214
225
  }
215
226
  },
216
227
  (err) => {
@@ -266,6 +277,8 @@
266
277
  if (controller.signal.aborted || isAbortError(err)) return;
267
278
  listError = err;
268
279
  status = 'error';
280
+ // A failed navigation must not steal focus on some later reload.
281
+ focusAfterLoad = false;
269
282
  announcement = describeFilesError(err).title;
270
283
  report(err);
271
284
  }
@@ -318,14 +331,21 @@
318
331
  const id = rootId;
319
332
  const folder = currentPath;
320
333
  const includeHidden = showHidden;
334
+ void searchAttempt;
321
335
  if (!src.search || !query || id === undefined) {
322
336
  searchResults = null;
323
337
  searchStatus = 'idle';
324
338
  return;
325
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
+ });
326
347
  const controller = new AbortController();
327
348
  const timer = setTimeout(() => {
328
- searchStatus = 'loading';
329
349
  src.search!(id, query, {
330
350
  path: folder,
331
351
  includeHidden,
@@ -340,8 +360,8 @@
340
360
  },
341
361
  (err) => {
342
362
  if (controller.signal.aborted || isAbortError(err)) return;
363
+ searchError = err;
343
364
  searchStatus = 'error';
344
- searchResults = [];
345
365
  report(err);
346
366
  }
347
367
  );
@@ -368,6 +388,7 @@
368
388
  }
369
389
  path = target;
370
390
  onpathchange?.(target);
391
+ if (rootId !== undefined) onnavigate?.({ rootId, path: target });
371
392
  }
372
393
 
373
394
  function goUp() {
@@ -387,15 +408,25 @@
387
408
  path = nextPath;
388
409
  onpathchange?.(nextPath);
389
410
  }
411
+ onnavigate?.({ rootId: id, path: nextPath });
390
412
  }
391
413
 
392
414
  /** From the folder tree: a folder in this drive, or another drive (and folder). */
393
415
  function treeNavigate(id: string, next: string) {
394
- foldersOpen = false;
416
+ if (foldersOpen) {
417
+ // Phone sheet: it closes, so continue in the list once it loads.
418
+ foldersOpen = false;
419
+ focusAfterLoad = true;
420
+ }
395
421
  if (id !== rootId) changeRoot(id, next);
396
422
  else navigate(next);
397
423
  }
398
424
 
425
+ // A sheet left open on a phone must not reappear when the view narrows again.
426
+ $effect(() => {
427
+ if (wide.current) foldersOpen = false;
428
+ });
429
+
399
430
  function refresh() {
400
431
  attempt++;
401
432
  }
@@ -465,6 +496,7 @@
465
496
  const loaded = entries.length;
466
497
  const all = total ?? loaded;
467
498
  if (searching) {
499
+ if (searchStatus === 'error') return '';
468
500
  return searchStatus === 'loading'
469
501
  ? 'Searching…'
470
502
  : `${nf.format(shown.length)} result${shown.length === 1 ? '' : 's'} in ${folderName}`;
@@ -631,6 +663,8 @@
631
663
  rootLabel={currentPath ? rootLabel : undefined}
632
664
  class="py-12"
633
665
  />
666
+ {:else if searching && searchStatus === 'error'}
667
+ <FileErrorState error={searchError} onretry={() => searchAttempt++} class="py-12" />
634
668
  {:else}
635
669
  <FileList
636
670
  bind:this={list}
@@ -640,13 +674,13 @@
640
674
  loading={rootsStatus === 'loading' ||
641
675
  status === 'loading' ||
642
676
  status === 'idle' ||
643
- (searching && searchStatus === 'loading' && !searchResults)}
677
+ (searching && searchStatus === 'loading')}
644
678
  {loadingMore}
645
679
  {hasMore}
646
680
  {autoLoad}
647
681
  onloadmore={loadMore}
648
682
  onopen={open}
649
- {total}
683
+ total={filter.trim() ? undefined : total}
650
684
  showCount={false}
651
685
  label={listLabel}
652
686
  {locale}
@@ -666,7 +700,16 @@
666
700
  {/snippet}
667
701
 
668
702
  {#snippet tree()}
669
- <FileTree {source} {roots} {rootId} path={currentPath} {showHidden} onnavigate={treeNavigate} />
703
+ <FileTree
704
+ {source}
705
+ {roots}
706
+ {rootId}
707
+ path={currentPath}
708
+ {showHidden}
709
+ refreshKey={attempt}
710
+ onerror={report}
711
+ onnavigate={treeNavigate}
712
+ />
670
713
  {/snippet}
671
714
 
672
715
  {#snippet actions(entry: FileEntry)}
@@ -700,6 +743,7 @@
700
743
  ondownload={(_, err) => {
701
744
  if (err) report(err);
702
745
  }}
746
+ onerror={report}
703
747
  class="min-h-0 flex-1"
704
748
  />
705
749
  </Dialog>
@@ -13,6 +13,16 @@ interface Props {
13
13
  onrootchange?: (rootId: string) => void;
14
14
  /** The user opened another folder. */
15
15
  onpathchange?: (path: string) => void;
16
+ /**
17
+ * The location changed (drive, folder or both), in one call. Use this to
18
+ * keep the location in the URL: on a drive change `onrootchange` and
19
+ * `onpathchange` fire back to back, and a URL built from the current page
20
+ * in each would lose the first change.
21
+ */
22
+ onnavigate?: (location: {
23
+ rootId: string;
24
+ path: string;
25
+ }) => void;
16
26
  /** Document viewers for previews, as lazy imports keyed by format. */
17
27
  viewers?: ViewerRegistry;
18
28
  /** Entries per page. Default 200. */
@@ -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, {}, "">;
@@ -31,6 +31,13 @@
31
31
  showHidden?: boolean;
32
32
  /** A folder (or a drive, with `path` `''`) was chosen. */
33
33
  onnavigate?: (rootId: string, path: string) => void;
34
+ /**
35
+ * Change it to reload the expanded folders in place (e.g. after a refresh
36
+ * or a write). FileBrowser passes its refresh counter.
37
+ */
38
+ refreshKey?: unknown;
39
+ /** A folder failed to load (a 401 included), for logging or re-login. */
40
+ onerror?: (error: unknown) => void;
34
41
  /** Accessible name of the tree. Default "Folders". */
35
42
  label?: string;
36
43
  class?: string;
@@ -43,14 +50,21 @@
43
50
  path = '',
44
51
  showHidden = false,
45
52
  onnavigate,
53
+ refreshKey,
54
+ onerror,
46
55
  label = 'Folders',
47
56
  class: className,
48
57
  }: Props = $props();
49
58
 
59
+ /** Folders listed per folder; past this the tree says to open the folder instead. */
60
+ const MAX_FOLDERS = 5000;
61
+
50
62
  type Status = 'loading' | 'ready' | 'error';
51
63
  interface Children {
52
64
  status: Status;
53
65
  folders: FileEntry[];
66
+ /** More than MAX_FOLDERS subfolders: only the first are listed. */
67
+ more?: boolean;
54
68
  }
55
69
 
56
70
  /** `${rootId}|${path}` → its subfolders (`|` can't occur in SMB names). */
@@ -71,15 +85,20 @@
71
85
  let focusedKey = $state<string>();
72
86
  let tree = $state<HTMLElement>();
73
87
 
74
- /** Load every subfolder (directories come first, so stop at the first file). */
75
- async function load(r: string, p: string) {
88
+ /**
89
+ * Load every subfolder (sources list directories first, so stop at the first
90
+ * file). `force` reloads a loaded folder, keeping its folders on screen.
91
+ */
92
+ async function load(r: string, p: string, force = false) {
76
93
  const key = keyOf(r, p);
77
94
  const state = children.get(key);
78
- if (state && state.status !== 'error') return;
95
+ if (!force && state && state.status !== 'error') return;
96
+ controllers.get(key)?.abort();
79
97
  const controller = new AbortController();
80
98
  controllers.set(key, controller);
81
99
  children.set(key, { status: 'loading', folders: state?.folders ?? [] });
82
100
  const folders: FileEntry[] = [];
101
+ let more = false;
83
102
  try {
84
103
  let cursor: string | undefined;
85
104
  for (;;) {
@@ -92,26 +111,66 @@
92
111
  const dirs = page.entries.filter((e) => e.type === 'dir');
93
112
  folders.push(...dirs);
94
113
  if (!page.nextCursor || dirs.length < page.entries.length) break;
114
+ if (folders.length >= MAX_FOLDERS) {
115
+ more = true;
116
+ break;
117
+ }
95
118
  cursor = page.nextCursor;
96
119
  }
97
- if (!controller.signal.aborted) children.set(key, { status: 'ready', folders });
120
+ if (!controller.signal.aborted) children.set(key, { status: 'ready', folders, more });
98
121
  } catch (err) {
99
122
  if (controller.signal.aborted || isAbortError(err)) return;
100
123
  children.set(key, { status: 'error', folders: [] });
124
+ onerror?.(err);
101
125
  } finally {
102
126
  if (controllers.get(key) === controller) controllers.delete(key);
103
127
  }
104
128
  }
105
129
 
106
- // Start over when the source or the hidden-files setting changes.
130
+ /** (Re)load every expanded folder of a drive that is still listed. */
131
+ function loadExpanded(force: boolean) {
132
+ for (const key of expanded) {
133
+ const i = key.indexOf('|');
134
+ const r = key.slice(0, i);
135
+ if (roots.some((root) => root.id === r)) void load(r, key.slice(i + 1), force);
136
+ }
137
+ }
138
+
139
+ function abortAll() {
140
+ for (const c of controllers.values()) c.abort();
141
+ controllers.clear();
142
+ }
143
+
144
+ // Effects below compare values: a parent that spreads a props object reruns
145
+ // every prop read on any change, and that must not wipe the cache.
146
+ const UNSET = Symbol();
147
+ let loadedFor: { source: FilesSource; showHidden: boolean } | undefined;
148
+ let lastRefresh: unknown = UNSET;
149
+
150
+ // Start over when the source or the hidden-files setting changes, reloading
151
+ // what was expanded (otherwise those folders would wait forever).
107
152
  $effect(() => {
108
- void source;
109
- void showHidden;
110
- return () => {
111
- for (const c of controllers.values()) c.abort();
112
- controllers.clear();
113
- children.clear();
114
- };
153
+ const src = source;
154
+ const hidden = showHidden;
155
+ untrack(() => {
156
+ if (loadedFor?.source === src && loadedFor.showHidden === hidden) return;
157
+ if (loadedFor) {
158
+ abortAll();
159
+ children.clear();
160
+ }
161
+ loadedFor = { source: src, showHidden: hidden };
162
+ loadExpanded(false);
163
+ });
164
+ });
165
+ $effect(() => abortAll);
166
+
167
+ // Refresh: reload the expanded folders in place (no "Loading…" flash).
168
+ $effect(() => {
169
+ const key = refreshKey;
170
+ untrack(() => {
171
+ if (lastRefresh !== UNSET && key !== lastRefresh) loadExpanded(true);
172
+ lastRefresh = key;
173
+ });
115
174
  });
116
175
 
117
176
  // Reveal the open folder: expand its drive and every ancestor, and load them.
@@ -144,10 +203,12 @@
144
203
  hidden: boolean;
145
204
  setsize: number;
146
205
  posinset: number;
206
+ /** A failed folder's "try again" row: a treeitem, so the keyboard reaches it. */
207
+ retry?: () => void;
147
208
  }
148
209
  type Row =
149
210
  | { kind: 'item'; item: Item }
150
- | { kind: 'note'; key: string; level: number; text: string; retry?: () => void };
211
+ | { kind: 'note'; key: string; level: number; text: string };
151
212
 
152
213
  const rows = $derived.by<Row[]>(() => {
153
214
  const out: Row[] = [];
@@ -159,11 +220,19 @@
159
220
  }
160
221
  if (state.status === 'error') {
161
222
  out.push({
162
- kind: 'note',
163
- key: `${keyOf(r, p)}:error`,
164
- level,
165
- text: "Couldn't open. Try again",
166
- retry: () => void load(r, p),
223
+ kind: 'item',
224
+ item: {
225
+ key: `${keyOf(r, p)}:error`,
226
+ rootId: r,
227
+ path: p,
228
+ name: "Couldn't open this folder. Try again",
229
+ level,
230
+ isRoot: false,
231
+ hidden: false,
232
+ setsize: 1,
233
+ posinset: 1,
234
+ retry: () => void load(r, p),
235
+ },
167
236
  });
168
237
  return;
169
238
  }
@@ -185,6 +254,14 @@
185
254
  });
186
255
  if (expanded.has(key)) walk(r, f.path, level + 1);
187
256
  });
257
+ if (state.more) {
258
+ out.push({
259
+ kind: 'note',
260
+ key: `${keyOf(r, p)}:more`,
261
+ level,
262
+ text: `Only the first ${state.folders.length.toLocaleString()} folders are listed. Open the folder to see them all.`,
263
+ });
264
+ }
188
265
  };
189
266
  roots.forEach((root, i) => {
190
267
  const key = keyOf(root.id, '');
@@ -214,8 +291,9 @@
214
291
  : (items.find((i) => i.key === currentKey) ?? items[0])?.key
215
292
  );
216
293
 
217
- /** Known to have no subfolders (loaded and empty). */
294
+ /** Known to have no subfolders (loaded and empty), or a retry row. */
218
295
  function isLeaf(item: Item): boolean {
296
+ if (item.retry) return true;
219
297
  const state = children.get(item.key);
220
298
  return state?.status === 'ready' && state.folders.length === 0;
221
299
  }
@@ -231,6 +309,13 @@
231
309
  }
232
310
 
233
311
  function choose(item: Item) {
312
+ if (item.retry) {
313
+ // The row turns into "Loading…": keep focus on its folder.
314
+ const parent = items.find((i) => i.key === keyOf(item.rootId, item.path));
315
+ void focusItem(parent);
316
+ item.retry();
317
+ return;
318
+ }
234
319
  focusedKey = item.key;
235
320
  onnavigate?.(item.rootId, item.path);
236
321
  }
@@ -331,16 +416,7 @@
331
416
  style:padding-left="{row.level * 0.875 + 0.5}rem"
332
417
  class="py-1 text-xs text-muted-foreground"
333
418
  >
334
- {#if row.retry}
335
- <button
336
- type="button"
337
- class="underline hover:text-foreground"
338
- tabindex="-1"
339
- onclick={row.retry}>{row.text}</button
340
- >
341
- {:else}
342
- {row.text}
343
- {/if}
419
+ {row.text}
344
420
  </li>
345
421
  {:else}
346
422
  {@const item = row.item}
@@ -361,7 +437,8 @@
361
437
  'flex cursor-pointer items-center gap-1 rounded-sm py-1 pr-2 outline-none',
362
438
  'focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring',
363
439
  current ? 'bg-chart-1/15 font-medium text-foreground' : 'hover:bg-muted/60',
364
- item.hidden && 'opacity-70'
440
+ // Hidden folders: muted and italic, not faded (opacity fails contrast).
441
+ item.hidden && 'italic text-muted-foreground'
365
442
  )}
366
443
  style:padding-left="{(item.level - 1) * 0.875 + 0.25}rem"
367
444
  title={item.name}
@@ -384,12 +461,16 @@
384
461
  >
385
462
  <Icon name={open ? 'chevron-down' : 'chevron-right'} size={14} />
386
463
  </span>
387
- {#if item.isRoot}
464
+ {#if item.retry}
465
+ <Icon name="refresh" size={14} class="shrink-0 text-muted-foreground" />
466
+ {:else if item.isRoot}
388
467
  <Icon name="home" size={16} class="shrink-0 text-muted-foreground" />
389
468
  {:else}
390
469
  <FileIcon type="dir" size={16} />
391
470
  {/if}
392
- <span class="truncate">{item.name}</span>
471
+ <span class={cn('truncate', item.retry && 'text-xs text-muted-foreground underline')}
472
+ >{item.name}</span
473
+ >
393
474
  </li>
394
475
  {/if}
395
476
  {/each}
@@ -11,6 +11,13 @@ interface Props {
11
11
  showHidden?: boolean;
12
12
  /** A folder (or a drive, with `path` `''`) was chosen. */
13
13
  onnavigate?: (rootId: string, path: string) => void;
14
+ /**
15
+ * Change it to reload the expanded folders in place (e.g. after a refresh
16
+ * or a write). FileBrowser passes its refresh counter.
17
+ */
18
+ refreshKey?: unknown;
19
+ /** A folder failed to load (a 401 included), for logging or re-login. */
20
+ onerror?: (error: unknown) => void;
14
21
  /** Accessible name of the tree. Default "Folders". */
15
22
  label?: string;
16
23
  class?: string;
@@ -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.2.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",