Debian Codegraph @

web/src/components/App.jsx

raw
1 import * as React from "react";
2 import { Suspense, useContext, useEffect, useState, useMemo } from "react";
3 import { Box, Toolbar, CssBaseline, Backdrop, CircularProgress, useMediaQuery, ThemeProvider, createTheme } from "@mui/material";
4 import { useLiveQuery } from "dexie-react-hooks";
5 import { BrowserRouter, Outlet, Route, Routes, useParams } from "react-router-dom";
6 import { useTranslation } from "react-i18next";
7 import { AllSubscriptions, SingleSubscription } from "./Notifications";
8 import { darkTheme, lightTheme } from "./theme";
9 import Navigation from "./Navigation";
10 import ActionBar from "./ActionBar";
11 import Preferences from "./Preferences";
12 import subscriptionManager from "../app/SubscriptionManager";
13 import userManager from "../app/UserManager";
14 import { expandUrl, getKebabCaseLangStr, darkModeEnabled, updateFavicon } from "../app/utils";
15 import ErrorBoundary from "./ErrorBoundary";
16 import routes from "./routes";
17 import { useAccountListener, useBackgroundProcesses, useConnectionListeners, useWebPushTopics } from "./hooks";
18 import PublishDialog from "./PublishDialog";
19 import Messaging from "./Messaging";
20 import Login from "./Login";
21 import Signup from "./Signup";
22 import Account from "./Account";
23 import EmailVerify from "./EmailVerify";
24 import PasswordReset from "./PasswordReset";
25 import PasswordResetRequest from "./PasswordResetRequest";
26 import initI18n from "../app/i18n"; // Translations!
27 import prefs from "../app/Prefs";
28 import RTLCacheProvider from "./RTLCacheProvider";
29 import session from "../app/Session";
30 import AccountContext from "./AccountContext";
31 import { PrefCacheProvider } from "./PrefCache";
32 import hideSplash from "../app/splash";
33
34 initI18n();
35
36 const App = () => {
37 const { i18n } = useTranslation();
38 const languageDir = i18n.dir();
39 const [account, setAccount] = useState(null);
40 const accountMemo = useMemo(() => ({ account, setAccount }), [account, setAccount]);
41 const prefersDarkMode = useMediaQuery("(prefers-color-scheme: dark)");
42 const themePreference = useLiveQuery(() => prefs.theme());
43 const isDark = darkModeEnabled(prefersDarkMode, themePreference);
44 const theme = React.useMemo(() => createTheme({ ...(isDark ? darkTheme : lightTheme), direction: languageDir }), [isDark, languageDir]);
45
46 useEffect(() => {
47 document.documentElement.setAttribute("lang", getKebabCaseLangStr(i18n.language));
48 document.dir = languageDir;
49 }, [i18n.language, languageDir]);
50
51 // Keep the <html> background in sync with the theme once loaded. The splash script sets the
52 // initial class; don't override it while the preference is still loading.
53 useEffect(() => {
54 if (themePreference === undefined) {
55 return;
56 }
57 document.documentElement.classList.toggle("dark", isDark);
58 }, [isDark, themePreference]);
59
60 // Safety net: hide the splash even if no route does (e.g. an unmatched path).
61 useEffect(() => {
62 const timer = setTimeout(() => hideSplash(), 3000);
63 return () => clearTimeout(timer);
64 }, []);
65
66 useEffect(() => {
67 if (!session.exists() && config.require_login && window.location.pathname !== routes.login) {
68 window.location.href = routes.login;
69 }
70 }, []);
71
72 return (
73 <Suspense fallback={<Loader />}>
74 <RTLCacheProvider>
75 <BrowserRouter>
76 <ThemeProvider theme={theme}>
77 <AccountContext.Provider value={accountMemo}>
78 <CssBaseline />
79 <ErrorBoundary>
80 <Routes>
81 <Route element={<AuthLayout />}>
82 <Route path={routes.login} element={<Login />} />
83 <Route path={routes.signup} element={<Signup />} />
84 <Route path={routes.passwordResetRequest} element={<PasswordResetRequest />} />
85 <Route path={routes.passwordReset} element={<PasswordReset />} />
86 <Route path={routes.emailVerify} element={<EmailVerify />} />
87 </Route>
88 <Route element={<Layout />}>
89 <Route path={routes.app} element={<AllSubscriptions />} />
90 <Route path={routes.account} element={<Account />} />
91 <Route path={routes.settings} element={<Preferences />} />
92 <Route path={routes.subscription} element={<SingleSubscription />} />
93 <Route path={routes.subscriptionExternal} element={<SingleSubscription />} />
94 </Route>
95 </Routes>
96 </ErrorBoundary>
97 </AccountContext.Provider>
98 </ThemeProvider>
99 </BrowserRouter>
100 </RTLCacheProvider>
101 </Suspense>
102 );
103 };
104
105 const updateTitle = (newNotificationsCount) => {
106 document.title = newNotificationsCount > 0 ? `(${newNotificationsCount}) ntfy` : "ntfy";
107 window.navigator.setAppBadge?.(newNotificationsCount);
108 updateFavicon(newNotificationsCount);
109 };
110
111 // Auth pages render synchronously, so the splash can be removed on mount.
112 const AuthLayout = () => {
113 useEffect(() => hideSplash(), []);
114 return <Outlet />;
115 };
116
117 const Layout = () => {
118 const params = useParams();
119 const { account, setAccount } = useContext(AccountContext);
120 const [mobileDrawerOpen, setMobileDrawerOpen] = useState(false);
121 const [sendDialogOpenMode, setSendDialogOpenMode] = useState("");
122 const users = useLiveQuery(() => userManager.all());
123 const subscriptions = useLiveQuery(() => subscriptionManager.all());
124 // Preloaded here so the All view (and single topics, via filter) have data on mount -- no empty
125 // frame when switching.
126 const allNotifications = useLiveQuery(() => subscriptionManager.getAllNotifications());
127 const webPushTopics = useWebPushTopics();
128 const subscriptionsWithoutInternal = subscriptions?.filter((s) => !s.internal);
129 const newNotificationsCount = subscriptionsWithoutInternal?.reduce((prev, cur) => prev + cur.new, 0) || 0;
130 const [selected] = (subscriptionsWithoutInternal || []).filter(
131 (s) =>
132 (params.baseUrl && expandUrl(params.baseUrl).includes(s.baseUrl) && params.topic === s.topic) ||
133 (config.base_url === s.baseUrl && params.topic === s.topic),
134 );
135
136 useConnectionListeners(account, subscriptions, users, webPushTopics);
137 useAccountListener(setAccount);
138 useBackgroundProcesses();
139 useEffect(() => updateTitle(newNotificationsCount), [newNotificationsCount]);
140
141 // Hide the splash only once subscriptions have loaded, so the nav/list don't pop in empty-then-filled.
142 useEffect(() => {
143 if (subscriptions !== undefined) {
144 hideSplash();
145 }
146 }, [subscriptions]);
147
148 return (
149 <PrefCacheProvider>
150 <Box sx={{ display: "flex" }}>
151 <ActionBar selected={selected} onMobileDrawerToggle={() => setMobileDrawerOpen(!mobileDrawerOpen)} />
152 <Navigation
153 subscriptions={subscriptionsWithoutInternal}
154 selectedSubscription={selected}
155 mobileDrawerOpen={mobileDrawerOpen}
156 onMobileDrawerToggle={() => setMobileDrawerOpen(!mobileDrawerOpen)}
157 onPublishMessageClick={() => setSendDialogOpenMode(PublishDialog.OPEN_MODE_DEFAULT)}
158 />
159 <Main>
160 <Toolbar />
161 <Outlet
162 context={{
163 subscriptions: subscriptionsWithoutInternal,
164 selected,
165 allNotifications,
166 }}
167 />
168 </Main>
169 <Messaging selected={selected} dialogOpenMode={sendDialogOpenMode} onDialogOpenModeChange={setSendDialogOpenMode} />
170 </Box>
171 </PrefCacheProvider>
172 );
173 };
174
175 const Main = (props) => (
176 <Box
177 id="main"
178 component="main"
179 sx={{
180 display: "flex",
181 flexGrow: 1,
182 flexDirection: "column",
183 padding: { xs: 0, md: 3 },
184 width: { sm: `calc(100% - ${Navigation.width}px)` },
185 height: "100dvh",
186 overflow: "auto",
187 backgroundColor: ({ palette }) => (palette.mode === "light" ? palette.grey[100] : palette.grey[900]),
188 }}
189 >
190 {props.children}
191 </Box>
192 );
193
194 const Loader = () => (
195 <Backdrop
196 open
197 sx={{
198 zIndex: 100000,
199 backgroundColor: ({ palette }) => (palette.mode === "light" ? palette.grey[100] : palette.grey[900]),
200 }}
201 >
202 <CircularProgress color="success" disableShrink />
203 </Backdrop>
204 );
205
206 export default App;