summaryrefslogtreecommitdiffstats
path: root/packages/meshbay-hub/src/meshbay_hub/static/files-app.js
blob: 762945999f669594c4d13f0e4b92795c2753a79f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
import {
  html, useState, useEffect, useRef, useCallback,
} from './vendor/htm-preact.js';
import { t } from './i18n.js';
import { Icon } from './icon.js';
import { entriesUnder } from './zipstream.js';
import { transfers } from './transfers.js';
import {
  FILE_ICONS, formatSize, formatDate, canPreview, CHUNK_SIZE, MEMORY_CEILING,
  pipelinedDownload, downloadEntry, downloadDirectory as sharedDownloadDirectory,
} from './file-utils.js';
import { useStickyBand } from './sticky.js';

// ── Files ────────────────────────────────────────────────────────────────────
//
// The group's file browser: toolbar (upload, mkdir, filter, select), the
// table itself, and every file/directory operation. `entries`/`nodeDirs`/
// `nodeRoots` are owned by the group shell (group-page.js) — Chat needs the
// same index for its image attachments — and handed down here read-only
// alongside `applyIndex`/the raw setters to write back through, the same
// shape ChatPanel already takes for `onRefreshIndex`.
//
// `onPreview` opens a file in the shell's video/preview modal rather than
// this component owning that state itself, again because more than one tab
// (Chat's attachments) can trigger it.

// ── Dropping files and folders ───────────────────────────────────────────────

