@peers-app/peers-ui 0.21.2 → 0.21.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/dist/screens/network-viewer/connection-troubleshooter.js +1 -1
  2. package/dist/screens/network-viewer/device-details-modal.js +11 -15
  3. package/dist/screens/network-viewer/group-details-modal.js +60 -17
  4. package/dist/screens/network-viewer/network-viewer-ipc.d.ts +9 -39
  5. package/dist/screens/network-viewer/network-viewer-ipc.js +71 -3
  6. package/dist/screens/network-viewer/network-viewer-ipc.test.d.ts +1 -0
  7. package/dist/screens/network-viewer/network-viewer-ipc.test.js +59 -0
  8. package/dist/screens/network-viewer/network-viewer.js +46 -60
  9. package/dist/screens/network-viewer/remote-logs-panel.js +11 -12
  10. package/dist/tabs-layout/network-status-indicator.d.ts +41 -0
  11. package/dist/tabs-layout/network-status-indicator.js +261 -0
  12. package/dist/tabs-layout/network-status-indicator.test.d.ts +1 -0
  13. package/dist/tabs-layout/network-status-indicator.test.js +333 -0
  14. package/dist/tabs-layout/tabs-layout.js +25 -24
  15. package/dist/tabs-layout/use-network-status.d.ts +8 -0
  16. package/dist/tabs-layout/use-network-status.js +57 -0
  17. package/dist/tabs-layout/use-network-status.test.d.ts +1 -0
  18. package/dist/tabs-layout/use-network-status.test.js +42 -0
  19. package/package.json +3 -3
  20. package/src/screens/network-viewer/connection-troubleshooter.tsx +2 -2
  21. package/src/screens/network-viewer/device-details-modal.tsx +19 -61
  22. package/src/screens/network-viewer/group-details-modal.tsx +211 -130
  23. package/src/screens/network-viewer/network-viewer-ipc.test.ts +70 -0
  24. package/src/screens/network-viewer/network-viewer-ipc.ts +102 -35
  25. package/src/screens/network-viewer/network-viewer.tsx +76 -148
  26. package/src/screens/network-viewer/remote-logs-panel.tsx +14 -16
  27. package/src/tabs-layout/network-status-indicator.test.tsx +391 -0
  28. package/src/tabs-layout/network-status-indicator.tsx +475 -0
  29. package/src/tabs-layout/tabs-layout.tsx +4 -1
  30. package/src/tabs-layout/use-network-status.test.tsx +55 -0
  31. package/src/tabs-layout/use-network-status.ts +68 -0
