Repository navigation
Expand file tree
/
Copy pathApp.tsx
More file actions
139 lines (130 loc) · 4.99 KB
/
Copy pathApp.tsx
File metadata and controls
139 lines (130 loc) · 4.99 KB
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
import type { Site } from '@pulse/core';
import { useEffect, useRef, useState } from 'react';
import { ErrorBoundary } from './components/ErrorBoundary';
import { Footer } from './components/Footer';
import { Header } from './components/Header';
import { ShortcutsDialog } from './components/ShortcutsDialog';
import type { DataSource } from './data/source';
import { DataSourceContext } from './hooks/useDataSource';
import { useHotkeys } from './hooks/useHotkeys';
import { PRESETS, isLive } from './lib/ranges';
import { AnalyticsPage, type AnalyticsPageHandle } from './pages/AnalyticsPage';
import { UptimePage } from './pages/UptimePage';
import { useLive } from './state/live';
import { readHash, selectRange, useDashboard, writeHash } from './state/store';
const REFRESH_MS = 10_000;
export function App({ dataSource }: { dataSource: DataSource }) {
const [sites, setSites] = useState<Site[] | null>(null);
const [error, setError] = useState<string | null>(null);
const s = useDashboard();
const analyticsRef = useRef<AnalyticsPageHandle>(null);
useEffect(() => {
dataSource
.sites()
.then((list) => {
setSites(list);
const st = useDashboard.getState();
if (!st.siteId || !list.some((x) => x.id === st.siteId)) st.setSite(list[0]?.id ?? '');
})
.catch((e: unknown) => setError(e instanceof Error ? e.message : String(e)));
}, [dataSource]);
// Day presets start at the selected site's midnight, as the server's day buckets do.
useEffect(() => {
useDashboard.getState().setTimeZone(sites?.find((x) => x.id === s.siteId)?.timeZone ?? null);
}, [sites, s.siteId]);
// Two-way sync between the URL hash and the current view / open monitor.
useEffect(() => {
const apply = () => useDashboard.setState(readHash(location.hash));
apply();
window.addEventListener('hashchange', apply);
const unsub = useDashboard.subscribe((st) => {
const next = writeHash(st);
if (location.hash !== next) history.replaceState(null, '', next);
});
return () => {
window.removeEventListener('hashchange', apply);
unsub();
};
}, []);
// Live stream for the selected site.
useEffect(() => {
if (!s.siteId) return;
const live = useLive.getState();
live.reset(s.siteId);
const siteId = s.siteId;
dataSource
.realtime(siteId)
.then((rt) => useLive.getState().seed(siteId, rt.active, rt.recent))
.catch(() => undefined);
return dataSource.subscribe(siteId, (m) => {
if (!useDashboard.getState().paused) useLive.getState().apply(m);
});
}, [dataSource, s.siteId]);
// Auto-refresh while the window reaches "now".
useEffect(() => {
const t = setInterval(() => {
const st = useDashboard.getState();
if (st.paused || document.hidden) return;
if (st.view === 'uptime' || isLive(selectRange(st), Date.now())) st.refresh();
}, REFRESH_MS);
return () => clearInterval(t);
}, []);
useHotkeys({
a: () => s.setView('analytics'),
u: () => s.setView('uptime'),
...Object.fromEntries(PRESETS.map((p) => [p.key, () => s.setPreset(p.id)])),
c: () => s.setRangeOpen(true),
ArrowLeft: () => s.shift(-1),
ArrowRight: () => s.shift(1),
s: () => {
if (!sites?.length) return;
const i = sites.findIndex((x) => x.id === s.siteId);
s.setSite(sites[(i + 1) % sites.length]!.id);
},
v: () => s.setMetric(s.metric === 'visitors' ? 'pageviews' : 'visitors'),
'/': () => {
s.setView('analytics');
requestAnimationFrame(() => analyticsRef.current?.focusSearch());
},
e: () => analyticsRef.current?.exportCsv(),
l: () => s.togglePaused(),
'?': () => s.setHelpOpen(true),
Escape: () => {
if (s.helpOpen) s.setHelpOpen(false);
else if (s.rangeOpen) s.setRangeOpen(false);
else if (s.monitorId) s.openMonitor(null);
},
});
return (
<DataSourceContext.Provider value={dataSource}>
<a className="skip-link" href="#main">
Skip to content
</a>
<div className="app">
<Header sites={sites ?? []} sourceKind={dataSource.kind} />
{error ? (
<main className="page">
<div className="error">
Could not reach the Pulse API: {error}. Start the server (<code>npm run dev:api</code>
) or open the demo mode (<code>?source=demo</code>).
</div>
</main>
) : s.view === 'uptime' ? (
<ErrorBoundary label="Uptime view failed">
<UptimePage />
</ErrorBoundary>
) : s.siteId ? (
<ErrorBoundary label="Analytics view failed">
<AnalyticsPage ref={analyticsRef} siteId={s.siteId} />
</ErrorBoundary>
) : (
<main className="page">
<div className="skeleton" style={{ height: 480 }} aria-label="Loading" />
</main>
)}
<Footer sourceKind={dataSource.kind} />
</div>
<ShortcutsDialog open={s.helpOpen} onClose={() => s.setHelpOpen(false)} />
</DataSourceContext.Provider>
);
}