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
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
|
import {
html, render, useState, useEffect, useLayoutEffect, useCallback, useRef,
createContext, useContext,
} from './vendor/htm-preact.js';
import { t, getLocale, setLocale, initLocale, LOCALES } from './i18n.js';
import { ZipStream, entriesUnder } from './zipstream.js';
import { transfers, formatSpeed, etaSeconds } from './transfers.js';
import * as platform from './platform.js';
import * as downloads from './downloads.js';
import { Icon } from './icon.js';
import { formatSize } from './file-utils.js';
import {
HUB, navigate, session, getCachedGroupIndex,
_storeBundleKey, _loadBundleKey, _clearKeyDB,
loadAuth, saveAuth, setAuth, setAuthChangeListener, ensureFreshToken, hubFetch,
refreshAccessToken,
} from './hub-client.js';
import { GroupPage } from './group-page.js';
import { SearchPage, ConnectionPool } from './search-page.js';
import { MusicPlayerBar } from './music-player.js';
import { SettingsPage } from './settings-page.js';
import { ProfilePage } from './profile-page.js';
import { ExplorePage } from './explore-page.js';
import { GroupName } from './group-name.js';
import { FirstRunPage, LoginPage, RegisterPage, ResetPasswordPage } from './auth-page.js';
// ── Constants ────────────────────────────────────────────────────────────────
// How often to look. Cheap — it reads a timestamp out of the token and almost
// always does nothing.
const TOKEN_CHECK_MS = 60000;
const THEME_KEY = 'mb_theme';
// ── Theme ────────────────────────────────────────────────────────────────────
function getInitialTheme() {
const stored = localStorage.getItem(THEME_KEY);
if (stored === 'dark' || stored === 'light' || stored === 'system') return stored;
return 'system';
}
function resolveTheme(pref) {
if (pref === 'system') {
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}
return pref;
}
// ── Router ───────────────────────────────────────────────────────────────────
function useRoute() {
const [hash, setHash] = useState(window.location.hash.slice(1) || '/');
useEffect(() => {
const onHash = () => setHash(window.location.hash.slice(1) || '/');
window.addEventListener('hashchange', onHash);
return () => window.removeEventListener('hashchange', onHash);
}, []);
return hash;
}
// ── Context ──────────────────────────────────────────────────────────────────
const AuthContext = createContext(null);
function useAuth() { return useContext(AuthContext); }
// The M of the wordmark is a picture; the rest is text. Resolved from this
// module's own URL so the hub's fingerprinted path and the application's
// app:// scheme both come out right without either being named here.
const BRAND_M = new URL('./meshbay-m.png', import.meta.url).href;
// ── User Menu ────────────────────────────────────────────────────────────────
function UserMenu({ user, theme, onThemeChange, onLogout }) {
const [open, setOpen] = useState(false);
const [langOpen, setLangOpen] = useState(false);
const ref = useRef(null);
useEffect(() => {
if (!open) return;
const close = (e) => {
if (ref.current && !ref.current.contains(e.target)) setOpen(false);
};
document.addEventListener('click', close);
return () => document.removeEventListener('click', close);
}, [open]);
const resolved = resolveTheme(theme);
return html`
<div class="user-menu-wrap" ref=${ref}>
<button class="user-menu-trigger" onClick=${() => setOpen(o => !o)}>
<span class="user-menu-avatar">${user.username[0].toUpperCase()}</span>
<span class="user-menu-name">${user.username}</span>
<${Icon} name="chevron" cls="user-menu-caret ${open ? 'flip' : ''}" />
</button>
${open && html`
<div class="user-menu-dropdown">
<div class="user-menu-header">
<span class="user-menu-avatar lg">${user.username[0].toUpperCase()}</span>
<div>
<div class="user-menu-uname">${user.username}</div>
<div class="user-menu-role">${user.role || 'user'}</div>
</div>
</div>
<div class="user-menu-divider"></div>
<button class="user-menu-item" onClick=${(e) => { e.stopPropagation(); setLangOpen(o => !o); }}>
<${Icon} name="globe" cls="umi-icon" /> ${t('usermenu.language')}
<${Icon} name="chevron" cls="umi-arrow ${langOpen ? 'flip' : ''}" />
</button>
${langOpen && LOCALES.map(l => html`
<button key=${l.code} class="user-menu-item user-menu-sub"
onClick=${() => { setLocale(l.code); window.location.reload(); }}>
${l.name}
${getLocale() === l.code
&& html`<${Icon} name="check" cls="umi-check" />`}
</button>
`)}
<button class="user-menu-item" onClick=${() => { setOpen(false); navigate('/profile'); }}>
<${Icon} name="user" cls="umi-icon" /> ${t('usermenu.profile')}
</button>
<button class="user-menu-item" onClick=${() => { setOpen(false); navigate('/settings'); }}>
<${Icon} name="gear" cls="umi-icon" /> ${t('usermenu.settings')}
</button>
<button class="user-menu-item" onClick=${() => {
onThemeChange(resolved === 'dark' ? 'light' : 'dark');
setOpen(false);
}}>
<${Icon} name=${resolved === 'dark' ? 'sun' : 'moon'} cls="umi-icon" />
${' '}${resolved === 'dark' ? t('usermenu.theme_light') : t('usermenu.theme_dark')}
</button>
<div class="user-menu-divider"></div>
<button class="user-menu-item user-menu-logout" onClick=${onLogout}>
<${Icon} name="power" cls="umi-icon" /> ${t('usermenu.logout')}
</button>
</div>
`}
</div>
`;
}
// ── Transfers widget ─────────────────────────────────────────────────────────
function TransferWidget() {
const [items, setItems] = useState(() => transfers.list());
const [open, setOpen] = useState(false);
const ref = useRef(null);
useEffect(() => transfers.subscribe(setItems), []);
useEffect(() => {
if (!open) return;
const close = (e) => {
if (ref.current && !ref.current.contains(e.target)) setOpen(false);
};
document.addEventListener('click', close);
return () => document.removeEventListener('click', close);
}, [open]);
const running = items.filter(i => i.status === 'running');
const waiting = items.filter(
i => i.status === 'queued' || i.status === 'preparing');
// Its own group, and not a leftover.
//
// "Finished" used to be defined as everything that is not running, queued or
// preparing — a definition by exclusion, which quietly swallowed `paused` the
// day pausing shipped. A transfer somebody stopped on purpose then sat under
// "Finished", beside the ones that are actually over, offering a resume
// button in the section of things that cannot be resumed.
const paused = items.filter(i => i.status === 'paused');
const finished = items.filter(
i => i.status !== 'running' && i.status !== 'queued'
&& i.status !== 'preparing' && i.status !== 'paused');
// Paused counts as active: it is not over, the person means to come back to
// it, and the badge saying nothing is happening would be a lie.
const active = running.length + waiting.length + paused.length;
// Grouped, and in this order: what is moving, what is waiting, what is over.
// Re-sorting the flat list on every emit made rows jump under the pointer
// each time a neighbour finished — the group is what changes, not the
// position within it, so a row only moves when its own state does.
const groups = [
['running', running],
['waiting', waiting],
['paused', paused],
['finished', finished],
].filter(([, rows]) => rows.length);
if (!items.length) return null;
return html`
<div class="transfer-wrap" ref=${ref}>
<button class="nav-notif transfer-btn ${running.length ? 'active' : ''}"
aria-label=${t('transfers.title')}
aria-expanded=${open ? 'true' : 'false'}
title=${t('transfers.title')}
onClick=${(e) => { e.stopPropagation(); setOpen(o => !o); }}>
<${Icon} name="transfer" />
${active > 0 && html`
<span class="notif-badge">${active}</span>
`}
</button>
${/* One live region for the panel, announcing what changed state rather
than every progress tick — a reader that says "62%… 63%… 64%" for a
four-gigabyte film is a reader nobody leaves on. */''}
<span class="sr-only" aria-live="polite">
${t('transfers.summary', { running: running.length, waiting: waiting.length })}
</span>
${open && html`
<div class="transfer-panel" role="group"
aria-label=${t('transfers.title')}>
<div class="transfer-head">
<span class="transfer-head-title">${t('transfers.title')}</span>
${active > 0 && html`
<span class="transfer-head-summary">
${t('transfers.summary', {
running: running.length, waiting: waiting.length })}
</span>
`}
${finished.length > 0 && html`
<button class="btn-secondary"
onClick=${() => transfers.clearFinished()}>
${t('transfers.clear')}
</button>
`}
</div>
${groups.map(([label, rows]) => html`
<div class="transfer-group" key=${label}>
${groups.length > 1 && html`
<div class="transfer-group-head">
${t('transfers.group_' + label, { n: rows.length })}
</div>
`}
${rows.map(it => html`<${TransferRow} it=${it} key=${it.id} />`)}
</div>
`)}
</div>
`}
</div>
`;
}
/** One row. Split out so the panel above reads as a layout and this as a state
* machine — they change for different reasons. */
function TransferRow({ it }) {
const eta = etaSeconds(it);
return html`
<div class="transfer-item transfer-${it.status}">
<div class="transfer-line">
<span class="transfer-kind" aria-hidden="true">
<${Icon} name=${it.kind === 'upload' ? 'upload' : 'download'} />
</span>
${it.canOpen
? html`<a class="transfer-name" href="#" title=${it.name}
onClick=${(e) => { e.preventDefault(); transfers.open(it.id); }}>${it.name}</a>`
: html`<span class="transfer-name" title=${it.name}>${it.name}</span>`}
${it.pausable && (it.status === 'running' || it.status === 'paused')
&& html`
${/* Offered only where the target can actually do it: a
service-worker stream is a download the browser already owns,
and a pause there would restart from zero. */''}
<button class="transfer-pause"
aria-label=${t(it.status === 'paused'
? 'transfers.resume_one' : 'transfers.pause_one',
{ name: it.name })}
title=${t(it.status === 'paused'
? 'transfers.resume' : 'transfers.pause')}
onClick=${() => (it.status === 'paused'
? transfers.resume(it.id) : transfers.pause(it.id))}>
<${Icon} name=${it.status === 'paused' ? 'play' : 'pause'} />
</button>
`}
${!it.pausable && downloads.SUPPORTED && it.kind === 'download'
&& (it.status === 'running' || it.status === 'queued') && html`
${/* Say why, rather than leaving a gap where a button is on the row
above. Without a granted folder this browser writes through the
service worker — a download it already owns, which cannot be
paused — so the button is absent for a reason nobody can see,
and an upload beside it has one. Shown only where choosing a
folder is actually possible: on Firefox and Safari there is no
folder to choose and this hint would be a lie. */''}
<span class="transfer-nopause" title=${t('transfers.not_pausable')}
aria-label=${t('transfers.not_pausable')}>
<${Icon} name="pause" />
</span>
`}
${(it.status === 'running' || it.status === 'queued'
|| it.status === 'preparing' || it.status === 'paused') && html`
<button class="transfer-cancel"
aria-label=${t('transfers.cancel_one', { name: it.name })}
title=${t('transfers.cancel')}
onClick=${() => transfers.cancel(it.id)}>
<${Icon} name="close" />
</button>
`}
</div>
${it.status === 'preparing'
? html`
${/* Not a progress bar at 0%: nothing is wrong and nothing is
stalled, the download is still finding somewhere to write. The
row exists from the click precisely so this state is visible
instead of being an empty panel. */''}
<div class="dl-progress dl-waiting"></div>
<div class="transfer-meta">
<span>${t('transfers.preparing')}</span>
<span>${formatSize(it.total)}</span>
</div>
`
: it.status === 'queued'
? html`
<div class="dl-progress dl-waiting"></div>
<div class="transfer-meta">
<span>${it.queuedByOwnLimit
? t('transfers.waiting_own_slots')
: t('transfers.waiting_node', { n: it.ahead })}</span>
<span>${formatSize(it.total)}</span>
</div>
`
: it.status === 'paused'
? html`
${/* The bar keeps its fill: what has been written is still there,
and resuming continues from it rather than starting again. */''}
<div class="dl-progress" role="progressbar"
aria-valuenow=${it.percent} aria-valuemin="0" aria-valuemax="100">
<div class="dl-fill dl-paused" style="width:${it.percent}%"></div>
</div>
<div class="transfer-meta">
<span>${t('transfers.paused')}</span>
<span>${formatSize(it.done)}${it.total
? ' / ' + formatSize(it.total) : ''}</span>
</div>
`
: it.status === 'running'
? html`
<div class="dl-progress" role="progressbar"
aria-valuenow=${it.percent} aria-valuemin="0" aria-valuemax="100">
<div class="dl-fill" style="width:${it.percent}%"></div>
</div>
<div class="transfer-meta">
<span>${formatSize(it.done)}${it.total
? ' / ' + formatSize(it.total) : ''}</span>
<span>${[formatSpeed(it.speed),
it.settled && eta !== null ? formatEta(eta) : '']
.filter(Boolean).join(' · ')}</span>
</div>
`
: html`
<div class="transfer-meta">
<span class=${it.status === 'failed' ? 'transfer-failed' : ''}>
${it.status === 'done' ? t('transfers.done')
: it.status === 'cancelled' ? t('transfers.cancelled')
: it.error || t('transfers.failed')}
</span>
${it.canOpen && html`
<button class="link-btn" onClick=${() => transfers.open(it.id)}>
${t('transfers.open')}
</button>
`}
</div>
`}
</div>
`;
}
/** "4 min left". Coarse on purpose: a per-second countdown on a transfer whose
* speed varies is a number that is wrong most of the time and looks precise. */
function formatEta(seconds) {
if (seconds < 60) return t('transfers.eta_seconds', { n: Math.ceil(seconds) });
if (seconds < 3600) return t('transfers.eta_minutes', { n: Math.round(seconds / 60) });
return t('transfers.eta_hours', { n: Math.round(seconds / 360) / 10 });
}
// ── Nav ──────────────────────────────────────────────────────────────────────
function Nav({ user, theme, onThemeChange, onLogout, onMenuToggle, unreadCount,
hubUnset }) {
return html`
<nav class="nav">
<div class="nav-left">
${user && html`
<button class="nav-hamburger" onClick=${onMenuToggle}
aria-label="${t('nav.toggle_menu')}"><${Icon} name="menu" /></button>
`}
<a class="nav-brand" href="#/">
<img class="nav-brand-m" src=${BRAND_M} alt="M" />eshBay
</a>
</div>
<div class="nav-right">
${user && html`<${TransferWidget} />`}
${platform.capabilities.tray && html`
<button class="nav-tray" onClick=${() => platform.minimizeToTray(trayLabels())}
title=${t('nav.minimize_tray')} aria-label=${t('nav.minimize_tray')}>
<${Icon} name="tray" />
</button>
`}
${user && html`
<a class="nav-notif" href="#/" title=${t('notif.title')}>
<${Icon} name="bell" />${unreadCount > 0
&& html`<span class="notif-badge">${unreadCount}</span>`}
</a>
`}
${user ? html`
<${UserMenu} user=${user} theme=${theme}
onThemeChange=${onThemeChange} onLogout=${onLogout} />
` : hubUnset ? null : html`
<a class="nav-btn" href="#/login">${t('nav.login')}</a>
`}
</div>
</nav>
`;
}
// ── Sidebar ──────────────────────────────────────────────────────────────────
function Sidebar({ groups, presence, indexProgressPct, route, menuOpen, role, hasNodeKey,
allowPublicGroups = true }) {
const isStaff = role === 'moderator' || role === 'admin';
return html`
<aside class="sidebar ${menuOpen ? 'open' : ''}">
${isStaff && html`
<div class="sidebar-section">
<div class="sidebar-heading">${t('sidebar.admin')}</div>
<a class="sidebar-item ${route === '/admin' ? 'active' : ''}"
href="#/admin"><${Icon} name="shield" /> ${t('admin.title')}</a>
</div>
`}
<div class="sidebar-section">
<div class="sidebar-heading">${t('sidebar.discover')}</div>
${allowPublicGroups && html`
<a class="sidebar-item ${route === '/explore' ? 'active' : ''}"
href="#/explore"><${Icon} name="globe" /> ${t('sidebar.public_groups')}</a>`}
<a class="sidebar-item ${route === '/search' ? 'active' : ''}"
href="#/search"><${Icon} name="search" /> ${t('sidebar.search')}</a>
</div>
${platform.capabilities.nodeAdmin && hasNodeKey && html`
<div class="sidebar-section">
<div class="sidebar-heading">${t('sidebar.node')}</div>
<a class="sidebar-item ${route === '/node' ? 'active' : ''}"
href="#/node"><${Icon} name="server" /> ${t('node.title')}</a>
<a class="sidebar-item ${route === '/create-group' ? 'active' : ''}"
href="#/create-group"><${Icon} name="plus" /> ${t('sidebar.create_group')}</a>
</div>
`}
<div class="sidebar-section">
<div class="sidebar-heading">${t('sidebar.my_groups')}</div>
${groups.length === 0
? html`<div class="sidebar-empty">${t('sidebar.no_groups')}</div>`
: [...groups].sort((a, b) =>
(b.last_activity_at || b.created_at || '').localeCompare(
a.last_activity_at || a.created_at || '')).map(g => {
// Three states, each backed by something. `node_online` comes from
// the hub's signaling registry and rides on the group list itself,
// so there is no poll and no timer; a connection this browser tried
// and failed overrides it, because that is the fact the reader
// actually cares about. Anything else is "not known yet".
const state = presence[g.id] ?? (g.node_online === true ? 'online'
: g.node_online === false ? 'offline' : 'unknown');
const label = state === 'indexing'
? t('presence.indexing', { pct: indexProgressPct[g.id] ?? 0 })
: t('presence.' + state);
return html`
<a key=${g.id}
class="sidebar-item sidebar-group ${route === '/group/' + g.id ? 'active' : ''}"
href="#/group/${g.id}">
<span class="si-head">
<span class="presence presence-${state}"
title="${label}"
aria-label="${label}"></span>
<span class="sidebar-item-name">${g.name}</span>
</span>
${g.owner_username && html`
<span class="sidebar-owner">@${g.owner_username}</span>`}
</a>
`;
})
}
</div>
<a class="sidebar-legal" href="${legalUrl()}" target="_blank" rel="noopener">
${t('sidebar.legal')}</a>
</aside>
`;
}
// The legal pages of the hub in use: the page's own origin in a browser, the
// configured hub in the application. A new tab either way: the application
// refuses to navigate away from its interface and hands a new window to the
// system browser instead, and in a browser it keeps the session on screen.
function legalUrl() {
return `${platform.hubBase().replace(/\/$/, '')}/legal/`;
}
// ── Home Page ────────────────────────────────────────────────────────────────
function NotificationFeed({ notifications, onMarkRead, onPurge }) {
if (!notifications.length) return null;
return html`
<div class="notif-feed">
<h3>
${t('notif.title')}
<button class="btn-secondary notif-purge" onClick=${onPurge}>
${t('notif.purge')}
</button>
</h3>
${notifications.map(n => html`
<div key=${n.id} class="notif-item notif-unread"
onClick=${() => {
// Reading it is the point of clicking it: it goes, here and in the
// count, rather than sitting there greyed out.
onMarkRead(n.id);
if (n.link) navigate(n.link);
}}>
<span class="notif-kind">${n.kind}</span>
<span class="notif-text">${n.title}</span>
<span class="notif-time">${new Date(n.created_at).toLocaleDateString()}</span>
</div>
`)}
</div>
`;
}
function HomePage({ groups, notifications, onMarkRead, onPurge, allowPublicGroups = true }) {
const [setupDismissed, setSetupDismissed] = useState(false);
if (groups.length === 0) {
if (platform.isNative && !setupDismissed) {
return html`<${SetupWelcome}
onDismiss=${() => setSetupDismissed(true)} />`;
}
return html`
<div>
<h2>${t('home.welcome')}</h2>
<${NotificationFeed} notifications=${notifications}
onMarkRead=${onMarkRead} onPurge=${onPurge} />
<p class="page-message">
${t('home.no_groups')}
${' '}${allowPublicGroups
? html`${t('home.browse_prefix')}<a href="#/explore">${t('home.browse_link')}</a>${t('home.browse_suffix')}`
: t('home.invite_only')}
</p>
</div>
`;
}
return html`
<div>
<h2>${t('home.my_groups')}</h2>
<${NotificationFeed} notifications=${notifications}
onMarkRead=${onMarkRead} onPurge=${onPurge} />
<div class="group-grid">
${groups.map(g => html`
<a key=${g.id} class="group-card" href="#/group/${g.id}">
${/* The host, not the visibility. "private" and "invite" were on
every card because they are the default everywhere — two
badges that never varied and so never told anyone anything.
Who hosts a group does vary, and is the thing that tells two
groups of the same name apart (the hub only enforces
uniqueness per owner). GroupName renders it as a smaller
@handle beside the name, which is how the group header and
Explore already write it. "admin" stays: it does vary. */''}
<h3><${GroupName} name=${g.name} owner=${g.owner_username} /></h3>
${g.description && html`<p class="group-card-desc">${g.description}</p>`}
${g.is_admin && html`<span class="badge">admin</span>`}
</a>
`)}
</div>
</div>
`;
}
// ── First-run welcome (Electron-only, shown once on empty home) ─────────────
function SetupWelcome({ onDismiss }) {
// An install-time NSIS page used to be the only place this choice was
// ever offered, and an AppX/MSIX install has no install-time page at all
// (no custom actions, full stop, not just no elevation) -- so a build
// running its own bundled node needs to say so somewhere the user will
// actually see it, not just leave the choice sitting unfound on the Node
// page. Shown only while neither startup mode is configured yet; it
// disappears on its own once one is (or stays hidden forever if the
// platform has no node.service at all, e.g. Light, non-Windows, browser).
const [startupHint, setStartupHint] = useState(false);
useEffect(() => {
let cancelled = false;
(async () => {
try {
if (!platform.node.available || !(await platform.node.bundled())) return;
if (!platform.node.service.available) return;
const status = await platform.node.service.status();
const configured = status.mode === 'service' || Boolean(status.autostart);
if (!cancelled && status.supported !== false && !configured) setStartupHint(true);
} catch { /* best effort -- the Node page itself is the source of truth */ }
})();
return () => { cancelled = true; };
}, []);
return html`<div class="page-content">
<h2>${t('setup.welcome_title')}</h2>
<p class="page-message" style="margin-bottom:24px">
${t('setup.welcome_message')}</p>
${startupHint && html`
<p class="page-message" style="margin-bottom:24px">
${t('setup.node_startup_hint')}
</p>
`}
<div style="display:flex;gap:8px;flex-wrap:wrap">
<a class="btn btn-primary" href="#/create-group">
${t('setup.create_group')}</a>
<button class="btn btn-secondary" onClick=${onDismiss}>
${t('setup.dismiss')}</button>
</div>
</div>`;
}
// ── Lazy-loaded Create Group page ────────────────────────────────────────────
let _CreateGroupPage = null;
function LazyCreateGroupPage(props) {
const [loaded, setLoaded] = useState(!!_CreateGroupPage);
useEffect(() => {
if (!_CreateGroupPage) {
import('./create-group-page.js').then(m => { _CreateGroupPage = m.CreateGroupPage; setLoaded(true); });
}
}, []);
if (!loaded) return html`<div class="page-content">
<p class="page-message"><span class="spinner"></span></p></div>`;
return html`<${_CreateGroupPage} ...${props} />`;
}
// ── Settings Page ───────────────────────────────────────────────────────────
const THEME_OPTIONS = ['light', 'dark', 'system'];
// ── Profile Page ────────────────────────────────────────────────────────────
//
// ── Lazy-loaded Admin page (admin/moderator only) ─────────────────────────
let _AdminPage = null;
function LazyAdminPage(props) {
const [loaded, setLoaded] = useState(!!_AdminPage);
useEffect(() => {
if (!_AdminPage) {
import('./admin-page.js').then(m => { _AdminPage = m.AdminPage; setLoaded(true); });
}
}, []);
if (!loaded) return html`<div class="page-content">
<p class="page-message"><span class="spinner"></span></p></div>`;
return html`<${_AdminPage} ...${props} />`;
}
// ── Lazy-loaded Node page (Electron only) ───────────────────────────────────
let _NodePage = null;
function LazyNodePage(props) {
const [loaded, setLoaded] = useState(!!_NodePage);
useEffect(() => {
if (!_NodePage) {
import('./node-page.js').then(m => { _NodePage = m.NodePage; setLoaded(true); });
}
}, []);
if (!loaded) return html`<div class="page-content">
<p class="page-message"><span class="spinner"></span></p></div>`;
return html`<${_NodePage} ...${props} />`;
}
// ── App ──────────────────────────────────────────────────────────────────────
function App() {
const route = useRoute();
const [theme, setTheme] = useState(getInitialTheme);
const [user, setUser] = useState(loadAuth);
// A desktop build with a remembered device signs in without asking. Null
// until it has tried, so nothing renders a sign-in form the user is about to
// be taken past.
const [deviceTried, setDeviceTried] = useState(!platform.device.available);
// Native, and nowhere to talk to yet.
const [needsHub, setNeedsHub] = useState(
platform.isNative && !platform.hubBase());
const [groups, setGroups] = useState([]);
const [menuOpen, setMenuOpen] = useState(false);
const [notifications, setNotifications] = useState([]);
const [unreadCount, setUnreadCount] = useState(0);
const [notifDisabled, setNotifDisabled] = useState(false);
const [userPrefs, setUserPrefs] = useState({});
const [hasNodeKey, setHasNodeKey] = useState(false);
// Instance policy, fetched once, unauthenticated. `null` until it answers;
// treat unknown as "allowed" so a slow hub never blocks a legitimate private
// group — the hub refuses a public one server-side regardless.
const [hubInfo, setHubInfo] = useState(null);
const allowPublicGroups = !hubInfo || hubInfo.allow_public_groups !== false;
// -- Persistent music player (lifted from group-page.js) --
const [musicQueue, setMusicQueue] = useState(null);
const musicPoolRef = useRef(null);
const userRef = useRef(user);
userRef.current = user;
const groupTransportRef = useRef(null);
useEffect(() => {
musicPoolRef.current = new ConnectionPool(HUB);
return () => { if (musicPoolRef.current) musicPoolRef.current.closeAll(); };
}, []);
const getMusicConnection = useCallback(async (groupId) => {
const gt = groupTransportRef.current;
if (gt && gt.groupId === groupId) {
const tr = gt.transportRef.current;
if (tr && tr.connected) return { transport: tr, gek: gt.gekRef.current };
}
const u = userRef.current;
if (!u || !musicPoolRef.current) throw new Error('no connection');
const bundleKey = session.bundleKey || await _loadBundleKey();
if (bundleKey) session.bundleKey = bundleKey;
const conn = await musicPoolRef.current.connect(
groupId, u.token, bundleKey, u.username, u.userId);
return { transport: conn.transport, gek: conn.gek };
}, []);
const handlePlayQueue = useCallback((tracks, startIndex, source) => {
if (source && source.transportRef) {
groupTransportRef.current = {
groupId: source.groupId,
transportRef: source.transportRef,
gekRef: source.gekRef,
};
} else {
groupTransportRef.current = null;
}
setMusicQueue({ tracks, startIndex, nonce: Date.now() });
}, []);
const handleStopMusic = useCallback(() => setMusicQueue(null), []);
const resolved = resolveTheme(theme);
// Keep the session alive without anyone having to think about it.
useEffect(() => {
// A renewal can happen inside hubFetch, well away from any render. This is
// how the component learns about it — including a failed one, which sets
// null and lands on the login page instead of failing every later call.
setAuthChangeListener((auth) => setUser(auth));
// On mount above all: a tab reopened tomorrow holds an hour-old access
// token and a refresh token good for a month, and used to greet its owner
// with "invalid token" rather than spending the second on renewing it.
ensureFreshToken();
const timer = setInterval(ensureFreshToken, TOKEN_CHECK_MS);
// A backgrounded tab has its timers throttled hard, so the check above may
// not have run for the whole time it was away. Coming back is exactly when
// the token is most likely to be stale.
const onVisible = () => {
if (document.visibilityState === 'visible') ensureFreshToken();
};
document.addEventListener('visibilitychange', onVisible);
return () => {
setAuthChangeListener(null);
clearInterval(timer);
document.removeEventListener('visibilitychange', onVisible);
};
}, []);
useEffect(() => {
document.documentElement.className = `theme-${resolved}`;
localStorage.setItem(THEME_KEY, theme);
}, [theme, resolved]);
useEffect(() => {
hubFetch('/v1/hub/info').then(setHubInfo).catch(() => {});
}, []);
const fetchNotifications = useCallback(() => {
if (!user || notifDisabled) {
setNotifications([]); setUnreadCount(0); return;
}
// `unread_only`: clicking one is what dismisses it (see markRead), so a
// read notification is a dismissed notification and must not come back on
// the next launch. Without this the two halves disagreed — the click
// removed it here and marked it read on the hub, and the next startup
// asked for everything and put it straight back. `unread_count` is
// computed server-side and is unaffected by the filter.
hubFetch('/v1/notifications?limit=20&unread_only=true', { token: user.token })
.then(data => {
setNotifications(data.notifications || []);
setUnreadCount(data.unread_count || 0);
})
.catch(() => {});
}, [user, notifDisabled]);
useEffect(() => {
if (!user) { setGroups([]); setNotifications([]); setUnreadCount(0); setHasNodeKey(false); return; }
hubFetch('/v1/groups/mine', { token: user.token })
.then(data => setGroups(data.groups || []))
.catch(() => setGroups([]));
hubFetch('/v1/users/me/preferences', { token: user.token })
.then(prefs => {
setUserPrefs(prefs || {});
if (prefs.notifications_disabled === 'true') setNotifDisabled(true);
})
.catch(() => {});
if (platform.capabilities.nodeAdmin) {
hubFetch(`/v1/users/${user.username}/pubkeys`, { token: user.token })
.then(data => setHasNodeKey(Boolean(data.pk_node_ed25519)))
.catch(() => {});
}
fetchNotifications();
}, [user]);
// The group list lives here, so an edit made three components down has to come
// back up rather than be re-fetched: a reload would drop the WebRTC connection
// the page is holding.
const updateGroup = useCallback((gid, patch) => {
setGroups(prev => prev.map(g => (g.id === gid ? { ...g, ...patch } : g)));
}, []);
// What this browser saw for itself, which beats what the hub reported. Held
// for the session only: it is a cache of observations, not a source of truth,
// and a reload should go back to asking.
const [presence, setPresence] = useState({});
// Percentage alongside 'indexing' presence — kept separate from `presence`
// itself so a changing % does not require treating every tick as a new
// presence state (see the Sidebar dot's title/aria-label).
const [indexProgressPct, setIndexProgressPct] = useState({});
const notePresence = useCallback((gid, state, pct) => {
setPresence(prev => (prev[gid] === state ? prev : { ...prev, [gid]: state }));
if (pct !== undefined) {
setIndexProgressPct(prev => (prev[gid] === pct ? prev : { ...prev, [gid]: pct }));
}
}, []);
const handleLeftGroup = useCallback((gid) => {
setGroups(prev => prev.filter(g => g.id !== gid));
setPresence(prev => {
const next = { ...prev };
delete next[gid];
return next;
});
navigate('/');
}, []);
const markRead = useCallback((id) => {
if (!user) return;
// Drop it here and now. Waiting for the round trip leaves it on screen while
// the page navigates, which reads as "the click did nothing".
setNotifications(prev => prev.filter(n => n.id !== id));
setUnreadCount(c => Math.max(0, c - 1));
// DELETE, not `/read`: dismissing one drops the row. The old path still
// works and still deletes, for interfaces older than the hub.
hubFetch(`/v1/notifications/${id}`, { method: 'DELETE', token: user.token })
.catch(() => fetchNotifications());
}, [user, fetchNotifications]);
const purgeNotifications = useCallback(() => {
if (!user) return;
setNotifications([]);
setUnreadCount(0);
hubFetch('/v1/notifications', { method: 'DELETE', token: user.token })
.catch(() => fetchNotifications());
}, [user, fetchNotifications]);
/** Clear the invitation for a group once its code has actually been redeemed. */
const dismissGroupNotifications = useCallback((groupId) => {
if (!user) return;
setNotifications(prev => {
const gone = prev.filter(n => n.group_id === groupId && n.kind === 'group_invite');
gone.forEach(n => hubFetch(`/v1/notifications/${n.id}`,
{ method: 'DELETE', token: user.token }).catch(() => {}));
if (gone.length) setUnreadCount(c => Math.max(0, c - gone.length));
return prev.filter(n => !gone.includes(n));
});
}, [user]);
// Sign in with this device's key, once, at startup.
//
// The passphrase stays the account's credential and its recovery path; this
// is what saves entering it every launch. A refusal is not an error worth
// showing — the key may have been retired from another device, or the hub may
// have forgotten it — so it falls through to the ordinary form.
useEffect(() => {
// Nothing to do when a session was restored from storage, or when this is
// a browser. `user` is read once here on purpose: this runs at startup and
// must not re-fire when the session it just created lands.
if (deviceTried || user) { setDeviceTried(true); return; }
let cancelled = false;
(async () => {
try {
// `loadAuth` keeps the username even when the tokens in it are stale,
// and `app://meshbay` is a stable origin, so localStorage survives a
// relaunch. A fresh install has nothing here and asks for a passphrase,
// which is right: the first sign-in is what registers the device.
const saved = loadAuth();
const username = saved && saved.username;
if (!username) return;
const signed = await platform.device.sign(username);
if (!signed) return;
const data = await hubFetch('/v1/users/auth', {
method: 'POST',
body: { username, timestamp: signed.timestamp,
signature: signed.signature },
});
const me = await hubFetch('/v1/users/me', { token: data.access_token });
if (cancelled) return;
const u = { username, userId: me.user_id, token: data.access_token,
refreshToken: data.refresh_token, role: me.role };
setAuth(u);
setUser(u);
} catch {
// Falls through to the sign-in form, which is the honest outcome.
} finally {
if (!cancelled) setDeviceTried(true);
}
})();
return () => { cancelled = true; };
}, []);
useEffect(() => { setMenuOpen(false); }, [route]);
const changeTheme = useCallback((val) => {
setTheme(val);
}, []);
/**
* Register this device's hub key, once, after a passphrase sign-in.
*
* Deliberately not fatal: a hub that refuses it, or a machine with no key
* storage, means the passphrase is asked for again next time — which is
* exactly what a browser does, and is a worse experience rather than a
* broken one.
*/
const registerThisDevice = useCallback(async (token) => {
if (!platform.device.available) return;
try {
const backend = await platform.secrets.backend();
if (backend === 'unavailable') return;
const pk = await platform.device.ensure();
if (!pk) return;
await hubFetch('/v1/users/devices', {
method: 'POST', token,
body: { pk_auth_ed25519: pk, label: t('device.this_device') },
});
} catch (err) {
console.warn('device not registered:', err.message);
}
}, []);
const authCtx = {
user,
login: async (username, password) => {
let token, refreshToken;
if (window.MeshBayKeys) {
const data = await window.MeshBayKeys.loginAndRecover(username, password);
token = data.accessToken;
refreshToken = data.refreshToken;
// The only thing sign-in produces: the key that opens a node's bundle.
// Which identity we use is decided per node, when we get there.
session.bundleKey = data.bundleKey;
await _storeBundleKey(session.bundleKey);
} else {
const data = await hubFetch('/v1/users/login', {
method: 'POST',
body: { username, password },
});
token = data.access_token;
refreshToken = data.refresh_token;
}
const me = await hubFetch('/v1/users/me', { token });
const u = { username, userId: me.user_id, token, refreshToken, role: me.role };
// On a desktop build, remember this device so the next launch does not ask
// for the passphrase again. The key is generated and held by the main
// process; what travels here is only its public half.
await registerThisDevice(token);
// setAuth, not saveAuth: it is the one writer that also updates the copy
// hubFetch renews from. Storing the session without it left the renewal
// path with no refresh token to present.
setAuth(u);
setUser(u);
},
logout: () => {
// Navigating away leaves transfers running; signing out does not. They
// are moving data on tokens that are about to stop being ours.
transfers.reset();
setAuth(null);
setUser(null);
setGroups([]);
navigate('/login');
},
};
// Group membership is baked into the access token at login and the hub does not
// push updates, so someone invited after they signed in carries a token that
// says they are in nothing. Refreshing re-reads membership from the database.
// Goes through refreshAccessToken like everything else. It used to call the
// endpoint here and keep only the access token, dropping the rotated refresh
// token that came back with it — so the refresh token was spent on first use,
// and presenting the spent one again revoked the whole family. Which is how
// a session that should last a month ended at "invalid token" with signing
// out as the only way back.
const refreshAuth = useCallback(() => refreshAccessToken(), []);
let page;
// A desktop build with no hub configured cannot do anything at all, so it
// asks before showing a sign-in form that could not work. Deliberately not
// defaulted to meshbay.org: a client that picks its own hub is a client that
// can be pointed at one.
if (needsHub) {
page = html`<${FirstRunPage} onSet=${() => setNeedsHub(false)} />`;
} else if (!deviceTried) {
// Signing in with this device's key. Showing a form here would be showing
// one the user is about to be taken past.
page = html`<p class="page-message">${t('status.connecting')}</p>`;
} else if (route === '/login' || route === '/register' || route === '/reset') {
page = route === '/register'
? html`<${RegisterPage} />`
: route === '/reset'
? html`<${ResetPasswordPage} onLogin=${authCtx.login} />`
: html`<${LoginPage} onLogin=${authCtx.login} />`;
} else if (!user) {
page = html`<${LoginPage} onLogin=${authCtx.login} />`;
} else if (route === '/search') {
page = html`<${SearchPage}
token=${user.token} username=${user.username} userId=${user.userId}
groups=${groups} userPrefs=${userPrefs}
onPlayQueue=${handlePlayQueue} />`;
} else if (route === '/explore') {
page = html`<${ExplorePage} token=${user.token}
myGroupIds=${groups.map(g => g.id)}
allowPublicGroups=${allowPublicGroups} />`;
} else if (route === '/create-group') {
page = html`<${LazyCreateGroupPage} token=${user.token} username=${user.username}
allowPublicGroups=${allowPublicGroups}
onCreated=${() => {
hubFetch('/v1/groups/mine', { token: user.token })
.then(data => setGroups(data.groups || []))
.catch(() => {});
}} />`;
} else if (route === '/node' && platform.capabilities.nodeAdmin && hasNodeKey) {
page = html`<${LazyNodePage} groups=${groups} />`;
} else if (route.startsWith('/group/')) {
const groupId = route.slice(7);
const group = groups.find(g => g.id === groupId);
page = html`<${GroupPage}
groupId=${groupId} group=${group} token=${user.token}
username=${user.username} userId=${user.userId}
userPrefs=${userPrefs}
onRefreshAuth=${refreshAuth} onJoined=${dismissGroupNotifications}
onGroupUpdated=${updateGroup} onPresence=${notePresence}
onLeft=${handleLeftGroup}
onPlayQueue=${handlePlayQueue} onStopMusic=${handleStopMusic} />`;
} else if (route === '/admin') {
page = (user.role === 'moderator' || user.role === 'admin')
? html`<${LazyAdminPage} token=${user.token} role=${user.role} />`
: html`<${HomePage} groups=${groups} notifications=${notifications}
allowPublicGroups=${allowPublicGroups}
onMarkRead=${markRead} onPurge=${purgeNotifications} />`;
} else if (route === '/settings') {
page = html`<${SettingsPage} user=${user} theme=${theme}
onThemeChange=${setTheme} groups=${groups}
onPrefsChange=${(p) => {
if ('notifications_disabled' in p) {
setNotifDisabled(p.notifications_disabled);
if (p.notifications_disabled) { setNotifications([]); setUnreadCount(0); }
else fetchNotifications();
}
setUserPrefs(prev => ({ ...prev, ...p }));
}} />`;
} else if (route === '/profile') {
page = html`<${ProfilePage} user=${user} onLogout=${authCtx.logout} />`;
} else {
page = html`<${HomePage} groups=${groups} notifications=${notifications}
allowPublicGroups=${allowPublicGroups}
onMarkRead=${markRead} onPurge=${purgeNotifications} />`;
}
return html`
<${AuthContext.Provider} value=${authCtx}>
<${Nav}
user=${user}
theme=${theme}
onThemeChange=${changeTheme}
onLogout=${authCtx.logout}
onMenuToggle=${() => setMenuOpen(o => !o)}
unreadCount=${unreadCount} hubUnset=${needsHub} />
<div class="layout">
${user && html`<${Sidebar}
groups=${groups}
presence=${presence}
indexProgressPct=${indexProgressPct}
route=${route}
menuOpen=${menuOpen}
role=${user.role}
allowPublicGroups=${allowPublicGroups}
hasNodeKey=${hasNodeKey} />`}
${menuOpen && html`<div class="overlay visible"
onClick=${() => setMenuOpen(false)} />`}
<main class="main">
${page}
</main>
</div>
${musicQueue && html`
<${MusicPlayerBar}
getConnection=${getMusicConnection}
queue=${musicQueue}
userPrefs=${userPrefs}
onClose=${handleStopMusic} />
`}
<//>
`;
}
// ── Boot ─────────────────────────────────────────────────────────────────────
// The tray menu's four strings. The main process has no i18n (see
// packages/meshbay-client/src/main.js), so they are translated here and sent
// over the bridge — once at boot, because the app now creates its indicator at
// launch rather than on the first minimise, and again from the nav button.
const trayLabels = () => ({
show: t('tray.show'), quit: t('tray.quit'),
start_node: t('tray.start_node'), stop_node: t('tray.stop_node'),
});
// Catalogues are fetched, so the first render waits for one: mounting earlier
// would paint the interface in English and then swap every string. initLocale()
// falls back to English rather than rejecting, so this cannot strand the page.
const mount = () => {
render(html`<${App} />`, document.getElementById('app'));
// Get the download worker registered and this page under its control now,
// rather than inside the first click on Download. On Firefox and Safari it is
// the only unbounded way to write a file to disk, and it used to be
// registered lazily — so the first download of a session paid install,
// activate and claim while somebody watched, and a claim that missed its
// budget sent the file to a path that cannot hold a film. Fire-and-forget:
// nothing renders differently for it, and a failure is retried on demand.
downloads.primeServiceWorker();
// After the catalogue, so the labels are in the right language. A no-op in a
// browser and on macOS. A language change reloads the page, which comes back
// through here, so nothing else has to watch for it.
platform.setTrayLabels(trayLabels()).catch(() => {});
};
initLocale().then(mount, (err) => {
// Nothing in initLocale() is supposed to reject. If something does, an
// English interface is still an interface; an unhandled rejection here is a
// blank page.
console.error('[MeshBay] locale init failed, continuing in English:', err);
mount();
});
|