Debian Codegraph @

web/src/components/Notifications.jsx

raw
1 import {
2 Container,
3 ButtonBase,
4 CardActions,
5 CardContent,
6 CircularProgress,
7 Fade,
8 Link,
9 Modal,
10 Snackbar,
11 Stack,
12 Tooltip,
13 Card,
14 Typography,
15 IconButton,
16 Box,
17 Button,
18 } from "@mui/material";
19 import * as React from "react";
20 import { Suspense, lazy, useEffect, useMemo, useState } from "react";
21 import CheckIcon from "@mui/icons-material/Check";
22 import CloseIcon from "@mui/icons-material/Close";
23 import InfiniteScroll from "react-infinite-scroll-component";
24 import { Trans, useTranslation } from "react-i18next";
25 import { useOutletContext } from "react-router-dom";
26 import { copyToClipboard, formatBytes, formatDateTime, maybeActionErrors, openUrl, shortUrl, topicUrl, unmatchedTags } from "../app/utils";
27 import { ACTION_BROADCAST, ACTION_COPY, ACTION_HTTP, ACTION_VIEW } from "../app/actions";
28 import { formatMessage, formatTitle, isImage } from "../app/notificationUtils";
29 import { LightboxBackdrop, Paragraph, VerticallyCenteredContainer } from "./styles";
30 import subscriptionManager from "../app/SubscriptionManager";
31 import notifier from "../app/Notifier";
32 import priority1 from "../img/priority-1.svg";
33 import priority2 from "../img/priority-2.svg";
34 import priority4 from "../img/priority-4.svg";
35 import priority5 from "../img/priority-5.svg";
36 import logoOutline from "../img/ntfy-outline.svg";
37 import AttachmentIcon from "./AttachmentIcon";
38 import { useAutoSubscribe } from "./hooks";
39 import { usePrefCache } from "./PrefCache";
40
41 const priorityFiles = {
42 1: priority1,
43 2: priority2,
44 4: priority4,
45 5: priority5,
46 };
47
48 export const AllSubscriptions = () => {
49 // allNotifications is preloaded in Layout, so this view has its data on mount (no empty frame on switch).
50 const { subscriptions, allNotifications } = useOutletContext();
51 if (!subscriptions || allNotifications === null || allNotifications === undefined) {
52 return <DeferredLoading />;
53 }
54 return <AllSubscriptionsList subscriptions={subscriptions} notifications={allNotifications} />;
55 };
56
57 export const SingleSubscription = () => {
58 const { subscriptions, selected, allNotifications } = useOutletContext();
59 useAutoSubscribe(subscriptions, selected);
60 if (!selected || allNotifications === null || allNotifications === undefined) {
61 return <DeferredLoading />;
62 }
63 return <SingleSubscriptionList subscription={selected} allNotifications={allNotifications} />;
64 };
65
66 const AllSubscriptionsList = (props) => {
67 const { subscriptions, notifications } = props;
68 if (subscriptions.length === 0) {
69 return <NoSubscriptions />;
70 }
71 if (notifications.length === 0) {
72 return <NoNotificationsWithoutSubscription subscriptions={subscriptions} />;
73 }
74 return <NotificationList key="all" notifications={notifications} messageBar={false} />;
75 };
76
77 const SingleSubscriptionList = (props) => {
78 const { subscription, allNotifications } = props;
79 // Filter the preloaded allNotifications instead of a per-topic query (getNotifications(id) ==
80 // getAllNotifications() filtered by id), so topic switches are instant.
81 const notifications = useMemo(
82 () => allNotifications.filter((notification) => notification.subscriptionId === subscription.id),
83 [allNotifications, subscription.id],
84 );
85 if (notifications.length === 0) {
86 return <NoNotifications subscription={subscription} />;
87 }
88 return <NotificationList id={subscription.id} notifications={notifications} messageBar />;
89 };
90
91 const NotificationList = (props) => {
92 const { t } = useTranslation();
93 const pageSize = 20;
94 const { notifications } = props;
95 const [snackOpen, setSnackOpen] = useState(false);
96 const [maxCount, setMaxCount] = useState(pageSize);
97 const count = Math.min(notifications.length, maxCount);
98
99 useEffect(
100 () => () => {
101 setMaxCount(pageSize);
102 const main = document.getElementById("main");
103 if (main) {
104 main.scrollTo(0, 0);
105 }
106 },
107 [props.id],
108 );
109
110 return (
111 <InfiniteScroll
112 dataLength={count}
113 next={() => setMaxCount((prev) => prev + pageSize)}
114 hasMore={count < notifications.length}
115 loader={<>Loading ...</>}
116 scrollThreshold={0.7}
117 scrollableTarget="main"
118 >
119 <Container
120 maxWidth="md"
121 role="list"
122 aria-label={t("notifications_list")}
123 sx={{
124 marginTop: 3,
125 marginBottom: props.messageBar ? "100px" : 3, // Hack to avoid hiding notifications behind the message bar
126 }}
127 >
128 <Stack spacing={3}>
129 {notifications.slice(0, count).map((notification) => (
130 <NotificationItem key={notification.id} notification={notification} onShowSnack={() => setSnackOpen(true)} />
131 ))}
132 <Snackbar
133 open={snackOpen}
134 autoHideDuration={3000}
135 onClose={() => setSnackOpen(false)}
136 message={t("notifications_copied_to_clipboard")}
137 />
138 </Stack>
139 </Container>
140 </InfiniteScroll>
141 );
142 };
143
144 /**
145 * Replace links with <Link/> components; this is a combination of the genius function
146 * in [1] and the regex in [2].
147 *
148 * [1] https://github.com/facebook/react/issues/3386#issuecomment-78605760
149 * [2] https://github.com/bryanwoods/autolink-js/blob/master/autolink.js#L9
150 */
151 const autolink = (s) => {
152 const parts = s.split(/(\bhttps?:\/\/[-A-Z0-9+\u0026\u2019@#/%?=()~_|!:,.;]*[-A-Z0-9+\u0026@#/%=~()_|]\b)/gi);
153 for (let i = 1; i < parts.length; i += 2) {
154 parts[i] = (
155 <Link key={i} href={parts[i]} underline="hover" target="_blank" rel="noreferrer">
156 {shortUrl(parts[i])}
157 </Link>
158 );
159 }
160 return <>{parts}</>;
161 };
162
163 // Loaded lazily so the heavy react-remark/unified markdown stack is only fetched when a
164 // text/markdown notification is actually rendered (see MarkdownContent.jsx).
165 const MarkdownContent = lazy(() => import("./MarkdownContent"));
166
167 const NotificationBody = ({ notification }) => {
168 const displayAsMarkdown = notification.content_type === "text/markdown";
169 const formatted = formatMessage(notification);
170 if (displayAsMarkdown) {
171 return (
172 <Suspense fallback={null}>
173 <MarkdownContent content={formatted} />
174 </Suspense>
175 );
176 }
177 return autolink(formatted);
178 };
179
180 const NotificationItem = (props) => {
181 const { t } = useTranslation();
182 const { dateFormat, timeFormat } = usePrefCache();
183 const { notification } = props;
184 const { attachment } = notification;
185 const date = formatDateTime(notification.time, dateFormat, timeFormat);
186 const otherTags = unmatchedTags(notification.tags);
187 const tags = otherTags.length > 0 ? otherTags.join(", ") : null;
188 const handleDelete = async () => {
189 console.log(`[Notifications] Deleting notification ${notification.id}`);
190 await subscriptionManager.deleteNotification(notification.id);
191 };
192 const handleMarkRead = async () => {
193 console.log(`[Notifications] Marking notification ${notification.id} as read`);
194 await subscriptionManager.markNotificationRead(notification.id);
195 };
196 const handleCopy = (s) => {
197 copyToClipboard(s);
198 props.onShowSnack();
199 };
200 const expired = attachment && attachment.expires && attachment.expires < Date.now() / 1000;
201 const hasAttachmentActions = attachment && !expired;
202 const hasClickAction = notification.click;
203 const hasUserActions = notification.actions && notification.actions.length > 0;
204 const showActions = hasAttachmentActions || hasClickAction || hasUserActions;
205
206 return (
207 <Card sx={{ padding: 1 }} role="listitem" aria-label={t("notifications_list_item")}>
208 <CardContent>
209 <Tooltip title={t("notifications_delete")} enterDelay={500}>
210 <IconButton onClick={handleDelete} sx={{ float: "right", marginRight: -1, marginTop: -1 }} aria-label={t("notifications_delete")}>
211 <CloseIcon />
212 </IconButton>
213 </Tooltip>
214 {notification.new === 1 && (
215 <Tooltip title={t("notifications_mark_read")} enterDelay={500}>
216 <IconButton
217 onClick={handleMarkRead}
218 sx={{ float: "right", marginRight: -0.5, marginTop: -1 }}
219 aria-label={t("notifications_mark_read")}
220 >
221 <CheckIcon />
222 </IconButton>
223 </Tooltip>
224 )}
225 <Typography sx={{ fontSize: 14 }} color="text.secondary">
226 {date}
227 {[1, 2, 4, 5].includes(notification.priority) && (
228 <img
229 src={priorityFiles[notification.priority]}
230 alt={t("notifications_priority_x", {
231 priority: notification.priority,
232 })}
233 style={{ verticalAlign: "bottom" }}
234 />
235 )}
236 {notification.new === 1 && (
237 <svg
238 style={{ width: "8px", height: "8px", marginLeft: "4px" }}
239 viewBox="0 0 100 100"
240 xmlns="http://www.w3.org/2000/svg"
241 aria-label={t("notifications_new_indicator")}
242 >
243 <circle cx="50" cy="50" r="50" fill="#338574" />
244 </svg>
245 )}
246 </Typography>
247 {notification.title && (
248 <Typography variant="h5" component="div" role="rowheader">
249 {formatTitle(notification)}
250 </Typography>
251 )}
252 <Typography variant="body1" sx={{ whiteSpace: "pre-line", overflowX: "auto" }}>
253 <NotificationBody notification={notification} />
254 {maybeActionErrors(notification)}
255 </Typography>
256 {attachment && <Attachment attachment={attachment} />}
257 {tags && (
258 <Typography sx={{ fontSize: 14 }} color="text.secondary">
259 {t("notifications_tags")}: {tags}
260 </Typography>
261 )}
262 </CardContent>
263 {showActions && (
264 <CardActions sx={{ paddingTop: 0 }}>
265 {hasAttachmentActions && (
266 <>
267 <Tooltip title={t("notifications_attachment_copy_url_title")}>
268 <Button onClick={() => handleCopy(attachment.url)}>{t("notifications_attachment_copy_url_button")}</Button>
269 </Tooltip>
270 <Tooltip
271 title={t("notifications_attachment_open_title", {
272 url: attachment.url,
273 })}
274 >
275 <Button onClick={() => openUrl(attachment.url)}>{t("notifications_attachment_open_button")}</Button>
276 </Tooltip>
277 </>
278 )}
279 {hasClickAction && (
280 <>
281 <Tooltip title={t("notifications_click_copy_url_title")}>
282 <Button onClick={() => handleCopy(notification.click)}>{t("notifications_click_copy_url_button")}</Button>
283 </Tooltip>
284 <Tooltip
285 title={t("notifications_actions_open_url_title", {
286 url: notification.click,
287 })}
288 >
289 <Button onClick={() => openUrl(notification.click)}>{t("notifications_click_open_button")}</Button>
290 </Tooltip>
291 </>
292 )}
293 {hasUserActions && <UserActions notification={notification} onShowSnack={props.onShowSnack} />}
294 </CardActions>
295 )}
296 </Card>
297 );
298 };
299
300 const Attachment = (props) => {
301 const { t } = useTranslation();
302 const { dateFormat, timeFormat } = usePrefCache();
303 const { attachment } = props;
304 const expired = attachment.expires && attachment.expires < Date.now() / 1000;
305 const expires = attachment.expires && attachment.expires > Date.now() / 1000;
306 const displayableImage = !expired && isImage(attachment);
307
308 // Unexpired image
309 if (displayableImage) {
310 return <Image attachment={attachment} />;
311 }
312
313 // Anything else: Show box
314 const infos = [];
315 if (attachment.size) {
316 infos.push(formatBytes(attachment.size));
317 }
318 if (expires) {
319 infos.push(
320 t("notifications_attachment_link_expires", {
321 date: formatDateTime(attachment.expires, dateFormat, timeFormat),
322 }),
323 );
324 }
325 if (expired) {
326 infos.push(t("notifications_attachment_link_expired"));
327 }
328 const maybeInfoText =
329 infos.length > 0 ? (
330 <>
331 <br />
332 {infos.join(", ")}
333 </>
334 ) : null;
335
336 // If expired, just show infos without click target
337 if (expired) {
338 return (
339 <Box
340 sx={{
341 display: "flex",
342 alignItems: "center",
343 marginTop: 2,
344 padding: 1,
345 borderRadius: "4px",
346 }}
347 >
348 <AttachmentIcon type={attachment.type} />
349 <Typography variant="body2" sx={{ marginLeft: 1, textAlign: "left", color: "text.primary" }}>
350 <b>{attachment.name}</b>
351 {maybeInfoText}
352 </Typography>
353 </Box>
354 );
355 }
356
357 // Not expired
358 return (
359 <ButtonBase
360 sx={{
361 marginTop: 2,
362 }}
363 >
364 <Link
365 href={attachment.url}
366 target="_blank"
367 rel="noopener"
368 underline="none"
369 sx={{
370 display: "flex",
371 alignItems: "center",
372 padding: 1,
373 borderRadius: "4px",
374 "&:hover": {
375 backgroundColor: "rgba(0, 0, 0, 0.05)",
376 },
377 }}
378 >
379 <AttachmentIcon type={attachment.type} />
380 <Typography variant="body2" sx={{ marginLeft: 1, textAlign: "left", color: "text.primary" }}>
381 <b>{attachment.name}</b>
382 {maybeInfoText}
383 </Typography>
384 </Link>
385 </ButtonBase>
386 );
387 };
388
389 const Image = (props) => {
390 const { t } = useTranslation();
391 const [open, setOpen] = useState(false);
392 return (
393 <>
394 <Box
395 component="img"
396 src={props.attachment.url}
397 loading="lazy"
398 alt={t("notifications_attachment_image")}
399 onClick={() => setOpen(true)}
400 sx={{
401 marginTop: 2,
402 borderRadius: "4px",
403 boxShadow: 2,
404 width: 1,
405 maxHeight: "400px",
406 objectFit: "cover",
407 cursor: "pointer",
408 }}
409 />
410 <Modal open={open} onClose={() => setOpen(false)} slots={{ backdrop: LightboxBackdrop }}>
411 <Fade in={open}>
412 <Box
413 component="img"
414 src={props.attachment.url}
415 alt={t("notifications_attachment_image")}
416 loading="lazy"
417 sx={{
418 maxWidth: 1,
419 maxHeight: 1,
420 position: "absolute",
421 top: "50%",
422 left: "50%",
423 transform: "translate(-50%, -50%)",
424 padding: 4,
425 }}
426 />
427 </Fade>
428 </Modal>
429 </>
430 );
431 };
432
433 const UserActions = (props) => (
434 <>
435 {props.notification.actions.map((action) => (
436 <UserAction key={action.id} notification={props.notification} action={action} onShowSnack={props.onShowSnack} />
437 ))}
438 </>
439 );
440
441 const ACTION_PROGRESS_ONGOING = 1;
442 const ACTION_PROGRESS_SUCCESS = 2;
443 const ACTION_PROGRESS_FAILED = 3;
444
445 const ACTION_LABEL_SUFFIX = {
446 [ACTION_PROGRESS_ONGOING]: " …",
447 [ACTION_PROGRESS_SUCCESS]: " ✔",
448 [ACTION_PROGRESS_FAILED]: " ❌",
449 };
450
451 const updateActionStatus = (notification, action, progress, error) => {
452 subscriptionManager.updateNotification({
453 ...notification,
454 actions: notification.actions.map((a) => (a.id === action.id ? { ...a, progress, error } : a)),
455 });
456 };
457
458 const clearNotification = async (notification) => {
459 console.log(`[Notifications] Clearing notification ${notification.id}`);
460 const subscription = await subscriptionManager.get(notification.subscriptionId);
461 if (subscription) {
462 await notifier.cancel(subscription, notification);
463 }
464 await subscriptionManager.markNotificationRead(notification.id);
465 };
466
467 const performHttpAction = async (notification, action) => {
468 console.log(`[Notifications] Performing HTTP user action`, action);
469 try {
470 updateActionStatus(notification, action, ACTION_PROGRESS_ONGOING, null);
471 const response = await fetch(action.url, {
472 method: action.method ?? "POST",
473 headers: action.headers ?? {},
474 // This must not null-coalesce to a non nullish value. Otherwise, the fetch API
475 // will reject it for "having a body"
476 body: action.body,
477 });
478 console.log(`[Notifications] HTTP user action response`, response);
479 const success = response.status >= 200 && response.status <= 299;
480 if (success) {
481 updateActionStatus(notification, action, ACTION_PROGRESS_SUCCESS, null);
482 if (action.clear) {
483 await clearNotification(notification);
484 }
485 } else {
486 updateActionStatus(notification, action, ACTION_PROGRESS_FAILED, `${action.label}: Unexpected response HTTP ${response.status}`);
487 }
488 } catch (e) {
489 console.log(`[Notifications] HTTP action failed`, e);
490 updateActionStatus(notification, action, ACTION_PROGRESS_FAILED, `${action.label}: ${e} Check developer console for details.`);
491 }
492 };
493
494 const UserAction = (props) => {
495 const { t } = useTranslation();
496 const { notification } = props;
497 const { action } = props;
498 if (action.action === ACTION_BROADCAST) {
499 return (
500 <Tooltip title={t("notifications_actions_not_supported")}>
501 <span>
502 <Button disabled aria-label={t("notifications_actions_not_supported")}>
503 {action.label}
504 </Button>
505 </span>
506 </Tooltip>
507 );
508 }
509 if (action.action === ACTION_VIEW) {
510 const handleClick = () => {
511 openUrl(action.url);
512 if (action.clear) {
513 clearNotification(notification);
514 }
515 };
516 return (
517 <Tooltip title={t("notifications_actions_open_url_title", { url: action.url })}>
518 <Button
519 onClick={handleClick}
520 aria-label={t("notifications_actions_open_url_title", {
521 url: action.url,
522 })}
523 >
524 {action.label}
525 </Button>
526 </Tooltip>
527 );
528 }
529 if (action.action === ACTION_HTTP) {
530 const method = action.method ?? "POST";
531 const label = action.label + (ACTION_LABEL_SUFFIX[action.progress ?? 0] ?? "");
532 return (
533 <Tooltip
534 title={t("notifications_actions_http_request_title", {
535 method,
536 url: action.url,
537 })}
538 >
539 <Button
540 onClick={() => performHttpAction(notification, action)}
541 aria-label={t("notifications_actions_http_request_title", {
542 method,
543 url: action.url,
544 })}
545 >
546 {label}
547 </Button>
548 </Tooltip>
549 );
550 }
551 if (action.action === ACTION_COPY) {
552 const handleClick = async () => {
553 await copyToClipboard(action.value);
554 props.onShowSnack();
555 if (action.clear) {
556 await clearNotification(notification);
557 }
558 };
559 return (
560 <Tooltip title={t("common_copy_to_clipboard")}>
561 <Button onClick={handleClick} aria-label={t("common_copy_to_clipboard")}>
562 {action.label}
563 </Button>
564 </Tooltip>
565 );
566 }
567 return null; // Others
568 };
569
570 const NoNotifications = (props) => {
571 const { t } = useTranslation();
572 const topicUrlResolved = topicUrl(props.subscription.baseUrl, props.subscription.topic);
573 return (
574 <VerticallyCenteredContainer maxWidth="xs">
575 <Typography variant="h5" align="center" sx={{ paddingBottom: 1 }}>
576 <img src={logoOutline} height="64" width="64" alt={t("action_bar_logo_alt")} />
577 <br />
578 {t("notifications_none_for_topic_title")}
579 </Typography>
580 <Paragraph>{t("notifications_none_for_topic_description")}</Paragraph>
581 <Paragraph>
582 {t("notifications_example")}:<br />
583 <tt>
584 {'$ curl -d "Hi" '}
585 {topicUrlResolved}
586 </tt>
587 </Paragraph>
588 <Paragraph>
589 <ForMoreDetails />
590 </Paragraph>
591 </VerticallyCenteredContainer>
592 );
593 };
594
595 const NoNotificationsWithoutSubscription = (props) => {
596 const { t } = useTranslation();
597 const subscription = props.subscriptions[0];
598 const topicUrlResolved = topicUrl(subscription.baseUrl, subscription.topic);
599 return (
600 <VerticallyCenteredContainer maxWidth="xs">
601 <Typography variant="h5" align="center" sx={{ paddingBottom: 1 }}>
602 <img src={logoOutline} height="64" width="64" alt={t("action_bar_logo_alt")} />
603 <br />
604 {t("notifications_none_for_any_title")}
605 </Typography>
606 <Paragraph>{t("notifications_none_for_any_description")}</Paragraph>
607 <Paragraph>
608 {t("notifications_example")}:<br />
609 <tt>
610 {'$ curl -d "Hi" '}
611 {topicUrlResolved}
612 </tt>
613 </Paragraph>
614 <Paragraph>
615 <ForMoreDetails />
616 </Paragraph>
617 </VerticallyCenteredContainer>
618 );
619 };
620
621 const NoSubscriptions = () => {
622 const { t } = useTranslation();
623 return (
624 <VerticallyCenteredContainer maxWidth="xs">
625 <Typography variant="h5" align="center" sx={{ paddingBottom: 1 }}>
626 <img src={logoOutline} height="64" width="64" alt={t("action_bar_logo_alt")} />
627 <br />
628 {t("notifications_no_subscriptions_title")}
629 </Typography>
630 <Paragraph>
631 {t("notifications_no_subscriptions_description", {
632 linktext: t("nav_button_subscribe"),
633 })}
634 </Paragraph>
635 <Paragraph>
636 <ForMoreDetails />
637 </Paragraph>
638 </VerticallyCenteredContainer>
639 );
640 };
641
642 const ForMoreDetails = () => (
643 <Trans
644 i18nKey="notifications_more_details"
645 components={{
646 websiteLink: <Link href="https://ntfy.sh" target="_blank" rel="noopener" />,
647 docsLink: <Link href="https://ntfy.sh/docs" target="_blank" rel="noopener" />,
648 }}
649 />
650 );
651
652 const Loading = () => {
653 const { t } = useTranslation();
654 return (
655 <VerticallyCenteredContainer>
656 <Typography variant="h5" color="text.secondary" align="center" sx={{ paddingBottom: 1 }}>
657 <CircularProgress disableShrink sx={{ marginBottom: 1 }} />
658 <br />
659 {t("notifications_loading")}
660 </Typography>
661 </VerticallyCenteredContainer>
662 );
663 };
664
665 // Render nothing until a load takes at least `delayMs`, so the centered spinner only shows on
666 // genuinely slow loads -- normal sub-frame IndexedDB reads don't flash it on every remount.
667 const DeferredLoading = ({ delayMs = 250 }) => {
668 const [show, setShow] = useState(false);
669 useEffect(() => {
670 const timer = setTimeout(() => setShow(true), delayMs);
671 return () => clearTimeout(timer);
672 }, [delayMs]);
673 return show ? <Loading /> : null;
674 };