@classic-homes/files-svelte 0.1.0 → 0.3.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.
package/README.md CHANGED
@@ -2,8 +2,8 @@
2
2
 
3
3
  Svelte 5 network-drive file browser for Classic Theme.
4
4
 
5
- - `FileBrowser`: root picker, breadcrumbs, paged listing, filter, hidden files, preview dialog, download, details, every error state, offline banner
6
- - Building blocks: `FileList`, `FileBreadcrumbs`, `FileIcon`, `FilePreview`, `FileDetails`, `FileErrorState`
5
+ - `FileBrowser`: Explorer-style folder pane (drives, open folder's parents expanded, resizable), root picker, breadcrumbs, paged listing, filter, hidden files, preview dialog, download, details, every error state, offline banner
6
+ - Building blocks: `FileTree`, `FileList`, `FileBreadcrumbs`, `FileIcon`, `FilePreview`, `FileDetails`, `FileErrorState`
7
7
  - Previews reuse [`@classic-homes/viewer-svelte`](../viewer-svelte): pass a `viewers` registry of lazy imports
8
8
  - Re-exports the [`@classic-homes/files-core`](../files-core) sources and helpers
9
9
 
@@ -1,6 +1,7 @@
1
1
  <script lang="ts">
2
2
  import type { Snippet } from 'svelte';
3
3
  import { tick, untrack } from 'svelte';
4
+ import { MediaQuery } from 'svelte/reactivity';
4
5
  import {
5
6
  Alert,
6
7
  Button,
@@ -8,7 +9,9 @@
8
9
  EmptyState,
9
10
  Icon,
10
11
  LiveRegion,
12
+ ResizablePanes,
11
13
  Select,
14
+ Sheet,
12
15
  Switch,
13
16
  } from '@classic-homes/theme-svelte';
14
17
  import type { ViewerRegistry } from '@classic-homes/viewer-svelte';
@@ -29,6 +32,7 @@
29
32
  import FileErrorState from './FileErrorState.svelte';
30
33
  import FileList from './FileList.svelte';
31
34
  import FilePreview from './FilePreview.svelte';
35
+ import FileTree from './FileTree.svelte';
32
36
  import type { FileBrowserContext } from './types.js';
33
37
  import { cn, isTextInput } from './utils.js';
34
38
 
@@ -43,6 +47,13 @@
43
47
  onrootchange?: (rootId: string) => void;
44
48
  /** The user opened another folder. */
45
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;
46
57
  /** Document viewers for previews, as lazy imports keyed by format. */
47
58
  viewers?: ViewerRegistry;
48
59
  /** Entries per page. Default 200. */
@@ -68,6 +79,16 @@
68
79
  toolbar?: Snippet<[FileBrowserContext]>;
69
80
  /** Per-row write actions, under the same rule as `toolbar`. */
70
81
  rowActions?: Snippet<[FileEntry, FileBrowserContext]>;
82
+ /**
83
+ * Explorer-style folder tree beside the list (drives at the top, the open
84
+ * folder's parents expanded). On phones it opens from a "Folders" button.
85
+ * Default true.
86
+ */
87
+ navigationPane?: boolean;
88
+ /** Starting width of the folder pane, in percent. Default 25. */
89
+ paneSize?: number;
90
+ /** Remember the pane width in localStorage under this key. */
91
+ paneKey?: string;
71
92
  /** Accessible name of the browser region. Default "File browser". */
72
93
  label?: string;
73
94
  locale?: string | string[];
@@ -80,6 +101,7 @@
80
101
  path = $bindable(''),
81
102
  onrootchange,
82
103
  onpathchange,
104
+ onnavigate,
83
105
  viewers = {},
84
106
  pageSize = 200,
85
107
  autoLoad = false,
@@ -91,12 +113,18 @@
91
113
  onpreview,
92
114
  toolbar,
93
115
  rowActions,
116
+ navigationPane = true,
117
+ paneSize = $bindable(25),
118
+ paneKey,
94
119
  label = 'File browser',
95
120
  locale,
96
121
  class: className,
97
122
  }: Props = $props();
98
123
 
99
124
  const uid = $props.id();