@@ -0,0 +1,475 @@
1
+ import type { INetworkConnectionInfo, INetworkStatusSummary } from "@peers-app/peers-sdk";
2
+ import moment from "moment";
3
+ import { useEffect, useId, useRef, useState } from "react";
4
+ import { getNetworkDiagnosticsConsumer } from "../screens/network-viewer/network-viewer-ipc";
5
+ import { goToTabPath } from "./tabs-state";
6
+ import { type INetworkStatusViewState, useNetworkStatus } from "./use-network-status";
7
+
8
+ /** How long continuous raw syncing stays a green pulse before the indeterminate circle. */
9
+ export const SYNCING_GREEN_MS = 2_000;
10
+
11
+ /** How long status must stay fully synced before leaving the syncing visual. */
12
+ export const SYNCED_STABLE_MS = 1_000;
13
+
14
+ /** Slightly slower than Bootstrap's default spinner-grow (~0.75s). */
15
+ const PULSE_ANIMATION_DURATION = "1.0s";
16
+
17
+ const DOT_SIZE = "0.7rem";
18
+
19
+ type NetworkStatusMark = "solid" | "pulse" | "indeterminate";
20
+
21
+ type ConnectionsLoadState =
22
+ | { status: "idle" }
23
+ | { status: "loading" }
24
+ | { status: "ready"; connections: INetworkConnectionInfo[] }
25
+ | { status: "error" };
26
+
27
+ interface INetworkStatusPresentation {
28
+ label: string;
29
+ shortLabel: string;
30
+ colorClass: string;
31
+ /** Bootstrap Icons class when not using a status mark. */
32
+ iconClass?: string;
33
+ spinning?: boolean;
34
+ /** Size the Bootstrap icon to match the status marks. */
35
+ compactIcon?: boolean;
36
+ /** Solid / pulsing / indeterminate mark (syncing / error). */
37
+ mark?: NetworkStatusMark;
38
+ }
39
+
40
+ /** Convert host availability and network state into accessible indicator text and styling. */
41
+ export function getNetworkStatusPresentation(
42
+ viewState: INetworkStatusViewState,
43
+ opts?: {
44
+ syncingLongerThanGreenMs?: boolean;
45
+ /** Keep the calm green syncing pulse while waiting for stable synced. */
46
+ holdSyncingVisual?: boolean;
47
+ },
48
+ ): INetworkStatusPresentation {
49
+ if (viewState.availability === "loading") {
50
+ return {
51
+ label: "Network status loading",
52
+ shortLabel: "Loading",
53
+ iconClass: "bi-arrow-repeat",
54
+ colorClass: "text-secondary",
55
+ spinning: true,
56
+ };
57
+ }
58
+ if (viewState.availability === "unavailable" || !viewState.status) {
59
+ return {
60
+ label: "Network status unavailable",
61
+ shortLabel: "Unavailable",
62
+ iconClass: "bi-question-circle",
63
+ colorClass: "text-secondary",
64
+ };
65
+ }
66
+ const { connectionCount, errorCount, state, syncingContextCount } = viewState.status;
67
+ if (state === "error") {
68
+ return {
69
+ label: `Network error; ${errorCount} sync ${errorCount === 1 ? "error" : "errors"}; ${connectionCount} active ${connectionCount === 1 ? "connection" : "connections"}`,
70
+ shortLabel: "Error",
71
+ colorClass: "text-danger",
72
+ mark: "solid",
73
+ };
74
+ }
75
+ if (state === "syncing" || opts?.holdSyncingVisual) {
76
+ const longSync = state === "syncing" && opts?.syncingLongerThanGreenMs === true;
77
+ const contextsLabel =
78
+ state === "syncing"
79
+ ? `${syncingContextCount} ${syncingContextCount === 1 ? "context" : "contexts"}`
80
+ : "recent activity";
81
+ return {
82
+ label: `Network syncing ${contextsLabel}; ${connectionCount} active ${connectionCount === 1 ? "connection" : "connections"}`,
83
+ shortLabel: "Syncing",
84
+ colorClass: longSync ? "text-primary" : "text-success",
85
+ mark: longSync ? "indeterminate" : "pulse",
86
+ };
87
+ }
88
+ if (state === "offline") {
89
+ return {
90
+ label: "Network offline; no active connections",
91
+ shortLabel: "Offline",
92
+ iconClass: "bi-cloud-slash-fill",
93
+ colorClass: "text-secondary",
94
+ };
95
+ }
96
+ return {
97
+ label: `Network synced; ${connectionCount} active ${connectionCount === 1 ? "connection" : "connections"}`,
98
+ shortLabel: "Synced",
99
+ iconClass: "bi-check-circle-fill",
100
+ colorClass: "text-success",
101
+ compactIcon: true,
102
+ };
103
+ }
104
+
105
+ function StatusMark({ mode, colorClass }: { mode: NetworkStatusMark; colorClass: string }) {
106
+ if (mode === "pulse") {
107
+ return (
108
+ <span
109
+ className={`spinner-grow spinner-grow-sm ${colorClass}`}
110
+ style={{
111
+ width: DOT_SIZE,
112
+ height: DOT_SIZE,
113
+ animationDuration: PULSE_ANIMATION_DURATION,
114
+ }}
115
+ aria-hidden="true"
116
+ />
117
+ );
118
+ }
119
+ if (mode === "indeterminate") {
120
+ return (
121
+ <span
122
+ className={`spinner-border spinner-border-sm ${colorClass}`}
123
+ style={{ width: DOT_SIZE, height: DOT_SIZE, borderWidth: "0.12em" }}
124
+ aria-hidden="true"
125
+ />
126
+ );
127
+ }
128
+ const bgClass =
129
+ colorClass === "text-danger"
130
+ ? "bg-danger"
131
+ : colorClass === "text-primary"
132
+ ? "bg-primary"
133
+ : "bg-success";
134
+ return (
135
+ <span
136
+ className={`rounded-circle ${bgClass}`}
137
+ style={{ width: DOT_SIZE, height: DOT_SIZE, display: "inline-block" }}
138
+ aria-hidden="true"
139
+ />
140
+ );
141
+ }
142
+
143
+ /** Compact relative time for the status popover (always short enough for one line). */
144
+ export function formatRelativeSyncTime(timestampMs: number, nowMs = Date.now()): string {
145
+ const then = moment(timestampMs);
146
+ const now = moment(nowMs);
147
+ if (now.diff(then, "seconds") < 45) {
148
+ return "now";
149
+ }
150
+ if (now.clone().subtract(1, "day").isSame(then, "day")) {
151
+ return "yesterday";
152
+ }
153
+ return then.from(now);
154
+ }
155
+
156
+ function middleEllipsis(value: string, head = 4, tail = 4): string {
157
+ if (value.length <= head + tail + 1) {
158
+ return value;
159
+ }
160
+ return `${value.slice(0, head)}…${value.slice(-tail)}`;
161
+ }
162
+
163
+ /** Prefer a friendly name; otherwise a compact middle-ellipsis of the id. */
164
+ export function connectionIdentityLabel(
165
+ name: string | undefined,
166
+ id: string,
167
+ ): { text: string; isId: boolean; title: string } {
168
+ const trimmed = name?.trim();
169
+ if (trimmed) {
170
+ return { text: trimmed, isId: false, title: trimmed };
171
+ }
172
+ return { text: middleEllipsis(id), isId: true, title: id };
173
+ }
174
+
175
+ function IdentityPart({ label }: { label: { text: string; isId: boolean; title: string } }) {
176
+ return (
177
+ <span
178
+ className={`text-truncate ${label.isId ? "text-muted" : ""}`}
179
+ style={{
180
+ minWidth: 0,
181
+ ...(label.isId ? { fontSize: "0.7rem" } : undefined),
182
+ }}
183
+ title={label.title}
184
+ >
185
+ {label.text}
186
+ </span>
187
+ );
188
+ }
189
+
190
+ function ConnectedDeviceRow({ connection }: { connection: INetworkConnectionInfo }) {
191
+ const user = connectionIdentityLabel(connection.userName, connection.userId);
192
+ const device = connectionIdentityLabel(connection.deviceName, connection.deviceId);
193
+ const groupCount = connection.sharedGroups.length;
194
+
195
+ return (
196
+ <li
197
+ className="d-flex align-items-baseline gap-1 py-1"
198
+ style={{ listStyle: "none", minWidth: 0 }}
199
+ >
200
+ <IdentityPart label={user} />
201
+ <span className="text-muted flex-shrink-0" aria-hidden="true">
202
+ ·
203
+ </span>
204
+ <IdentityPart label={device} />
205
+ {groupCount > 0 && (
206
+ <span
207
+ className="text-muted flex-shrink-0 ms-auto"
208
+ style={{ fontSize: "0.7rem" }}
209
+ title={`${groupCount} ${groupCount === 1 ? "group" : "groups"}`}
210
+ >
211
+ {groupCount}g
212
+ </span>
213
+ )}
214
+ </li>
215
+ );
216
+ }
217
+
218
+ function ConnectedDevicesList({ loadState }: { loadState: ConnectionsLoadState }) {
219
+ if (loadState.status === "idle" || loadState.status === "loading") {
220
+ return <p className="small text-muted mb-2">Loading…</p>;
221
+ }
222
+ if (loadState.status === "error") {
223
+ return <p className="small text-muted mb-2">Couldn't load devices</p>;
224
+ }
225
+ if (loadState.connections.length === 0) {
226
+ return <p className="small text-muted mb-2">No connected devices</p>;
227
+ }
228
+ return (
229
+ <ul className="small mb-0 ps-0" style={{ maxHeight: "180px", overflowY: "auto" }}>
230
+ {loadState.connections.map((connection) => (
231
+ <ConnectedDeviceRow key={connection.deviceId} connection={connection} />
232
+ ))}
233
+ </ul>
234
+ );
235
+ }
236
+
237
+ function NetworkStatusDetails({
238
+ detailsId,
239
+ status,
240
+ unavailable,
241
+ connectionsLoadState,
242
+ onOpenViewer,
243
+ }: {
244
+ detailsId: string;
245
+ status?: INetworkStatusSummary;
246
+ unavailable: boolean;
247
+ connectionsLoadState: ConnectionsLoadState;
248
+ onOpenViewer: () => void;
249
+ }) {
250
+ return (
251
+ <div
252
+ id={detailsId}
253
+ role="dialog"
254
+ aria-label="Network status details"
255
+ className="card shadow position-absolute end-0 mt-1"
256
+ style={{ top: "100%", width: "320px", zIndex: 1100 }}
257
+ >
258
+ <div className="card-body p-3">
259
+ <h6 className="card-title mb-2">Network status</h6>
260
+ {unavailable || !status ? (
261
+ <p className="small text-muted mb-3">
262
+ Network diagnostics are temporarily unavailable. The local host may still be starting or
263
+ reconnecting.
264
+ </p>
265
+ ) : (
266
+ <>
267
+ <dl className="row small mb-2">
268
+ <dt className="col-7">Connections</dt>
269
+ <dd className="col-5 text-end">{status.connectionCount}</dd>
270
+ <dt className="col-7">Syncing contexts</dt>
271
+ <dd className="col-5 text-end">{status.syncingContextCount}</dd>
272
+ <dt className="col-7">Sync errors</dt>
273
+ <dd className="col-5 text-end">{status.errorCount}</dd>
274
+ {status.lastSuccessfulSyncAt != null && (
275
+ <>
276
+ <dt className="col-7">Last sync</dt>
277
+ <dd
278
+ className="col-5 text-end text-truncate"
279
+ title={new Date(status.lastSuccessfulSyncAt).toLocaleString()}
280
+ >
281
+ {formatRelativeSyncTime(status.lastSuccessfulSyncAt)}
282
+ </dd>
283
+ </>
284
+ )}
285
+ </dl>
286
+ {status.errors.length > 0 && (
287
+ <div className="alert alert-danger py-2 px-2 small mb-2">
288
+ {status.errors[0].message}
289
+ {status.errors.length > 1 && ` (+${status.errors.length - 1} more)`}
290
+ </div>
291
+ )}
292
+ <div className="border-top pt-2 mt-1 mb-2">
293
+ <div className="small text-muted mb-1">Devices</div>
294
+ <ConnectedDevicesList loadState={connectionsLoadState} />
295
+ </div>
296
+ </>
297
+ )}
298
+ <button
299
+ type="button"
300
+ className="btn btn-sm btn-outline-primary w-100"
301
+ onClick={onOpenViewer}
302
+ >
303
+ Open Network Viewer
304
+ </button>
305
+ </div>
306
+ </div>
307
+ );
308
+ }
309
+
310
+ /** Accessible reactive network status button and details popover. */
311
+ export function NetworkStatusIndicator({ compact = false }: { compact?: boolean }) {
312
+ const viewState = useNetworkStatus();
313
+ const [displaySyncing, setDisplaySyncing] = useState(false);
314
+ const [syncingLongerThanGreenMs, setSyncingLongerThanGreenMs] = useState(false);
315
+ const [open, setOpen] = useState(false);
316
+ const [connectionsLoadState, setConnectionsLoadState] = useState<ConnectionsLoadState>({
317
+ status: "idle",
318
+ });
319
+ const containerRef = useRef<HTMLDivElement>(null);
320
+ const detailsId = useId();
321
+
322
+ const rawState = viewState.availability === "ready" ? viewState.status?.state : undefined;
323
+ const rawIsSyncing = rawState === "syncing";
324
+ const rawIsSynced = rawState === "synced";
325
+ const connectionCount = viewState.status?.connectionCount;
326
+ const diagnosticsReady = viewState.availability === "ready";
327
+
328
+ useEffect(() => {
329
+ if (rawIsSyncing) {
330
+ setDisplaySyncing(true);
331
+ return;
332
+ }
333
+ if (rawIsSynced) {
334
+ if (!displaySyncing) {
335
+ return;
336
+ }
337
+ const timer = window.setTimeout(() => {
338
+ setDisplaySyncing(false);
339
+ }, SYNCED_STABLE_MS);
340
+ return () => {
341
+ window.clearTimeout(timer);
342
+ };
343
+ }
344
+ setDisplaySyncing(false);
345
+ }, [rawIsSyncing, rawIsSynced, displaySyncing]);
346
+
347
+ useEffect(() => {
348
+ if (!rawIsSyncing) {
349
+ setSyncingLongerThanGreenMs(false);
350
+ return;
351
+ }
352
+ const timer = window.setTimeout(() => {
353
+ setSyncingLongerThanGreenMs(true);
354
+ }, SYNCING_GREEN_MS);
355
+ return () => {
356
+ window.clearTimeout(timer);
357
+ };
358
+ }, [rawIsSyncing]);
359
+
360
+ useEffect(() => {
361
+ if (!open || !diagnosticsReady) {
362
+ setConnectionsLoadState({ status: "idle" });
363
+ return;
364
+ }
365
+ let active = true;
366
+ setConnectionsLoadState({ status: "loading" });
367
+ void getNetworkDiagnosticsConsumer()
368
+ .then((diagnostics) => diagnostics.tools.getConnections())
369
+ .then((result) => {
370
+ if (active) {
371
+ setConnectionsLoadState({ status: "ready", connections: result.connections });
372
+ }
373
+ })
374
+ .catch(() => {
375
+ if (active) {
376
+ setConnectionsLoadState({ status: "error" });
377
+ }
378
+ });
379
+ return () => {
380
+ active = false;
381
+ };
382
+ }, [open, diagnosticsReady, connectionCount]);
383
+
384
+ const holdSyncingVisual = displaySyncing && !rawIsSyncing;
385
+ const presentation = getNetworkStatusPresentation(viewState, {
386
+ syncingLongerThanGreenMs,
387
+ holdSyncingVisual,
388
+ });
389
+
390
+ useEffect(() => {
391
+ if (!open) {
392
+ return;
393
+ }
394
+ const closeOutside = (event: MouseEvent) => {
395
+ if (!containerRef.current?.contains(event.target as Node)) {
396
+ setOpen(false);
397
+ }
398
+ };
399
+ const closeOnEscape = (event: KeyboardEvent) => {
400
+ if (event.key === "Escape") {
401
+ setOpen(false);
402
+ }
403
+ };
404
+ document.addEventListener("mousedown", closeOutside);
405
+ document.addEventListener("keydown", closeOnEscape);
406
+ return () => {
407
+ document.removeEventListener("mousedown", closeOutside);
408
+ document.removeEventListener("keydown", closeOnEscape);
409
+ };
410
+ }, [open]);
411
+
412
+ return (
413
+ <div ref={containerRef} className="position-relative d-flex align-items-center">
414
+ <button
415
+ type="button"
416
+ className={`btn btn-sm d-flex align-items-center gap-1 px-2 ${presentation.colorClass}`}
417
+ style={{
418
+ border: "none",
419
+ background: "transparent",
420
+ minWidth: compact ? "30px" : undefined,
421
+ }}
422
+ aria-label={presentation.label}
423
+ aria-expanded={open}
424
+ aria-controls={detailsId}
425
+ title={presentation.label}
426
+ onClick={() => setOpen((current) => !current)}
427
+ >
428
+ {presentation.mark ? (
429
+ <StatusMark mode={presentation.mark} colorClass={presentation.colorClass} />
430
+ ) : (
431
+ <i
432
+ className={`bi ${presentation.iconClass} ${presentation.spinning ? "spin" : ""}`}
433
+ style={
434
+ presentation.compactIcon
435
+ ? { fontSize: DOT_SIZE, lineHeight: 1, display: "inline-block" }
436
+ : undefined
437
+ }
438
+ aria-hidden="true"
439
+ />
440
+ )}
441
+ {!compact && (
442
+ <span className="small">
443
+ {viewState.status?.connectionCount ?? 0}
444
+ <span className="visually-hidden"> connections</span>
445
+ </span>
446
+ )}
447
+ </button>
448
+ {open && (
449
+ <NetworkStatusDetails
450
+ detailsId={detailsId}
451
+ status={viewState.status}
452
+ unavailable={viewState.availability !== "ready"}
453
+ connectionsLoadState={connectionsLoadState}
454
+ onOpenViewer={() => {
455
+ setOpen(false);
456
+ goToTabPath("network-viewer");
457
+ }}
458
+ />
459
+ )}
460
+ </div>
461
+ );
462
+ }
463
+
464
+ /** Fixed tabs-strip area for built-in shell indicators. */
465
+ export function TabsStripIndicators({ compact = false }: { compact?: boolean }) {
466
+ return (
467
+ <div
468
+ className="d-flex align-items-center flex-shrink-0"
469
+ role="group"
470
+ aria-label="Application status"
471
+ >
472
+ <NetworkStatusIndicator compact={compact} />
473
+ </div>
474
+ );
475
+ }
@@ -14,6 +14,7 @@ import { colorMode } from "../screens/settings/color-mode-dropdown";
14
14
  import { systemPackage } from "../system-apps";