// The node's SAFE_UPLOAD_NAME (roots.py), for files and folder names alike.
// Checked before anything is sent, so a dropped folder holding one name the
// node refuses is refused whole instead of arriving with holes in it. The node
// still decides; `test_files_drop_upload.py` holds the two to the same answers.
const UPLOAD_NAME = /^[\p{L}\p{N}][\p{L}\p{N}_ .\-()[\]'’,&+#@]{0,127}(?<![ .])$/u;

// How many dropped files are handed to the transfer store at once. The node
// queues at most 32 transfers per member (transfers.py) and refuses past that,
// so a folder of a few hundred files is fed in as earlier ones finish.
const UPLOAD_BATCH = 8;

// The names already in folder `dir`, files and folders both — from the index
// and the node's own directory listing, so an empty folder counts.
function namesIn(entries, nodeDirs, dir) {
  const names = new Set();
  const prefix = dir + '/';
  for (const e of entries) {
    const p = e.path || '';
    if (p === dir) names.add(e.name);
    else if (p.startsWith(prefix)) names.add(p.slice(prefix.length).split('/')[0]);
  }
  for (const d of nodeDirs) {
    if (d.startsWith(prefix)) names.add(d.slice(prefix.length).split('/')[0]);
  }
  return [...names];
}

// What a drop would do, decided before any of it is done. `items` are
// `{ kind: 'file'|'dir', path }` relative to the folder dropped into.
//
// A name already there refuses the whole drop. Left to the node, a colliding
// file is stored under a free name ("x (1).jpg") and a colliding folder is
// refused half-way through, after the folders before it were made — neither is
// what anyone dropping a file expects. Compared without case, because on
// NTFS and exFAT roots the two *are* the same name.
function planDrop(items, existing) {
  const taken = new Set(existing.map((n) => n.toLowerCase()));
  const tops = [...new Set(items.map((i) => i.path.split('/')[0]))];
  const conflicts = tops.filter((n) => taken.has(n.toLowerCase())).sort();
  const invalid = [...new Set(items.flatMap((i) => i.path.split('/')))]
    .filter((n) => !UPLOAD_NAME.test(n)).sort();
  // Every folder, including one only implied by a file's path, parents first:
  // the node creates one level at a time.
  const dirs = new Set();
  for (const i of items) {
    const parts = i.path.split('/');
    const depth = i.kind === 'dir' ? parts.length : parts.length - 1;
    for (let d = 1; d <= depth; d++) dirs.add(parts.slice(0, d).join('/'));
  }
  const orderedDirs = [...dirs].sort((a, b) =>
    (a.split('/').length - b.split('/').length) || a.localeCompare(b));
  return { conflicts, invalid, dirs: orderedDirs, files: items.filter((i) => i.kind === 'file') };
}

// The dropped entries, which must be taken during the drop event itself: the
// DataTransfer is emptied as soon as the handler returns.
function droppedEntries(dataTransfer) {
  return [...(dataTransfer.items || [])]
    .filter((it) => it.kind === 'file' && it.webkitGetAsEntry)
    .map((it) => it.webkitGetAsEntry())
    .filter(Boolean);
}

async function walkEntries(roots) {
  const out = [];
  const visit = async (entry, prefix) => {
    const path = prefix ? `${prefix}/${entry.name}` : entry.name;
    if (entry.isFile) {
      const file = await new Promise((resolve, reject) => entry.file(resolve, reject));
      out.push({ kind: 'file', path, file });
    } else if (entry.isDirectory) {
      out.push({ kind: 'dir', path });
      const reader = entry.createReader();
      // readEntries answers in batches (a hundred in Chromium) until it
      // answers with none.
      for (;;) {
        const batch = await new Promise((resolve, reject) => reader.readEntries(resolve, reject));
        if (!batch.length) break;
        for (const child of batch) await visit(child, path);
      }
    }
  };
  for (const root of roots) await visit(root, '');
  return out;
}

// One ordering for the whole listing. Folders stay above files and are ordered
// among themselves by the same column: a folder's size is everything under it,
// its date the newest file in it. It has no type, so sorted by type folders
// fall back to their names. Rows are `{ name, size, date, type }`; a tie goes
// to the name, ascending, so equal sizes do not shuffle between renders.
//
// Folders used to be `[...dirs].sort()` whatever the column — so reversing the
// name sort or sorting by size moved the files and left every folder where it
// was, which in a folder of folders is nothing moving at all.
function sortRows(rows, key, asc) {
  const byName = (a, b) => (a.name || '').localeCompare(b.name || '');
  return [...rows].sort((a, b) => {
    let cmp;
    if (key === 'size') cmp = (a.size || 0) - (b.size || 0);
    else if (key === 'date') cmp = (a.date || 0) - (b.date || 0);
    else if (key === 'type') cmp = (a.type || '').localeCompare(b.type || '');
    else cmp = byName(a, b);
    if (!asc) cmp = -cmp;
    return cmp || byName(a, b);
  });
}

function FilesPanel({
  groupId, transportRef, gekRef, status,
  entries, nodeDirs, nodeRoots, setEntries, setNodeDirs, setNodeRoots, applyIndex,
  isNodeAdmin, operatorPaired, userId, setError, onPreview,
  showGroup, readOnly, getTransport, onRefreshIndex, showRefresh,
}) {
  const [selected, setSelected] = useState(() => new Set());
  const [sortKey, setSortKey] = useState('name');
  const [sortAsc, setSortAsc] = useState(true);
  const [filter, setFilter] = useState('');
  const [currentPath, setCurrentPath] = useState('');
  const [refreshing, setRefreshing] = useState(false);
  // The toolbar pins below the page's own band and tells the column heads how
  // far down to pin. Its height is not a constant — it wraps to three rows on
  // a phone and grows a field while a folder is being named — so it is
  // measured rather than written down (sticky.js).
  const toolbarBand = useStickyBand('--toolbar-h');

  // Only the cross-group Search page shows this (`showRefresh`): it has no
  // live node connection pushing index deltas, so its file list really is
  // a one-shot cached fetch. In a real group the node streams every change
  // as it happens, so a manual re-fetch would just duplicate that.
  const doRefresh = useCallback(async () => {
    if (refreshing || !onRefreshIndex) return;
    setRefreshing(true);
    try { await onRefreshIndex(); } finally { setRefreshing(false); }
  }, [refreshing, onRefreshIndex]);

  // A directory from the group just left rarely exists in the one just
  // entered (e.g. "outputs" in one group, absent in another) — Files would
  // otherwise show that stale path and list nothing.
  useEffect(() => { setCurrentPath(''); setSelected(new Set()); setFilter(''); }, [groupId]);

  const downloadFile = useCallback(async (entry) => {
    let transport, gek;
    if (getTransport) {
      try {
        const conn = await getTransport(entry);
        transport = conn.transport;
        gek = conn.gek;
      } catch {
        setError(t('search.unreachable', { n: 1 }));
        return;
      }
    } else {
      transport = transportRef.current;
      gek = gekRef.current;
    }
    // Never a silent return. A click that produces nothing at all — no
    // transfer, no icon, no message — is indistinguishable from a broken
    // button, and it is what a download looks like whenever the WebRTC
    // connection is not up: on a screen lock, mid-reconnect, or after the node
    // restarted. Say so instead.
    if (!transport || !transport.connected) {
      setError(t('group.download_offline'));
      return;
    }
    await downloadEntry(transfers, transport, gek, entry);
  }, [getTransport]);

  // `jobs` are `{ file, dir }`, all under one root. Fed to the transfer store
  // UPLOAD_BATCH at a time; the Upload button's few files simply all fit in
  // the first batch.
  const startUploads = useCallback((jobs, { root }) => {
    const transport = transportRef.current;
    if (!jobs.length || !transport || !transport.connected) return;
    setError('');

    let next = 0;
    let live = 0;
    let stopped = false;
    let refreshTimer = null;
    // The node re-indexes on a filesystem event, so there is nothing to wait
    // on but the clock. Refreshing means the file appears in the list without
    // anyone reloading — once for a burst, not once per file of a folder.
    const refresh = () => {
      clearTimeout(refreshTimer);
      refreshTimer = setTimeout(async () => {
        try { if (transport.connected) applyIndex(await transport.fetchIndex()); } catch { /* next one */ }
      }, 2500);
    };
    const pump = () => {
      while (!stopped && live < UPLOAD_BATCH && next < jobs.length) {
        if (!transport.connected) { stopped = true; return; }
        const { file, dir } = jobs[next++];
        live += 1;
        const id = transfers.start({
          kind: 'upload', name: file.name, total: file.size, transport,
          // `makeLease`, not `lease`: pausing gives the slot back, so resuming
          // has to be able to ask for another one, and a transfer handed a lease
          // it cannot re-create is refused the button rather than offered one
          // that would drop its slot for good.
          makeLease: () => transport.openTransfer({ kind: 'upload',
                                                    bytes: file.size }),
          // A `File` is seekable and the node remembers how much it holds, so
          // there is no target tier to consult here — unlike a download.
          pausable: true,
          run: async ({ signal, onProgress, lease }) => {
            await transport.uploadFile(file, {
              // Bytes the node acknowledged, not bytes read locally.
              onProgress: (sent) => onProgress(sent, file.size),
              signal,
              root,
              dir,
              tr: lease && lease.tr,
            });
          },
        });
        transfers.settled(id).then((finalStatus) => {
          live -= 1;
          refresh();
          // Deferred, so that "cancel all" — every live transfer ending in the
          // same tick — is seen as that, and the rest of the folder is not
          // started behind it. Cancelling one file lets the others go on.
          setTimeout(() => {
            if (finalStatus === 'cancelled' && live === 0) stopped = true;
            pump();
          }, 0);
        });
      }
    };
    pump();
  }, [applyIndex]);

  const uploadFile = useCallback((e) => {
    const files = [...(e.target.files || [])];
    e.target.value = '';
    // The folder on screen is the destination — not its root, and not a
    // subdirectory of the node's invention. Somebody dropping a file into the
    // folder they are looking at expects it to be in that folder.
    const uploadDir = currentPath;
    if (!uploadDir) return;
    const uploadRoot = uploadDir.split('/')[0];
    startUploads(files.map((file) => ({ file, dir: uploadDir })), { root: uploadRoot });
  }, [startUploads, currentPath]);

  // `null` while not creating one; a draft string while the field is open.
  const [newDirName, setNewDirName] = useState(null);
  const [creatingDir, setCreatingDir] = useState(false);

  /**
   * Create a folder in the directory being browsed.
   *
   * The name comes from a field in the toolbar rather than `window.prompt`,
   * which **throws** in Electron — "prompt() is not supported" — and threw
   * outside this function's try, so clicking the button did nothing at all:
   * no folder, no error, nothing in the interface to react to. `confirm()` and
   * `alert()` do work there and are used elsewhere; `prompt` is the one
   * Chromium leaves to the embedder and Electron declines to implement.
   *
   * An inline field is better anyway — it can show the refusal next to the
   * input instead of after the dialog has closed.
   */
  useEffect(() => { setNewDirName(null); }, [currentPath]);

  const makeDirectory = useCallback(async (rawName) => {
    const transport = transportRef.current;
    const name = (rawName || '').trim();
    if (!name) return;
    if (!transport || !transport.connected) {
      setError(t('group.mkdir_offline'));
      return;
    }
    setCreatingDir(true);
    try {
      await transport.createDirectory(currentPath, name);
      // `list_dirs` walks the filesystem rather than the index, so a folder
      // with nothing in it is here on this very fetch.
      const indexMsg = await transport.fetchIndex();
      if (indexMsg.entries) setEntries(indexMsg.entries);
      if (indexMsg.dirs) setNodeDirs(indexMsg.dirs);
      if (indexMsg.roots) setNodeRoots(indexMsg.roots);
      setNewDirName(null);
    } catch (err) {
      setError(err.message);
    } finally {
      setCreatingDir(false);
    }
  }, [currentPath]);

  // The implementation lives in file-utils.js (docs/photos.md §3) so
  // photos-app.js's own "zip this album" button can call the same code
  // rather than a second one.
  const downloadDirectory = useCallback(async (dir) => {
    const transport = transportRef.current;
    await sharedDownloadDirectory(
      transfers, transport, gekRef.current, entries, dir, { setError });
  }, [entries]);

  const deleteDirectory = useCallback(async (dir) => {
    const transport = transportRef.current;
    if (!transport || !transport.connected) return;
    try {
      const sk = transport.sessionKeys && transport.sessionKeys.skEdB64;
      const signFn = (sk && window.MeshBayKeys)
        ? (transcript) => window.MeshBayKeys.signBytes(sk, transcript)
        : null;
      await transport.deleteDirectory(dir, signFn);
      applyIndex(await transport.fetchIndex());
    } catch (err) {
      setError(err.message);
    }
  }, [applyIndex]);

  const deleteFile = useCallback(async (entry) => {
    const transport = transportRef.current;
    if (!transport || !transport.connected) return;
    try {
      // Signs an explicit transcript built by transport.js, not opaque bytes from
      // the node — see MeshBayCrypto.adminTranscript and finding H5.
      // Signed with the identity this node pinned for us — the only one it
      // will accept, and the only one we hold here.
      const sk = transport.sessionKeys && transport.sessionKeys.skEdB64;
      const signFn = (sk && window.MeshBayKeys)
        ? (transcript) => window.MeshBayKeys.signBytes(sk, transcript)
        : null;
      await transport.deleteFile(entry.id, signFn);
      applyIndex(await transport.fetchIndex());
    } catch (err) {
      setError(err.message);
    }
  }, [applyIndex]);

  const toggleSort = useCallback((key) => {
    setSortAsc(prev => sortKey === key ? !prev : true);
    setSortKey(key);
  }, [sortKey]);

  // With text in the field the user is searching, not browsing: match every
  // file in the whole group, wherever it lives, by name or by the folder it
  // sits in — and hide the folder rows, there is nothing to walk into. The
  // old code only ever filtered files whose folder was exactly `currentPath`,
  // so at the top of a group — where the rows are roots, never loose files —
  // typing did nothing at all.
  const q = filter.trim().toLowerCase();
  const dirs = new Set();
  const filteredEntries = entries.filter(e => {
    const ePath = e.path || '';
    if (q) {
      return (e.name || '').toLowerCase().includes(q)
          || ePath.toLowerCase().includes(q);
    }
    if (ePath === currentPath) return true;
    if (!currentPath && ePath) {
      dirs.add(ePath.split('/')[0]);
    } else if (currentPath && ePath.startsWith(currentPath + '/')) {
      const rest = ePath.slice(currentPath.length + 1);
      dirs.add(rest.split('/')[0]);
    }
    return false;
  });

  const sorted = sortRows(
    filteredEntries.map((e) => ({ name: e.name, size: e.size, date: e.added_at, type: e.type, entry: e })),
    sortKey, sortAsc).map((r) => r.entry);

  // The node's own listing, so an empty folder is visible, plus anything implied
  // by a file path in case the two ever disagree. Skipped while searching — the
  // results are a flat list of matches, not a folder view.
  if (!q) for (const d of nodeDirs) {
    if (!currentPath && !d.includes('/')) dirs.add(d);
    else if (currentPath && d.startsWith(currentPath + '/')) {
      const rest = d.slice(currentPath.length + 1);
      if (!rest.includes('/')) dirs.add(rest);
    }
  }
  // What each folder holds, once — its size and date are sort keys now, not
  // only the figure in its row.
  const dirInfo = new Map([...dirs].map((d) => {
    const inside = entriesUnder(entries, currentPath ? currentPath + '/' + d : d);
    return [d, {
      inside,
      bytes: inside.reduce((n, f) => n + (f.entry.size || 0), 0),
      newest: inside.reduce((n, f) => Math.max(n, f.entry.added_at || 0), 0),
    }];
  }));
  const subdirs = sortRows(
    [...dirs].map((d) => ({ name: d, size: dirInfo.get(d).bytes, date: dirInfo.get(d).newest })),
    sortKey, sortAsc).map((r) => r.name);

  // At the top of a group the folders on screen ARE the roots, so their state
  // belongs there. Deeper in, everything shown lives inside one readable root
  // and there is nothing to flag.
  const rootState = new Map(nodeRoots.map(r => [r.name, r]));
  const unavailableHere = currentPath
    ? []
    : subdirs.filter(d => rootState.get(d) && rootState.get(d).available === false);
  const currentRootName = currentPath ? currentPath.split('/')[0] : '';
  const currentRoot = currentRootName ? rootState.get(currentRootName) : null;
  const currentRootWritable = currentRoot ? Boolean(currentRoot.writable)
                                          : false;
  // A member cannot create a folder at the top of a group: that level is the
  // set of roots, which is the operator's configuration and not a directory on
  // anyone's disk. The node refuses it, so offering it would only produce an
  // error nobody can act on.
  //
  // Otherwise the rule is the same as the Upload button's, and for the same
  // reason the node gives: "making a directory is not a privileged act — a
  // member who can add a file can organise where it goes". It used to require
  // `isNodeAdmin`, which contradicted the node and hid the control from
  // everyone who could actually use it.
  const canCreateDir = Boolean(currentPath) && currentRootWritable && !readOnly;

  // Dropping files and folders in, under the same rule as Upload and New
  // folder — a folder on screen, in a writable root, in a group.
  //
  // Taken on the window rather than on the table: an empty folder has almost no
  // table to aim at, and a file released a few pixels off a drop zone is opened
  // by the browser in place of the group. So every file drag over this tab is
  // caught, and the overlay says where it will land or why it will not.
  const canDropHere = canCreateDir && status === 'connected';
  const [dragging, setDragging] = useState(false);
  const dropRef = useRef(null);
  dropRef.current = {
    canDropHere,
    drop: async (roots, looseFiles) => {
      if (!canDropHere) return;
      const dir = currentPath;
      const transport = transportRef.current;
      if (!transport || !transport.connected) { setError(t('group.mkdir_offline')); return; }
      let items;
      try {
        items = roots.length
          ? await walkEntries(roots)
          // No entry API: plain files only, which is what such a browser offers.
          : looseFiles.map((file) => ({ kind: 'file', path: file.name, file }));
      } catch {
        setError(t('group.drop_unreadable'));
        return;
      }
      if (!items.length) return;

      const plan = planDrop(items, namesIn(entries, nodeDirs, dir));
      if (plan.conflicts.length) {
        setError(t('group.drop_conflict', { names: plan.conflicts.join(', ') }));
        return;
      }
      if (plan.invalid.length) {
        setError(t('group.drop_invalid', { names: plan.invalid.join(', ') }));
        return;
      }
      setError('');

      if (plan.dirs.length) {
        try {
          for (const d of plan.dirs) {
            const cut = d.lastIndexOf('/');
            await transport.createDirectory(cut < 0 ? dir : `${dir}/${d.slice(0, cut)}`,
                                            d.slice(cut + 1));
          }
        } catch (err) {
          setError(t('group.drop_mkdir_failed', { detail: err.message }));
          return;
        } finally {
          try { applyIndex(await transport.fetchIndex()); } catch { /* the uploads refresh it */ }
        }
      }
      startUploads(plan.files.map((f) => {
        const cut = f.path.lastIndexOf('/');
        return { file: f.file, dir: cut < 0 ? dir : `${dir}/${f.path.slice(0, cut)}` };
      }), { root: dir.split('/')[0] });
    },
  };

  useEffect(() => {
    if (readOnly) return undefined;
    let depth = 0;
    const carriesFiles = (e) => [...((e.dataTransfer && e.dataTransfer.types) || [])]
      .includes('Files');
    const onEnter = (e) => {
      if (!carriesFiles(e)) return;
      e.preventDefault();
      depth += 1;
      setDragging(true);
    };
    const onOver = (e) => {
      if (!carriesFiles(e)) return;
      e.preventDefault();
      e.dataTransfer.dropEffect = dropRef.current.canDropHere ? 'copy' : 'none';
    };
    const onLeave = (e) => {
      if (!carriesFiles(e)) return;
      depth = Math.max(0, depth - 1);
      if (!depth) setDragging(false);
    };
    const onDrop = (e) => {
      if (!carriesFiles(e)) return;
      e.preventDefault();
      depth = 0;
      setDragging(false);
      const roots = droppedEntries(e.dataTransfer);
      const looseFiles = [...(e.dataTransfer.files || [])];
      dropRef.current.drop(roots, looseFiles).catch((err) => setError(err.message));
    };
    window.addEventListener('dragenter', onEnter);
    window.addEventListener('dragover', onOver);
    window.addEventListener('dragleave', onLeave);
    window.addEventListener('drop', onDrop);
    return () => {
      window.removeEventListener('dragenter', onEnter);
      window.removeEventListener('dragover', onOver);
      window.removeEventListener('dragleave', onLeave);
      window.removeEventListener('drop', onDrop);
    };
  }, [readOnly]);

  const breadcrumbs = currentPath ? currentPath.split('/') : [];

  // Selection is keyed globally — file ids, and 'dir:' plus a full path — so
  // walking into another folder keeps what was already ticked.
  const dirKey = (name) => 'dir:' + (currentPath ? currentPath + '/' + name : name);
  const selectedFiles = entries.filter(e => selected.has(e.id));
  const selectedDirs = [...selected]
    .filter(k => typeof k === 'string' && k.startsWith('dir:'))
    .map(k => k.slice(4));
  const toggle = (key) => setSelected(prev => {
    const next = new Set(prev);
    if (next.has(key)) next.delete(key); else next.add(key);
    return next;
  });

  const allVisibleKeys = [...subdirs.map(d => dirKey(d)), ...sorted.map(e => e.id)];
  const allSelected = allVisibleKeys.length > 0 && allVisibleKeys.every(k => selected.has(k));
  const someSelected = allVisibleKeys.some(k => selected.has(k));
  const toggleAll = () => {
    if (allSelected) {
      setSelected(new Set());
    } else {
      setSelected(prev => {
        const next = new Set(prev);
        for (const k of allVisibleKeys) next.add(k);
        return next;
      });
    }
  };

  const onlyFile = selectedFiles.length === 1 && selectedDirs.length === 0
    ? selectedFiles[0] : null;
  const deletableFiles = selectedFiles.filter(
    e => isNodeAdmin || (userId && e.uploader_id === userId));

  const run = (fn) => {
    setSelected(new Set());
    Promise.resolve().then(fn).catch(err => {
      if (err && err.name !== 'AbortError') setError(err.message);
    });
  };

  // Icon only, with the name in the tooltip: these sit in a toolbar that is
  // already narrow, and every one of them is a verb the icon carries on its
  // own. `title` gives the hover text and `aria-label` the accessible name —
  // an icon button with neither is unusable with a screen reader.
  //
  // Every action is rendered as soon as Select is on, and the ones that do not
  // apply are disabled rather than absent. Buttons appearing and vanishing as
  // the selection changed made the bar jump about and gave no clue that an
  // action existed at all before something was ticked.
  const action = (icon, label, onClick, opts = {}) => html`
    <button class="tb-icon-btn ${opts.danger ? 'danger' : ''}"
      title=${label} aria-label=${label}
      disabled=${!!opts.disabled} onClick=${onClick}>
      <${Icon} name=${icon} />
    </button>
  `;

  const canPlay = !!(onlyFile && (onlyFile.type === 'video' || onlyFile.type === 'audio'));
  const canView = !!(onlyFile && onlyFile.type !== 'video' && onlyFile.type !== 'audio'
    && canPreview(onlyFile));
  const deletableCount = deletableFiles.length
    + (operatorPaired ? selectedDirs.length : 0);
  // The operator can always delete; anyone else only ever sees the button if
  // something here is theirs to remove. Hiding it from an uploader would take
  // away a right the protocol grants them (draft-v5 §5.1), not just a control.
  const mayEverDelete = isNodeAdmin
    || (userId && entries.some(e => e.uploader_id === userId));

  const actionItems = html`
    ${action('play', t('group.play'),
      () => run(() => onPreview(onlyFile)), { disabled: !canPlay })}
    ${action('eye', t('group.view'),
      () => run(() => onPreview(onlyFile)), { disabled: !canView })}
    ${action('download',
      selectedFiles.length
        ? t('group.download_n', { n: selectedFiles.length })
        : t('group.download'),
      () => run(async () => {
        // Awaited one at a time, and each returns as soon as its transfer is
        // registered — so the transfers still run together. Firing them without
        // awaiting meant every file asked the browser for a save dialog at
        // once, and a browser allows one: the rest were rejected and only the
        // first file ever downloaded.
        for (const e of selectedFiles) await downloadFile(e);
      }), { disabled: selectedFiles.length === 0 })}
    ${!readOnly && action('archive',
      selectedDirs.length
        ? t('group.download_zip_n', { n: selectedDirs.length })
        : t('group.download_zip_n', { n: 0 }),
      () => run(async () => {
        for (const d of selectedDirs) await downloadDirectory(d);
      }), { disabled: selectedDirs.length === 0 })}
    ${mayEverDelete && !readOnly && action('trash',
      deletableCount ? t('group.delete_n', { n: deletableCount }) : t('group.delete'),
      () => {
        const names = [...deletableFiles.map(e => e.name),
                       ...(operatorPaired ? selectedDirs : [])];
        if (!confirm(t('group.delete_n_confirm', { n: names.length,
                                                   names: names.join(', ') }))) return;
        run(() => {
          for (const e of deletableFiles) deleteFile(e);
          if (operatorPaired) for (const d of selectedDirs) deleteDirectory(d);
        });
      },
      { danger: true, disabled: status !== 'connected' || deletableCount === 0 })}
  `;

  return html`
    ${(status === 'discovering' || status === 'connecting' || status === 'fetching') && html`
      <p class="page-message"><span class="spinner"></span>${' '}${t('status.connecting_short')}</p>
    `}
    ${status === 'offline' && html`
      <p class="page-message">${t('group.offline_title')} ${t('group.offline_hint')}</p>
    `}

    ${status === 'connected' && html`
      <div class="file-toolbar" ref=${toolbarBand}>
        <div class="toolbar-group">
          ${currentPath && currentRootWritable && html`
          <label class="tb-btn primary">
            <${Icon} name="upload" /> ${t('group.upload')}
            <input type="file" multiple style="display:none"
              onChange=${uploadFile} />
          </label>
          `}
          ${/* Icon only: the toolbar already carries a labelled primary
                action, and a second one beside it competes with it for the
                width a breadcrumb trail needs. The name lives in the tooltip
                and in aria-label, so it is not lost to anyone reading with
                something other than their eyes. */''}
          ${canCreateDir && newDirName === null && html`
          <button class="tb-btn tb-btn-icon" onClick=${() => setNewDirName('')}
            title=${t('group.mkdir')} aria-label=${t('group.mkdir')}>
            <${Icon} name="folder-plus" />
          </button>
          `}
          ${canCreateDir && newDirName !== null && html`
          <span class="tb-mkdir">
            <input type="text" class="tb-mkdir-input" autofocus
              value=${newDirName} disabled=${creatingDir}
              placeholder=${t('group.mkdir_prompt')}
              aria-label=${t('group.mkdir')}
              onInput=${(e) => setNewDirName(e.target.value)}
              onKeyDown=${(e) => {
                if (e.key === 'Enter') makeDirectory(newDirName);
                if (e.key === 'Escape') setNewDirName(null);
              }} />
            <button class="tb-btn tb-btn-icon" title=${t('group.mkdir')}
              disabled=${creatingDir || !newDirName.trim()}
              onClick=${() => makeDirectory(newDirName)}>
              <${Icon} name="check" />
            </button>
            <button class="tb-btn tb-btn-icon" title=${t('settings.cancel')}
              disabled=${creatingDir}
              onClick=${() => setNewDirName(null)}>
              <${Icon} name="close" />
            </button>
          </span>
          `}
        </div>

        <div class="breadcrumbs">
          ${showRefresh && onRefreshIndex && html`
            <button class="crumb crumb-refresh ${refreshing ? 'spinning' : ''}"
              onClick=${doRefresh} disabled=${refreshing}
              title=${t('group.refresh_index')}>
              <${Icon} name="refresh" />
            </button>
          `}
          <a class="crumb" onClick=${() => setCurrentPath('')}>
            <${Icon} name="home" />
          </a>
          ${breadcrumbs.map((seg, i) => {
            const path = breadcrumbs.slice(0, i + 1).join('/');
            return html`
              <span class="crumb-sep">/</span>
              <a class="crumb" onClick=${() => setCurrentPath(path)}>${seg}</a>
            `;
          })}
        </div>

        <div class="toolbar-group right">
          ${!readOnly && html`<div class="tb-search">
            <${Icon} name="search" />
            <input type="text" placeholder="${t('group.filter')}"
              value=${filter} onInput=${e => setFilter(e.target.value)} />
          </div>`}
          <div class="tb-actions">${actionItems}</div>
        </div>
      </div>
      <table class="file-table">
        <thead>
          <tr>
            <th class="sel-cell">
              <input type="checkbox" checked=${allSelected}
                ref=${(el) => { if (el) el.indeterminate = someSelected && !allSelected; }}
                onChange=${toggleAll} />
            </th>
            <th></th>
            <th class="sortable" onClick=${() => toggleSort('name')}>
              ${t('group.col_name')} ${sortKey === 'name' ? (sortAsc ? '▲' : '▼') : ''}
            </th>
            <th class="sortable" onClick=${() => toggleSort('size')}>
              ${t('group.col_size')} ${sortKey === 'size' ? (sortAsc ? '▲' : '▼') : ''}
            </th>
            ${showGroup && html`<th class="td-group">${t('search.col_group')}</th>`}
            <th class="sortable th-type" onClick=${() => toggleSort('type')}>
              ${t('group.col_type')} ${sortKey === 'type' ? (sortAsc ? '▲' : '▼') : ''}
            </th>
            <th class="sortable th-date" onClick=${() => toggleSort('date')}>
              ${t('group.col_date')} ${sortKey === 'date' ? (sortAsc ? '▲' : '▼') : ''}
            </th>
          </tr>
        </thead>
        <tbody>
          ${currentPath && html`
            <tr class="file-row dir-row" key="__parent__" onClick=${() => {
              const parts = currentPath.split('/');
              setCurrentPath(parts.slice(0, -1).join('/'));
            }}>
              <td class="sel-cell"></td>
              <td>${'\u{1F4C1}'}</td>
              <td>..</td>
              <td class="file-size"></td>
              ${showGroup && html`<td class="td-group"></td>`}
              <td class="td-type"></td>
              <td class="td-date"></td>
            </tr>
          `}
          ${subdirs.map(d => {
            const full = currentPath ? currentPath + '/' + d : d;
            const { inside, bytes } = dirInfo.get(d);
            const rs = rootState.get(d);
            const isEjected = rs && rs.ejected;
            const isUnavail = unavailableHere.includes(d);
            const isRemovable = rs && rs.removable;
            return html`
            <tr class="file-row dir-row${isEjected ? ' root-ejected' : ''}" key=${full}
                onClick=${() => { if (!isEjected) setCurrentPath(full); }}>
                <td class="sel-cell">
                  <input type="checkbox" checked=${selected.has(dirKey(d))}
                    onClick=${(ev) => ev.stopPropagation()}
                    onChange=${() => toggle(dirKey(d))} />
                </td>
              <td>${isEjected ? '\u{23CF}' : isUnavail ? '\u{26A0}' : '\u{1F4C1}'}</td>
              ${/* `file-name`, like a file's own name cell. Without it this
                    was a bare <td>, so a folder called
                    `Rage_Against_The_Machine_Discography_1992-2000_FLAC` —
                    one unbreakable word, which is how music libraries are
                    named — set the column's minimum width to the whole
                    string. Measured on a phone: a 527px table in a 390px
                    window, and on Android a page wider than the screen takes
                    every pinned header out of the visible area with it. */''}
              <td class="file-name">${d}${isEjected ? html`
                <span class="root-offline"> ${t('group.root_ejected')}</span>
              ` : isUnavail ? html`
                <span class="root-offline"> ${t('group.root_unavailable')}</span>
              ` : ''}${rs && rs.writable && !isEjected ? html`
                <span class="root-rw" title="${t('group.root_writable')}" style="margin-left:8px;opacity:0.5;font-size:0.9em">✎</span>
              ` : ''}${isRemovable && isNodeAdmin && operatorPaired ? html`
                <button class="btn-small root-eject-btn" title=${isEjected ? t('group.root_plug') : t('group.root_eject')}
                  onClick=${(ev) => {
                  ev.stopPropagation();
                  const transport = transportRef.current;
                  if (!transport) return;
                  const sk = transport.sessionKeys && transport.sessionKeys.skEdB64;
                  const signFn = (sk && window.MeshBayKeys)
                    ? (transcript) => window.MeshBayKeys.signBytes(sk, transcript)
                    : null;
                  const fn = isEjected
                    ? () => transport.plugRoot(groupId, d, signFn)
                    : () => transport.ejectRoot(groupId, d, signFn);
                  fn().catch((err) => setError(err.message));
                }}>${isEjected ? '\u{1F50C}' : '\u{23CF}'}</button>
              ` : ''}</td>
              <td class="file-size">${inside.length ? formatSize(bytes) : ''}</td>
              ${showGroup && html`<td class="td-group"></td>`}
              <td class="td-type"></td>
              <td class="td-date"></td>
            </tr>
          `; })}
          ${sorted.map(e => html`
              <tr class="file-row" key=${e.id}>
                <td class="sel-cell">
                  <input type="checkbox" checked=${selected.has(e.id)}
                    onClick=${(ev) => ev.stopPropagation()}
                    onChange=${() => toggle(e.id)} />
                </td>
                <td>${FILE_ICONS[e.type] || FILE_ICONS.other}</td>
                <td class="file-name">
                  ${canPreview(e)
                    ? html`<a class="file-link" onClick=${() => onPreview(e)}>${e.name}</a>`
                    : e.name
                  }
                  ${q && e.path && html`
                    <a class="file-loc"
                       onClick=${() => { setFilter(''); setCurrentPath(e.path); }}>${e.path}</a>`}
                </td>
                <td class="file-size">${formatSize(e.size)}</td>
                ${showGroup && html`<td class="td-group">
                  <a href="#/group/${e.groupId}" class="badge">${e.groupName || ''}</a>
                </td>`}
                <td class="file-type td-type">${e.type}</td>
                <td class="file-date td-date">${formatDate(e.added_at)}</td>
              </tr>
            `)}
          ${sorted.length === 0 && subdirs.length === 0 && html`
            <tr><td colspan=${6 + (showGroup ? 1 : 0)} class="file-empty">
              ${filter ? t('group.empty_filter') : t('group.empty_dir')}
            </td></tr>
          `}
        </tbody>
      </table>
    `}
    ${dragging && !readOnly && html`
      <div class="drop-overlay ${canDropHere ? '' : 'refused'}">
        <div class="drop-overlay-label">
          ${canDropHere ? t('group.drop_here', { dir: currentPath }) : t('group.drop_not_here')}
        </div>
      </div>
    `}
  `;
}

// ── File Preview (text, images) ─────────────────────────────────────────

const TEXT_EXTS = /\.(txt|md|json|csv|log|xml|yaml|yml|ini|conf|py|js|html|css|sh|c|h|java|rs|go|rb|toml)$/i;
const IMAGE_EXTS = /\.(jpg|jpeg|png|gif|webp|svg|bmp|ico)$/i;

function FilePreview({ entry, transportRef, gekRef, onClose, onDownload }) {
  const [phase, setPhase] = useState('loading');
  const [progress, setProgress] = useState(0);
  const [content, setContent] = useState(null);
  const [error, setError] = useState('');
  const [downloading, setDownloading] = useState(false);
  const blobUrlRef = useRef(null);

  useEffect(() => {
    let cancelled = false;
    const load = async () => {
      // Nothing here streams: a preview is decrypted whole, held as an array of
      // chunks, and turned into a blob. That is right for a page of text and a
      // photograph, and it is a dead tab for the things that also reach here —
      // a scanned PDF, a multi-gigabyte .csv or .log. There was no size test at
      // all, and the text branch is the sharpest illustration: it decoded the
      // entire file and then kept 500 000 characters of it.
      //
      // Films and music never arrive (group-page.js's onPreview routes video to
      // the MSE player and audio to the music queue), so this guard is only ever
      // met by a document somebody clicked without knowing how big it was. It
      // offers the download instead, which does stream.
      if (entry.size > MEMORY_CEILING) {
        setError(t('preview.too_large', {
          size: formatSize(entry.size), limit: formatSize(MEMORY_CEILING),
        }));
        setPhase('error');
        return;
      }
      const transport = transportRef.current;
      if (!transport || !transport.connected) {
        setError(t('video.err_transport'));
        setPhase('error');
        return;
      }
      try {
        const totalChunks = Math.ceil(entry.size / CHUNK_SIZE);
        let downloaded = 0;
        const chunks = await pipelinedDownload(
          transport, gekRef.current, entry.id, totalChunks,
          (bytes) => { downloaded += bytes; setProgress(downloaded / entry.size); },
        );
        if (cancelled) return;

        if (/\.pdf$/i.test(entry.name)) {
          // Decrypted here and shown from a blob: URL — the bytes never leave
          // the page, and the browser's own viewer renders them.
          const blob = new Blob(chunks, { type: 'application/pdf' });
          blobUrlRef.current = URL.createObjectURL(blob);
          setContent({ type: 'pdf' });
        } else if (entry.name.match(IMAGE_EXTS)) {
          const ext = entry.name.split('.').pop().toLowerCase();
          const mime = ext === 'svg' ? 'image/svg+xml'
            : ext === 'png' ? 'image/png'
            : ext === 'gif' ? 'image/gif'
            : ext === 'webp' ? 'image/webp'
            : 'image/jpeg';
          const blob = new Blob(chunks, { type: mime });
          blobUrlRef.current = URL.createObjectURL(blob);
          setContent({ type: 'image' });
        } else {
          const decoder = new TextDecoder('utf-8', { fatal: false });
          const text = chunks.map(c => decoder.decode(c, { stream: true })).join('');
          setContent({ type: 'text', text: text.slice(0, 500000) });
        }
        setPhase('ready');
      } catch (err) {
        if (!cancelled) { setError(err.message); setPhase('error'); }
      }
    };
    load();
    return () => { cancelled = true; };
  }, [entry]);

  useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);

  useEffect(() => {
    return () => {
      if (blobUrlRef.current) {
        URL.revokeObjectURL(blobUrlRef.current);
        blobUrlRef.current = null;
      }
    };
  }, []);

  return html`
    <div class="video-overlay" onClick=${(e) => {
      if (e.target.classList.contains('video-overlay')) onClose();
    }}>
      <div class="video-top-bar">
        <span class="video-title">${entry.name} (${formatSize(entry.size)})</span>
        ${onDownload && html`
          <button class="video-close ${downloading ? 'dl-active' : ''}"
            onClick=${() => {
              if (!downloading) {
                setDownloading(true);
                onDownload();
                setTimeout(() => setDownloading(false), 1500);
              }
            }}
            title="${t('group.download')}" disabled=${downloading}>
            ${downloading
              ? html`<span class="spinner"></span>`
              : html`<${Icon} name="download" />`}</button>
        `}
        <button class="video-close" onClick=${onClose} title="${t('video.close')}">
          <${Icon} name="close" /></button>
      </div>
      ${phase === 'loading' && html`
        <div class="video-loading">
          <div class="video-loading-label">${t('video.loading', { name: entry.name })}</div>
          <div class="video-progress-bar">
            <div class="video-progress-fill" style="width:${Math.round(progress * 100)}%"></div>
          </div>
        </div>
      `}
      ${phase === 'ready' && content?.type === 'pdf' && html`
        <object data=${blobUrlRef.current} type="application/pdf"
                class="preview-pdf" aria-label=${entry.name}>
          <p class="page-message">${t('preview.pdf_fallback')}</p>
        </object>
      `}
      ${phase === 'ready' && content?.type === 'image' && html`
        <div class="preview-image-wrap">
          <img class="preview-image" src=${blobUrlRef.current} alt=${entry.name} />
        </div>
      `}
      ${phase === 'ready' && content?.type === 'text' && html`
        <div class="preview-text-wrap">
          <pre class="preview-text">${content.text}</pre>
        </div>
      `}
      ${phase === 'error' && html`
        <div class="video-error">${error}</div>
      `}
    </div>
  `;
}

export { FilesPanel, FilePreview };