125
+ // The folder pane sits beside the list from md up; phones get a sheet instead.
126
+ const wide = new MediaQuery('(min-width: 768px)', false);
127
+ let foldersOpen = $state(false);
100
128
  const filterId = `${uid}-filter`;
101
129
  const hiddenId = `${uid}-hidden`;
102
130
 
@@ -191,6 +219,7 @@
191
219
  rootId = list[0].id;
192
220
  if (current !== undefined) path = '';
193
221
  onrootchange?.(list[0].id);
222
+ onnavigate?.({ rootId: list[0].id, path: untrack(() => currentPath) });
194
223
  }
195
224
  },
196
225
  (err) => {
@@ -348,6 +377,7 @@
348
377
  }
349
378
  path = target;
350
379
  onpathchange?.(target);
380
+ if (rootId !== undefined) onnavigate?.({ rootId, path: target });
351
381
  }
352
382
 
353
383
  function goUp() {
@@ -356,19 +386,36 @@
356
386
  navigate(parentPath(currentPath), currentPath);
357
387
  }
358
388
 
359
- function changeRoot(id: string) {
389
+ function changeRoot(id: string, nextPath = '') {
360
390
  if (id === rootId) return;
361
391
  rootId = id;
362
392
  filter = '';
363
393
  sort = null;
364
394
  selected = undefined;
365
395
  onrootchange?.(id);
366
- if (currentPath !== '') {
367
- path = '';
368
- onpathchange?.('');
396
+ if (currentPath !== nextPath) {
397
+ path = nextPath;
398
+ onpathchange?.(nextPath);
399
+ }
400
+ onnavigate?.({ rootId: id, path: nextPath });
401
+ }
402
+
403
+ /** From the folder tree: a folder in this drive, or another drive (and folder). */
404
+ function treeNavigate(id: string, next: string) {
405
+ if (foldersOpen) {
406
+ // Phone sheet: it closes, so continue in the list once it loads.
407
+ foldersOpen = false;
408
+ focusAfterLoad = true;
369
409
  }
410
+ if (id !== rootId) changeRoot(id, next);
411
+ else navigate(next);
370
412
  }
371
413
 
414
+ // A sheet left open on a phone must not reappear when the view narrows again.
415
+ $effect(() => {
416
+ if (wide.current) foldersOpen = false;
417
+ });
418
+
372
419
  function refresh() {
373
420
  attempt++;
374
421
  }
@@ -429,6 +476,7 @@
429
476
  };
430
477
  });
431
478
 
479
+ const showPane = $derived(navigationPane && wide.current && roots.length > 0);
432
480
  const rootOptions = $derived(roots.map((r) => ({ value: r.id, label: r.label })));
433
481
  const listLabel = $derived(`${folderName} contents`);
434
482
 
@@ -477,7 +525,7 @@
477
525
  {:else}
478
526
  <div class="flex flex-col gap-3 border-b border-border p-3">
479
527
  <div class="flex flex-col gap-2 sm:flex-row sm:items-center">