15
15
  import { allPackages } from "../ui-router/routes-loader";
16
16
  import { UIRouter } from "../ui-router/ui-loader";
17
+ import { TabsStripIndicators } from "./network-status-indicator";
17
18
  import {
18
19
  activeTabId,
19
20
  activeTabs,
@@ -246,6 +247,7 @@ export function TabsLayoutInternal({ fillContainer = false }: { fillContainer?:
246
247
  />
247
248
  ))}
248
249
  </div>
250
+ <TabsStripIndicators />
249
251
  </div>
250
252
  )}
251
253
  </div>
@@ -314,7 +316,8 @@ function MobileTabsHeader({
314
316
  </div>
315
317
 
316
318
  {/* Right Side - Hamburger Menu */}
317
- <div className="d-flex align-items-center">
319
+ <div className="d-flex align-items-center gap-1">
320
+ <TabsStripIndicators compact />
318
321
  <div className="dropdown">
319
322
  <button
320
323
  type="button"
@@ -0,0 +1,55 @@
1
+ import {
2
+ type INetworkDiagnosticsConsumer,
3
+ type INetworkStatusSummary,
4
+ inProcessTransportPair,
5
+ observable,
6
+ registerHostContractTransport,
7
+ } from "@peers-app/peers-sdk";
8
+ import { act, renderHook, waitFor } from "@testing-library/react";
9
+ import { getNetworkDiagnosticsConsumer } from "../screens/network-viewer/network-viewer-ipc";
10
+ import { useNetworkStatus } from "./use-network-status";
11
+
12
+ jest.mock("../screens/network-viewer/network-viewer-ipc", () => ({
13
+ getNetworkDiagnosticsConsumer: jest.fn(),
14
+ }));
15
+
16
+ const mockGetDiagnostics = getNetworkDiagnosticsConsumer as jest.MockedFunction<
17
+ typeof getNetworkDiagnosticsConsumer
18
+ >;
19
+
20
+ function makeStatus(overrides: Partial<INetworkStatusSummary> = {}): INetworkStatusSummary {
21
+ return {
22
+ state: "offline",
23
+ connectionCount: 0,
24
+ syncingContextCount: 0,
25
+ errorCount: 0,
26
+ errors: [],
27
+ ...overrides,
28
+ };
29
+ }
30
+
31
+ describe("useNetworkStatus", () => {
32
+ it("streams status updates and reports host disconnection", async () => {
33
+ const status = observable(makeStatus());
34
+ mockGetDiagnostics.mockResolvedValue({
35
+ observables: { status },
36
+ } as INetworkDiagnosticsConsumer);
37
+ const [transport] = inProcessTransportPair();
38
+ const disposeTransport = registerHostContractTransport(transport);
39
+ const hook = renderHook(() => useNetworkStatus());
40
+
41
+ await waitFor(() => expect(hook.result.current.availability).toBe("ready"));
42
+ expect(hook.result.current.status?.state).toBe("offline");
43
+
44
+ act(() => {
45
+ status(makeStatus({ state: "syncing", connectionCount: 2, syncingContextCount: 1 }));
46
+ });
47
+ await waitFor(() => expect(hook.result.current.status?.state).toBe("syncing"));
48
+
49
+ act(() => {
50
+ disposeTransport();
51
+ });
52
+ await waitFor(() => expect(hook.result.current.availability).toBe("unavailable"));
53
+ hook.unmount();
54
+ });
55
+ });
@@ -0,0 +1,68 @@
1
+ import {
2
+ type INetworkStatusSummary,
3
+ type Subscription,
4
+ subscribeHostContractTransport,
5
+ } from "@peers-app/peers-sdk";
6
+ import { useEffect, useState } from "react";
7
+ import { getNetworkDiagnosticsConsumer } from "../screens/network-viewer/network-viewer-ipc";
8
+
9
+ /** Host availability plus the latest reactive network status snapshot. */
10
+ export interface INetworkStatusViewState {
11
+ availability: "loading" | "ready" | "unavailable";
12
+ status?: INetworkStatusSummary;
13
+ }
14
+
15
+ /** Subscribe to the current host's System Network Diagnostics status observable. */
16
+ export function useNetworkStatus(): INetworkStatusViewState {
17
+ const [viewState, setViewState] = useState<INetworkStatusViewState>({
18
+ availability: "loading",
19
+ });
20
+
21
+ useEffect(() => {
22
+ let active = true;
23
+ let generation = 0;
24
+ let statusSubscription: Subscription | undefined;
25
+ let hadTransport = false;
26
+ const unsubscribeTransport = subscribeHostContractTransport((transport) => {
27
+ generation += 1;
28
+ const currentGeneration = generation;
29
+ statusSubscription?.dispose();
30
+ statusSubscription = undefined;
31
+ if (!transport) {
32
+ setViewState({ availability: hadTransport ? "unavailable" : "loading" });
33
+ return;
34
+ }
35
+ hadTransport = true;
36
+ setViewState({ availability: "loading" });
37
+ void getNetworkDiagnosticsConsumer()
38
+ .then((diagnostics) => {
39
+ if (!active || generation !== currentGeneration) {
40
+ return;
41
+ }
42
+ setViewState({
43
+ availability: "ready",
44
+ status: diagnostics.observables.status(),
45
+ });
46
+ statusSubscription = diagnostics.observables.status.subscribe((status) => {
47
+ if (active && generation === currentGeneration) {
48
+ setViewState({ availability: "ready", status });
49
+ }
50
+ });
51
+ })
52
+ .catch(() => {
53
+ if (active && generation === currentGeneration) {
54
+ setViewState({ availability: "unavailable" });
55
+ }
56
+ });
57
+ });
58
+
59
+ return () => {
60
+ active = false;
61
+ generation += 1;
62
+ statusSubscription?.dispose();
63
+ unsubscribeTransport();
64
+ };
65
+ }, []);
66
+
67
+ return viewState;
68
+ }