480
- {#if roots.length > 1}
528
+ {#if roots.length > 1 && !showPane}
481
529
  <div class="sm:w-64">
482
530
  <Select
483
531
  label="Drive"
@@ -497,7 +545,7 @@
497
545
  />
498
546
  {/if}
499
547
  </div>
500
- {#if roots.length === 1 && root?.description}
548
+ {#if root?.description && (roots.length === 1 || showPane)}
501
549
  <p class="-mt-1 text-xs text-muted-foreground">{root.description}</p>
502
550
  {/if}
503
551
 
@@ -534,77 +582,134 @@
534
582
  {@render toolbar(context)}
535
583
  </div>
536
584
  {/if}
585
+ {#if navigationPane && !wide.current && roots.length > 0}
586
+ <Button
587
+ variant="outline"
588
+ size="sm"
589
+ onclick={() => (foldersOpen = true)}
590
+ aria-haspopup="dialog"
591
+ >
592
+ <Icon name="sidebar" size={16} />
593
+ Folders
594
+ </Button>
595
+ {/if}
537
596
  <Button variant="ghost" size="icon" onclick={refresh} aria-label="Refresh">
538
597
  <Icon name="refresh" size={16} />
539
598
  </Button>
540
599
  </div>
541
600
  </div>
542
601
 
543
- <div class="flex items-center justify-between gap-2 px-3 pt-2 text-xs text-muted-foreground">
544
- <span data-file-browser-count>{countText}</span>
545
- {#if currentPath}
546
- <button
547
- type="button"
548
- class="inline-flex items-center gap-1 rounded px-1 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
549
- onclick={goUp}
550
- aria-keyshortcuts="Alt+ArrowUp Backspace"
551
- >
552
- <Icon name="corner-up-left" size={14} />
553
- Up a folder
554
- </button>
555
- {/if}
556
- </div>
557
-
558
- <div class="min-h-0 flex-1 overflow-auto">
559
- {#if status === 'error'}
560
- <FileErrorState
561
- error={listError}
562
- onretry={refresh}
563
- onroot={() => navigate('')}
564
- rootLabel={currentPath ? rootLabel : undefined}
565
- class="py-12"
566
- />
567
- {:else}
568
- <FileList
569
- bind:this={list}
570
- bind:selected
571
- bind:sort
572
- entries={shown}
573
- loading={rootsStatus === 'loading' ||
574
- status === 'loading' ||
575
- status === 'idle' ||
576
- (searching && searchStatus === 'loading' && !searchResults)}
577
- {loadingMore}
578
- {hasMore}
579
- {autoLoad}
580
- onloadmore={loadMore}
581
- onopen={open}
582
- {total}
583
- showCount={false}
584
- label={listLabel}
585
- {locale}
586
- emptyTitle={filter.trim() ? `Nothing matches “${filter.trim()}”` : 'This folder is empty'}
587
- rowActions={rowActions && caps.any ? actions : undefined}
588
- />
589
- {#if moreError}
590
- <div class="px-3 pb-3">
591
- <Alert variant="destructive">
592
- {describeFilesError(moreError).title}.
593
- <Button variant="link" size="sm" onclick={loadMore}>Try again</Button>
594
- </Alert>
602
+ {#if showPane}
603
+ <ResizablePanes
604
+ bind:size={paneSize}
605
+ min={12}
606
+ max={50}
607
+ persistKey={paneKey}
608
+ handleLabel="Resize folder pane"
609
+ class="min-h-0 flex-1"
610
+ startClass="bg-muted/20"
611
+ >
612
+ {#snippet start()}
613
+ <div class="h-full overflow-auto px-1" data-file-tree-scroll>
614
+ {@render tree()}
595
615
  </div>
596
- {/if}
597
- {/if}
598
- </div>
616
+ {/snippet}
617
+ {#snippet end()}
618
+ <div class="flex h-full min-h-0 flex-col">{@render listArea()}</div>
619
+ {/snippet}
620
+ </ResizablePanes>
621
+ {:else}
622
+ {@render listArea()}
623
+ {/if}
599
624
  {/if}
600
625
 
601
626
  <LiveRegion message={announcement} />
602
627
  </section>
603
628
 
629
+ {#snippet listArea()}
630
+ <div class="flex items-center justify-between gap-2 px-3 pt-2 text-xs text-muted-foreground">
631
+ <span data-file-browser-count>{countText}</span>
632
+ {#if currentPath}
633
+ <button
634
+ type="button"
635
+ class="inline-flex items-center gap-1 rounded px-1 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
636
+ onclick={goUp}
637
+ aria-keyshortcuts="Alt+ArrowUp Backspace"
638
+ >
639
+ <Icon name="corner-up-left" size={14} />
640
+ Up a folder
641
+ </button>
642
+ {/if}
643
+ </div>
644
+
645
+ <div class="min-h-0 flex-1 overflow-auto">
646
+ {#if status === 'error'}
647
+ <FileErrorState
648
+ error={listError}
649
+ onretry={refresh}
650
+ onroot={() => navigate('')}
651
+ rootLabel={currentPath ? rootLabel : undefined}
652
+ class="py-12"
653
+ />
654
+ {:else}
655
+ <FileList
656
+ bind:this={list}
657
+ bind:selected
658
+ bind:sort
659
+ entries={shown}
660
+ loading={rootsStatus === 'loading' ||
661
+ status === 'loading' ||
662
+ status === 'idle' ||
663
+ (searching && searchStatus === 'loading' && !searchResults)}
664
+ {loadingMore}
665
+ {hasMore}
666
+ {autoLoad}
667
+ onloadmore={loadMore}
668
+ onopen={open}
669
+ {total}
670
+ showCount={false}
671
+ label={listLabel}
672
+ {locale}
673
+ emptyTitle={filter.trim() ? `Nothing matches “${filter.trim()}”` : 'This folder is empty'}
674
+ rowActions={rowActions && caps.any ? actions : undefined}
675
+ />
676
+ {#if moreError}
677
+ <div class="px-3 pb-3">
678
+ <Alert variant="destructive">
679
+ {describeFilesError(moreError).title}.
680
+ <Button variant="link" size="sm" onclick={loadMore}>Try again</Button>
681
+ </Alert>
682
+ </div>
683
+ {/if}
684
+ {/if}
685
+ </div>
686
+ {/snippet}
687
+
688
+ {#snippet tree()}
689
+ <FileTree
690
+ {source}
691
+ {roots}
692
+ {rootId}
693
+ path={currentPath}
694
+ {showHidden}
695
+ refreshKey={attempt}
696
+ onerror={report}
697
+ onnavigate={treeNavigate}
698
+ />
699
+ {/snippet}
700
+
604
701
  {#snippet actions(entry: FileEntry)}
605
702
  {@render rowActions?.(entry, context)}
606
703
  {/snippet}
607
704
 
705
+ {#if navigationPane && !wide.current}
706
+ <Sheet bind:open={foldersOpen} side="left" size="sm" title="Folders">
707
+ <div data-file-tree-scroll class="-mx-2">
708
+ {@render tree()}
709
+ </div>
710
+ </Sheet>
711
+ {/if}
712
+
608
713
  {#if previewEntry && rootId !== undefined}
609
714
  <Dialog
610
715
  bind:open={previewOpen}
@@ -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. */
@@ -38,11 +48,21 @@ interface Props {
38
48
  toolbar?: Snippet<[FileBrowserContext]>;
39
49
  /** Per-row write actions, under the same rule as `toolbar`. */
40
50
  rowActions?: Snippet<[FileEntry, FileBrowserContext]>;
51
+ /**
52
+ * Explorer-style folder tree beside the list (drives at the top, the open
53
+ * folder's parents expanded). On phones it opens from a "Folders" button.
54
+ * Default true.
55
+ */
56
+ navigationPane?: boolean;
57
+ /** Starting width of the folder pane, in percent. Default 25. */
58
+ paneSize?: number;
59
+ /** Remember the pane width in localStorage under this key. */
60
+ paneKey?: string;
41
61
  /** Accessible name of the browser region. Default "File browser". */
42
62
  label?: string;
43
63
  locale?: string | string[];
44
64
  class?: string;
45
65
  }
46
- declare const FileBrowser: import("svelte").Component<Props, {}, "path" | "filter" | "rootId" | "showHidden">;
66
+ declare const FileBrowser: import("svelte").Component<Props, {}, "path" | "filter" | "rootId" | "showHidden" | "paneSize">;
47
67
  type FileBrowser = ReturnType<typeof FileBrowser>;
48
68
  export default FileBrowser;
@@ -0,0 +1,477 @@
1
+ <!--
2
+ @component
3
+ Explorer-style navigation pane: drives at the top level, their folders
4
+ below, loaded lazily as they expand. The open folder is highlighted and
5
+ its ancestors are expanded, so its parent and siblings are always in view.
6
+ -->
7
+ <script lang="ts">
8
+ import { tick, untrack } from 'svelte';
9
+ import { SvelteMap, SvelteSet } from 'svelte/reactivity';
10
+ import { Icon } from '@classic-homes/theme-svelte';
11
+ import {
12
+ isAbortError,
13
+ normalizePath,
14
+ pathSegments,
15
+ type FileEntry,
16
+ type FileRoot,
17
+ type FilesSource,
18
+ } from '@classic-homes/files-core';
19
+ import FileIcon from './FileIcon.svelte';
20
+ import { cn } from './utils.js';
21
+
22
+ interface Props {
23
+ source: FilesSource;
24
+ /** Drives shown at the top level. */
25
+ roots: FileRoot[];
26
+ /** Drive of the open folder. */
27
+ rootId?: string;
28
+ /** Open folder, root-relative (`''` = the drive itself). */
29
+ path?: string;
30
+ /** Include hidden folders. */
31
+ showHidden?: boolean;
32
+ /** A folder (or a drive, with `path` `''`) was chosen. */
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;
41
+ /** Accessible name of the tree. Default "Folders". */
42
+ label?: string;
43
+ class?: string;
44
+ }
45
+
46
+ let {
47
+ source,
48
+ roots,
49
+ rootId,
50
+ path = '',
51
+ showHidden = false,
52
+ onnavigate,
53
+ refreshKey,
54
+ onerror,
55
+ label = 'Folders',
56
+ class: className,
57
+ }: Props = $props();
58
+
59
+ /** Folders listed per folder; past this the tree says to open the folder instead. */
60
+ const MAX_FOLDERS = 5000;
61
+
62
+ type Status = 'loading' | 'ready' | 'error';
63
+ interface Children {
64
+ status: Status;
65
+ folders: FileEntry[];
66
+ /** More than MAX_FOLDERS subfolders: only the first are listed. */
67
+ more?: boolean;
68
+ }
69
+
70
+ /** `${rootId}|${path}` → its subfolders (`|` can't occur in SMB names). */
71
+ const children = new SvelteMap<string, Children>();
72
+ const expanded = new SvelteSet<string>();
73
+ const controllers = new Map<string, AbortController>();
74
+
75
+ const keyOf = (r: string, p: string) => `${r}|${p}`;
76
+ const currentPath = $derived.by(() => {
77
+ try {
78
+ return normalizePath(path);
79
+ } catch {
80
+ return '';
81
+ }
82
+ });
83
+ const currentKey = $derived(rootId === undefined ? '' : keyOf(rootId, currentPath));
84
+
85
+ let focusedKey = $state<string>();
86
+ let tree = $state<HTMLElement>();
87
+
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) {
93
+ const key = keyOf(r, p);
94
+ const state = children.get(key);
95
+ if (!force && state && state.status !== 'error') return;
96
+ controllers.get(key)?.abort();
97
+ const controller = new AbortController();
98
+ controllers.set(key, controller);
99
+ children.set(key, { status: 'loading', folders: state?.folders ?? [] });
100
+ const folders: FileEntry[] = [];
101
+ let more = false;
102
+ try {
103
+ let cursor: string | undefined;
104
+ for (;;) {
105
+ const page = await source.list(r, p, {
106
+ limit: 1000,
107
+ cursor,
108
+ includeHidden: showHidden,
109
+ signal: controller.signal,
110
+ });
111
+ const dirs = page.entries.filter((e) => e.type === 'dir');
112
+ folders.push(...dirs);
113
+ if (!page.nextCursor || dirs.length < page.entries.length) break;
114
+ if (folders.length >= MAX_FOLDERS) {
115
+ more = true;
116
+ break;
117
+ }
118
+ cursor = page.nextCursor;
119
+ }
120
+ if (!controller.signal.aborted) children.set(key, { status: 'ready', folders, more });
121
+ } catch (err) {
122
+ if (controller.signal.aborted || isAbortError(err)) return;
123
+ children.set(key, { status: 'error', folders: [] });
124
+ onerror?.(err);
125
+ } finally {
126
+ if (controllers.get(key) === controller) controllers.delete(key);
127
+ }
128
+ }
129
+
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).
152
+ $effect(() => {
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
+ });
174
+ });
175
+
176
+ // Reveal the open folder: expand its drive and every ancestor, and load them.
177
+ $effect(() => {
178
+ const r = rootId;
179
+ const p = currentPath;
180
+ void source;
181
+ void showHidden;
182
+ if (r === undefined || !roots.some((root) => root.id === r)) return;
183
+ untrack(() => {
184
+ const ancestors = ['', ...pathSegments(p).map((s) => s.path)];
185
+ // The open folder itself is listed by the browser; expand it here too so
186
+ // its subfolders show, as in Explorer.
187
+ for (const a of ancestors) {
188
+ expanded.add(keyOf(r, a));
189
+ void load(r, a);
190
+ }
191
+ focusedKey = keyOf(r, p);
192
+ });
193
+ void tick().then(revealCurrent);
194
+ });
195
+
196
+ interface Item {
197
+ key: string;
198
+ rootId: string;
199
+ path: string;
200
+ name: string;
201
+ level: number;
202
+ isRoot: boolean;
203
+ hidden: boolean;
204
+ setsize: number;
205
+ posinset: number;
206
+ /** A failed folder's "try again" row: a treeitem, so the keyboard reaches it. */
207
+ retry?: () => void;
208
+ }
209
+ type Row =
210
+ | { kind: 'item'; item: Item }
211
+ | { kind: 'note'; key: string; level: number; text: string };
212
+
213
+ const rows = $derived.by<Row[]>(() => {
214
+ const out: Row[] = [];
215
+ const walk = (r: string, p: string, level: number) => {
216
+ const state = children.get(keyOf(r, p));
217
+ if (!state || (state.status === 'loading' && state.folders.length === 0)) {
218
+ out.push({ kind: 'note', key: `${keyOf(r, p)}:loading`, level, text: 'Loading…' });
219
+ return;
220
+ }
221
+ if (state.status === 'error') {
222
+ out.push({
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
+ },
236
+ });
237
+ return;
238
+ }
239
+ state.folders.forEach((f, i) => {
240
+ const key = keyOf(r, f.path);
241
+ out.push({
242
+ kind: 'item',
243
+ item: {
244
+ key,
245
+ rootId: r,
246
+ path: f.path,
247
+ name: f.name,
248
+ level,
249
+ isRoot: false,
250
+ hidden: f.hidden,
251
+ setsize: state.folders.length,
252
+ posinset: i + 1,
253
+ },
254
+ });
255
+ if (expanded.has(key)) walk(r, f.path, level + 1);
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
+ }
265
+ };
266
+ roots.forEach((root, i) => {
267
+ const key = keyOf(root.id, '');
268
+ out.push({
269
+ kind: 'item',
270
+ item: {
271
+ key,
272
+ rootId: root.id,
273
+ path: '',
274
+ name: root.label,
275
+ level: 1,
276
+ isRoot: true,
277
+ hidden: false,
278
+ setsize: roots.length,
279
+ posinset: i + 1,
280
+ },
281
+ });
282
+ if (expanded.has(key)) walk(root.id, '', 2);
283
+ });
284
+ return out;
285
+ });
286
+
287
+ const items = $derived(rows.flatMap((r) => (r.kind === 'item' ? [r.item] : [])));
288
+ const tabKey = $derived(
289
+ items.some((i) => i.key === focusedKey)
290
+ ? focusedKey
291
+ : (items.find((i) => i.key === currentKey) ?? items[0])?.key
292
+ );
293
+
294
+ /** Known to have no subfolders (loaded and empty), or a retry row. */
295
+ function isLeaf(item: Item): boolean {
296
+ if (item.retry) return true;
297
+ const state = children.get(item.key);
298
+ return state?.status === 'ready' && state.folders.length === 0;
299
+ }
300
+
301
+ function toggle(item: Item, open?: boolean) {
302
+ const willOpen = open ?? !expanded.has(item.key);
303
+ if (willOpen) {
304
+ expanded.add(item.key);
305
+ void load(item.rootId, item.path);
306
+ } else {
307
+ expanded.delete(item.key);
308
+ }
309
+ }
310
+
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
+ }
319
+ focusedKey = item.key;
320
+ onnavigate?.(item.rootId, item.path);
321
+ }
322
+
323
+ function el(key: string | undefined): HTMLElement | null {
324
+ if (!tree || key === undefined) return null;
325
+ for (const node of tree.querySelectorAll<HTMLElement>('[role="treeitem"]')) {
326
+ if (node.dataset.key === key) return node;
327
+ }
328
+ return null;
329
+ }
330
+
331
+ async function focusItem(item: Item | undefined) {
332
+ if (!item) return;
333
+ focusedKey = item.key;
334
+ await tick();
335
+ const node = el(item.key);
336
+ node?.focus({ preventScroll: true });
337
+ if (node) scrollIntoPane(node);
338
+ }
339
+
340
+ /** Scroll inside the pane only, never the page. */
341
+ function scrollIntoPane(node: HTMLElement) {
342
+ const pane = tree?.closest<HTMLElement>('[data-file-tree-scroll]') ?? tree?.parentElement;
343
+ if (!pane) return;
344
+ const p = pane.getBoundingClientRect();
345
+ const r = node.getBoundingClientRect();
346
+ if (r.top < p.top) pane.scrollTop -= p.top - r.top + 8;
347
+ else if (r.bottom > p.bottom) pane.scrollTop += r.bottom - p.bottom + 8;
348
+ }
349
+
350
+ function revealCurrent() {
351
+ const node = el(currentKey);
352
+ if (node) scrollIntoPane(node);
353
+ }
354
+
355
+ function onkeydown(event: KeyboardEvent, item: Item) {
356
+ const index = items.findIndex((i) => i.key === item.key);
357
+ const open = expanded.has(item.key);
358
+ switch (event.key) {
359
+ case 'ArrowDown':
360
+ event.preventDefault();
361
+ void focusItem(items[index + 1]);
362
+ break;
363
+ case 'ArrowUp':
364
+ if (event.altKey) return; // "up a folder" belongs to the browser
365
+ event.preventDefault();
366
+ void focusItem(items[index - 1]);
367
+ break;
368
+ case 'Home':
369
+ event.preventDefault();
370
+ void focusItem(items[0]);
371
+ break;
372
+ case 'End':
373
+ event.preventDefault();
374
+ void focusItem(items[items.length - 1]);
375
+ break;
376
+ case 'ArrowRight':
377
+ event.preventDefault();
378
+ if (isLeaf(item)) break;
379
+ if (!open) toggle(item, true);
380
+ else if (items[index + 1]?.level === item.level + 1) void focusItem(items[index + 1]);
381
+ break;
382
+ case 'ArrowLeft': {
383
+ event.preventDefault();
384
+ if (open && !isLeaf(item)) {
385
+ toggle(item, false);
386
+ break;
387
+ }
388
+ for (let i = index - 1; i >= 0; i--) {
389
+ if (items[i].level === item.level - 1) {
390
+ void focusItem(items[i]);
391
+ break;
392
+ }
393
+ }
394
+ break;
395
+ }
396
+ case 'Enter':
397
+ case ' ':
398
+ event.preventDefault();
399
+ choose(item);
400
+ break;
401
+ }
402
+ }
403
+ </script>
404
+
405
+ <ul
406
+ bind:this={tree}
407
+ role="tree"
408
+ aria-label={label}
409
+ class={cn('select-none py-1 text-sm', className)}
410
+ data-file-tree
411
+ >
412
+ {#each rows as row (row.kind === 'item' ? row.item.key : row.key)}
413
+ {#if row.kind === 'note'}
414
+ <li
415
+ role="none"
416
+ style:padding-left="{row.level * 0.875 + 0.5}rem"
417
+ class="py-1 text-xs text-muted-foreground"
418
+ >
419
+ {row.text}
420
+ </li>
421
+ {:else}
422
+ {@const item = row.item}
423
+ {@const open = expanded.has(item.key)}
424
+ {@const leaf = isLeaf(item)}
425
+ {@const current = item.key === currentKey}
426
+ <li
427
+ role="treeitem"
428
+ data-key={item.key}
429
+ aria-level={item.level}
430
+ aria-setsize={item.setsize}
431
+ aria-posinset={item.posinset}
432
+ aria-expanded={leaf ? undefined : open}
433
+ aria-selected={current}
434
+ aria-current={current ? 'location' : undefined}
435
+ tabindex={item.key === tabKey ? 0 : -1}
436
+ class={cn(
437
+ 'flex cursor-pointer items-center gap-1 rounded-sm py-1 pr-2 outline-none',
438
+ 'focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring',
439
+ current ? 'bg-chart-1/15 font-medium text-foreground' : 'hover:bg-muted/60',
440
+ // Hidden folders: muted and italic, not faded (opacity fails contrast).
441
+ item.hidden && 'italic text-muted-foreground'
442
+ )}
443
+ style:padding-left="{(item.level - 1) * 0.875 + 0.25}rem"
444
+ title={item.name}
445
+ onclick={() => choose(item)}
446
+ onkeydown={(e) => onkeydown(e, item)}
447
+ onfocus={() => (focusedKey = item.key)}
448
+ >
449
+ <!-- Chevron: expand/collapse without opening (as in Explorer). Keyboard: Right/Left. -->
450
+ <!-- svelte-ignore a11y_click_events_have_key_events, a11y_no_static_element_interactions -->
451
+ <span
452
+ class={cn(
453
+ 'flex h-5 w-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-muted',
454
+ leaf && 'invisible'
455
+ )}
456
+ aria-hidden="true"
457
+ onclick={(e) => {
458
+ e.stopPropagation();
459
+ toggle(item);
460
+ }}
461
+ >
462
+ <Icon name={open ? 'chevron-down' : 'chevron-right'} size={14} />
463
+ </span>
464
+ {#if item.retry}
465
+ <Icon name="refresh" size={14} class="shrink-0 text-muted-foreground" />
466
+ {:else if item.isRoot}
467
+ <Icon name="home" size={16} class="shrink-0 text-muted-foreground" />
468
+ {:else}
469
+ <FileIcon type="dir" size={16} />
470
+ {/if}
471
+ <span class={cn('truncate', item.retry && 'text-xs text-muted-foreground underline')}
472
+ >{item.name}</span
473
+ >
474
+ </li>
475
+ {/if}
476
+ {/each}
477
+ </ul>
@@ -0,0 +1,32 @@
1
+ import { type FileRoot, type FilesSource } from '@classic-homes/files-core';
2
+ interface Props {
3
+ source: FilesSource;
4
+ /** Drives shown at the top level. */
5
+ roots: FileRoot[];
6
+ /** Drive of the open folder. */
7
+ rootId?: string;
8
+ /** Open folder, root-relative (`''` = the drive itself). */
9
+ path?: string;
10
+ /** Include hidden folders. */
11
+ showHidden?: boolean;
12
+ /** A folder (or a drive, with `path` `''`) was chosen. */
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;
21
+ /** Accessible name of the tree. Default "Folders". */
22
+ label?: string;
23
+ class?: string;
24
+ }
25
+ /**
26
+ * Explorer-style navigation pane: drives at the top level, their folders
27
+ * below, loaded lazily as they expand. The open folder is highlighted and
28
+ * its ancestors are expanded, so its parent and siblings are always in view.
29
+ */
30
+ declare const FileTree: import("svelte").Component<Props, {}, "">;
31
+ type FileTree = ReturnType<typeof FileTree>;
32
+ export default FileTree;
@@ -1,6 +1,7 @@
1
1
  export { default as FileBrowser } from './FileBrowser.svelte';
2
2
  export { default as FileList } from './FileList.svelte';
3
3
  export { default as FileBreadcrumbs } from './FileBreadcrumbs.svelte';
4
+ export { default as FileTree } from './FileTree.svelte';
4
5
  export { default as FileIcon } from './FileIcon.svelte';
5
6
  export { default as FilePreview } from './FilePreview.svelte';
6
7
  export { default as FileDetails } from './FileDetails.svelte';
package/dist/lib/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  export { default as FileBrowser } from './FileBrowser.svelte';
2
2
  export { default as FileList } from './FileList.svelte';
3
3
  export { default as FileBreadcrumbs } from './FileBreadcrumbs.svelte';
4
+ export { default as FileTree } from './FileTree.svelte';
4
5
  export { default as FileIcon } from './FileIcon.svelte';
5
6
  export { default as FilePreview } from './FilePreview.svelte';
6
7
  export { default as FileDetails } from './FileDetails.svelte';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@classic-homes/files-svelte",
3
- "version": "0.1.0",
3
+ "version": "0.3.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",