@umituz/web-dashboard 7.9.0 → 8.0.0

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.
@@ -0,0 +1,108 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+ import { fireEvent, render, screen } from "@testing-library/react";
3
+ import { MemoryRouter } from "react-router";
4
+ import { NotificationItem } from "./NotificationItem";
5
+ import type { NotificationRecord } from "../types";
6
+
7
+ const UNREAD: NotificationRecord = {
8
+ id: "n1",
9
+ type: "order",
10
+ title: "Order shipped",
11
+ body: "Out for delivery",
12
+ read: false,
13
+ at: "2026-10-23T10:00:00Z",
14
+ };
15
+
16
+ const fixedTime = () => "T-10m";
17
+
18
+ describe("NotificationItem", () => {
19
+ it("renders title, body, time and the unread dot", () => {
20
+ render(
21
+ <MemoryRouter>
22
+ <NotificationItem notification={UNREAD} timeFormatter={fixedTime} />
23
+ </MemoryRouter>,
24
+ );
25
+ expect(screen.getByText("Order shipped")).not.toBeNull();
26
+ expect(screen.getByText("Out for delivery")).not.toBeNull();
27
+ expect(screen.getByText("T-10m")).not.toBeNull();
28
+ expect(screen.getByRole("img", { name: "Unread" })).not.toBeNull();
29
+ });
30
+
31
+ it("marks read through the host handler and hides both affordances once read", () => {
32
+ const onMarkRead = vi.fn();
33
+ const { rerender } = render(
34
+ <MemoryRouter>
35
+ <NotificationItem
36
+ notification={UNREAD}
37
+ onMarkRead={onMarkRead}
38
+ timeFormatter={fixedTime}
39
+ />
40
+ </MemoryRouter>,
41
+ );
42
+ fireEvent.click(screen.getByText("Mark read"));
43
+ expect(onMarkRead).toHaveBeenCalledWith("n1");
44
+
45
+ rerender(
46
+ <MemoryRouter>
47
+ <NotificationItem
48
+ notification={{ ...UNREAD, read: true }}
49
+ onMarkRead={onMarkRead}
50
+ timeFormatter={fixedTime}
51
+ />
52
+ </MemoryRouter>,
53
+ );
54
+ expect(screen.queryByRole("img", { name: "Unread" })).toBeNull();
55
+ expect(screen.queryByText("Mark read")).toBeNull();
56
+ });
57
+
58
+ it("omits the mark-read button without a handler", () => {
59
+ render(
60
+ <MemoryRouter>
61
+ <NotificationItem notification={UNREAD} timeFormatter={fixedTime} />
62
+ </MemoryRouter>,
63
+ );
64
+ expect(screen.queryByText("Mark read")).toBeNull();
65
+ });
66
+
67
+ it("dismisses through the host handler", () => {
68
+ const onDismiss = vi.fn();
69
+ render(
70
+ <MemoryRouter>
71
+ <NotificationItem notification={UNREAD} onDismiss={onDismiss} timeFormatter={fixedTime} />
72
+ </MemoryRouter>,
73
+ );
74
+ fireEvent.click(screen.getByLabelText("Dismiss"));
75
+ expect(onDismiss).toHaveBeenCalledWith("n1");
76
+ });
77
+
78
+ it("navigates via the record link and marks read on the way", () => {
79
+ const onMarkRead = vi.fn();
80
+ render(
81
+ <MemoryRouter>
82
+ <NotificationItem
83
+ notification={{ ...UNREAD, link: "/orders" }}
84
+ onMarkRead={onMarkRead}
85
+ timeFormatter={fixedTime}
86
+ />
87
+ </MemoryRouter>,
88
+ );
89
+ const anchor = screen.getByRole("link", { name: /Order shipped/ });
90
+ expect(anchor.getAttribute("href")).toBe("/orders");
91
+ fireEvent.click(anchor);
92
+ expect(onMarkRead).toHaveBeenCalledWith("n1");
93
+ });
94
+
95
+ it("falls back to the typeMeta label when the record has no title", () => {
96
+ render(
97
+ <MemoryRouter>
98
+ <NotificationItem
99
+ notification={{ id: "n2", type: "expiry", body: "Milk expires tomorrow", read: true }}
100
+ typeMeta={{ expiry: { label: "Expiry warning" } }}
101
+ timeFormatter={fixedTime}
102
+ />
103
+ </MemoryRouter>,
104
+ );
105
+ expect(screen.getByText("Expiry warning")).not.toBeNull();
106
+ expect(screen.getByText("Milk expires tomorrow")).not.toBeNull();
107
+ });
108
+ });
@@ -0,0 +1,100 @@
1
+ import { Link } from "react-router";
2
+ import { CircleAlert, CircleCheck, Info, TriangleAlert } from "lucide-react";
3
+ import type { LucideIcon } from "lucide-react";
4
+ import { severityOf, timeAgo, timestampOf } from "../time";
5
+ import type {
6
+ NotificationItemLabels,
7
+ NotificationRecord,
8
+ NotificationSeverity,
9
+ NotificationTypeMeta,
10
+ } from "../types";
11
+
12
+ const SEVERITY_ICON: Record<NotificationSeverity, LucideIcon> = {
13
+ info: Info,
14
+ success: CircleCheck,
15
+ warning: TriangleAlert,
16
+ danger: CircleAlert,
17
+ };
18
+
19
+ const DEFAULT_LABELS: NotificationItemLabels = {
20
+ markReadLabel: "Mark read",
21
+ dismissLabel: "Dismiss",
22
+ viewLabel: "View",
23
+ unreadLabel: "Unread",
24
+ };
25
+
26
+ export interface NotificationItemProps {
27
+ notification: NotificationRecord;
28
+ typeMeta?: NotificationTypeMeta;
29
+ onMarkRead?: (id: string) => void;
30
+ onDismiss?: (id: string) => void;
31
+ /** Overrides the relative-time renderer; defaults to `timeAgo`. */
32
+ timeFormatter?: (iso: string) => string;
33
+ labels?: Partial<NotificationItemLabels>;
34
+ }
35
+
36
+ /** One feed row; navigates when the record carries a link and marks read on the way. */
37
+ export const NotificationItem = ({
38
+ notification,
39
+ typeMeta,
40
+ onMarkRead,
41
+ onDismiss,
42
+ timeFormatter,
43
+ labels,
44
+ }: NotificationItemProps) => {
45
+ const text = { ...DEFAULT_LABELS, ...labels };
46
+ const severity = severityOf(notification);
47
+ const Icon = typeMeta?.[notification.type]?.icon ?? SEVERITY_ICON[severity];
48
+ const stamp = timestampOf(notification);
49
+ const when = stamp ? (timeFormatter ?? timeAgo)(stamp) : "";
50
+ const unread = !notification.read;
51
+ const heading = notification.title ?? typeMeta?.[notification.type]?.label ?? notification.type;
52
+
53
+ const markRead = () => {
54
+ if (unread) onMarkRead?.(notification.id);
55
+ };
56
+
57
+ const content = (
58
+ <>
59
+ <span className={`udb-notif-item__icon udb-notif-item__icon--${severity}`}>
60
+ <Icon size={15} aria-hidden="true" />
61
+ </span>
62
+ <span className="udb-notif-item__body">
63
+ <span className="udb-notif-item__title">{heading}</span>
64
+ {notification.body && <span className="udb-notif-item__text">{notification.body}</span>}
65
+ {when && <span className="udb-notif-item__when">{when}</span>}
66
+ </span>
67
+ <span className="udb-notif-item__side">
68
+ {unread && (
69
+ <span className="udb-notif-item__dot" role="img" aria-label={text.unreadLabel} />
70
+ )}
71
+ {unread && onMarkRead && (
72
+ <button type="button" className="udb-link-button" onClick={markRead}>
73
+ {text.markReadLabel}
74
+ </button>
75
+ )}
76
+ {onDismiss && (
77
+ <button
78
+ type="button"
79
+ className="udb-link-button udb-link-button--muted"
80
+ aria-label={text.dismissLabel}
81
+ onClick={() => onDismiss(notification.id)}
82
+ >
83
+ ✕
84
+ </button>
85
+ )}
86
+ </span>
87
+ </>
88
+ );
89
+
90
+ const className = `udb-notif-item${unread ? " udb-notif-item--unread" : ""}`;
91
+
92
+ if (notification.link) {
93
+ return (
94
+ <Link to={notification.link} className={className} onClick={markRead}>
95
+ {content}
96
+ </Link>
97
+ );
98
+ }
99
+ return <div className={className}>{content}</div>;
100
+ };
@@ -0,0 +1,75 @@
1
+ import { Bell } from "lucide-react";
2
+ import { EmptyState } from "@umituz/web-design-system/organisms";
3
+ import type {
4
+ NotificationItemLabels,
5
+ NotificationListLabels,
6
+ NotificationRecord,
7
+ NotificationTypeMeta,
8
+ } from "../types";
9
+ import { NotificationItem } from "./NotificationItem";
10
+
11
+ const DEFAULT_LABELS: NotificationListLabels = {
12
+ markReadLabel: "Mark read",
13
+ dismissLabel: "Dismiss",
14
+ viewLabel: "View",
15
+ unreadLabel: "Unread",
16
+ emptyTitle: "You're all caught up",
17
+ emptyDescription: "New alerts will land here.",
18
+ };
19
+
20
+ export interface NotificationListProps {
21
+ notifications: readonly NotificationRecord[];
22
+ typeMeta?: NotificationTypeMeta;
23
+ onMarkRead?: (id: string) => void;
24
+ onDismiss?: (id: string) => void;
25
+ timeFormatter?: (iso: string) => string;
26
+ labels?: Partial<NotificationListLabels>;
27
+ }
28
+
29
+ export const NotificationList = ({
30
+ notifications,
31
+ typeMeta,
32
+ onMarkRead,
33
+ onDismiss,
34
+ timeFormatter,
35
+ labels,
36
+ }: NotificationListProps) => {
37
+ const text: NotificationListLabels = { ...DEFAULT_LABELS, ...labels };
38
+ const itemLabels: Partial<NotificationItemLabels> = {
39
+ markReadLabel: text.markReadLabel,
40
+ dismissLabel: text.dismissLabel,
41
+ viewLabel: text.viewLabel,
42
+ unreadLabel: text.unreadLabel,
43
+ };
44
+
45
+ if (notifications.length === 0) {
46
+ return (
47
+ <div className="udb-notif-list__empty">
48
+ <EmptyState
49
+ icon={<Bell size={20} aria-hidden="true" />}
50
+ title={text.emptyTitle}
51
+ description={text.emptyDescription}
52
+ size="md"
53
+ centered
54
+ />
55
+ </div>
56
+ );
57
+ }
58
+
59
+ return (
60
+ <ul className="udb-notif-list">
61
+ {notifications.map((notification) => (
62
+ <li key={notification.id}>
63
+ <NotificationItem
64
+ notification={notification}
65
+ typeMeta={typeMeta}
66
+ onMarkRead={onMarkRead}
67
+ onDismiss={onDismiss}
68
+ timeFormatter={timeFormatter}
69
+ labels={itemLabels}
70
+ />
71
+ </li>
72
+ ))}
73
+ </ul>
74
+ );
75
+ };
@@ -0,0 +1,100 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+ import { fireEvent, render, screen } from "@testing-library/react";
3
+ import { MemoryRouter } from "react-router";
4
+ import { NotificationsPage } from "./NotificationsPage";
5
+ import { NotificationsProvider } from "../NotificationsContext";
6
+ import type { NotificationRecord } from "../types";
7
+
8
+ const FEED: NotificationRecord[] = [
9
+ { id: "a", type: "order", title: "Order shipped", read: false, at: "2026-10-23T10:00:00Z", severity: "info" },
10
+ { id: "b", type: "stock", title: "Milk low", read: false, at: "2026-10-23T09:00:00Z", severity: "critical" },
11
+ { id: "c", type: "order", title: "Order delivered", read: true, at: "2026-10-22T09:00:00Z", severity: "info" },
12
+ ];
13
+
14
+ const TYPE_META = {
15
+ order: { label: "Orders" },
16
+ stock: { label: "Stock" },
17
+ };
18
+
19
+ const mount = (feed: readonly NotificationRecord[] = FEED, props: Record<string, unknown> = {}) =>
20
+ render(
21
+ <MemoryRouter>
22
+ <NotificationsProvider notifications={feed}>
23
+ <NotificationsPage typeMeta={TYPE_META} timeFormatter={() => "T"} {...props} />
24
+ </NotificationsProvider>
25
+ </MemoryRouter>,
26
+ );
27
+
28
+ describe("NotificationsPage", () => {
29
+ it("renders the header, base segments with counts and every row", () => {
30
+ mount();
31
+ expect(screen.getByText("Notifications")).not.toBeNull();
32
+ expect(screen.getByText("All")).not.toBeNull();
33
+ expect(screen.getByText("Unread (2)")).not.toBeNull();
34
+ expect(screen.getByText("Orders (2)")).not.toBeNull();
35
+ expect(screen.getByText("Stock (1)")).not.toBeNull();
36
+ expect(screen.getByText("Order shipped")).not.toBeNull();
37
+ expect(screen.getByText("Order delivered")).not.toBeNull();
38
+ });
39
+
40
+ it("filters by the unread and type segments", () => {
41
+ mount();
42
+ fireEvent.click(screen.getByText("Unread (2)"));
43
+ expect(screen.queryByText("Order delivered")).toBeNull();
44
+ expect(screen.getByText("Order shipped")).not.toBeNull();
45
+
46
+ fireEvent.click(screen.getByText("Stock (1)"));
47
+ expect(screen.getByText("Milk low")).not.toBeNull();
48
+ expect(screen.queryByText("Order shipped")).toBeNull();
49
+ expect(screen.queryByText("Order delivered")).toBeNull();
50
+ });
51
+
52
+ it("adds an attention segment for warning and danger records", () => {
53
+ mount(FEED, { attentionLabel: "Needs attention" });
54
+ fireEvent.click(screen.getByText("Needs attention"));
55
+ expect(screen.getByText("Milk low")).not.toBeNull();
56
+ expect(screen.queryByText("Order shipped")).toBeNull();
57
+ });
58
+
59
+ it("marks all read from the header and drops the button once caught up", () => {
60
+ const onMarkAllRead = vi.fn();
61
+ render(
62
+ <MemoryRouter>
63
+ <NotificationsProvider notifications={FEED} onMarkAllRead={onMarkAllRead}>
64
+ <NotificationsPage timeFormatter={() => "T"} />
65
+ </NotificationsProvider>
66
+ </MemoryRouter>,
67
+ );
68
+ fireEvent.click(screen.getByText("Mark all read"));
69
+ expect(onMarkAllRead).toHaveBeenCalledTimes(1);
70
+ expect(screen.queryByText("Mark all read")).toBeNull();
71
+ });
72
+
73
+ it("renders the unread empty state on the unread segment", () => {
74
+ mount();
75
+ fireEvent.click(screen.getByText("Unread (2)"));
76
+ fireEvent.click(screen.getByText("Mark all read"));
77
+ expect(screen.getByText("Nothing unread")).not.toBeNull();
78
+ });
79
+
80
+ it("shows skeletons when loaded is false", () => {
81
+ render(
82
+ <MemoryRouter>
83
+ <NotificationsProvider notifications={[]} loaded={false}>
84
+ <NotificationsPage timeFormatter={() => "T"} />
85
+ </NotificationsProvider>
86
+ </MemoryRouter>,
87
+ );
88
+ expect(screen.getByText("All")).not.toBeNull();
89
+ expect(screen.queryByText("You're all caught up")).toBeNull();
90
+ });
91
+
92
+ it("hides type segments with zero matching records", () => {
93
+ mount(
94
+ FEED.filter((n) => n.type === "order"),
95
+ { typeMeta: TYPE_META },
96
+ );
97
+ expect(screen.getByText("Orders (2)")).not.toBeNull();
98
+ expect(screen.queryByText("Stock (1)")).toBeNull();
99
+ });
100
+ });
@@ -0,0 +1,126 @@
1
+ import { useMemo, useState } from "react";
2
+ import { CheckCheck } from "lucide-react";
3
+ import { Button } from "@umituz/web-design-system/atoms";
4
+ import { Segmented } from "@umituz/web-design-system/molecules";
5
+ import type { SegmentedOption } from "@umituz/web-design-system/molecules";
6
+ import { PageHeader } from "../../layouts/components";
7
+ import { useNotifications } from "../NotificationsContext";
8
+ import { severityOf } from "../time";
9
+ import type { NotificationListLabels, NotificationTypeMeta } from "../types";
10
+ import { NotificationList } from "./NotificationList";
11
+
12
+ const ALL = "all";
13
+ const UNREAD = "unread";
14
+ const ATTENTION = "attention";
15
+ const TYPE_PREFIX = "type:";
16
+
17
+ export interface NotificationsPageLabels extends NotificationListLabels {
18
+ title: string;
19
+ description: string;
20
+ allLabel: string;
21
+ unreadLabel: string;
22
+ markAllLabel: string;
23
+ emptyUnreadTitle: string;
24
+ emptyAttentionTitle: string;
25
+ }
26
+
27
+ const DEFAULT_LABELS: NotificationsPageLabels = {
28
+ title: "Notifications",
29
+ description: "Alerts across the workspace.",
30
+ allLabel: "All",
31
+ unreadLabel: "Unread",
32
+ markAllLabel: "Mark all read",
33
+ emptyTitle: "No notifications",
34
+ emptyUnreadTitle: "Nothing unread",
35
+ emptyAttentionTitle: "No critical alerts",
36
+ emptyDescription: "Alerts land here as work happens.",
37
+ markReadLabel: "Mark read",
38
+ dismissLabel: "Dismiss",
39
+ viewLabel: "View",
40
+ };
41
+
42
+ export interface NotificationsPageProps {
43
+ /** Adds one segment per type; types with zero records stay hidden. */
44
+ typeMeta?: NotificationTypeMeta;
45
+ /** When set, adds a segment for warning/danger records (e.g. "Needs attention"). */
46
+ attentionLabel?: string;
47
+ timeFormatter?: (iso: string) => string;
48
+ labels?: Partial<NotificationsPageLabels>;
49
+ }
50
+
51
+ const needsAttention = (severity: string): boolean => severity === "warning" || severity === "danger";
52
+
53
+ /** Full-page feed skeleton: filter segments, mark-all-read, and the shared list. */
54
+ export const NotificationsPage = ({ typeMeta, attentionLabel, timeFormatter, labels }: NotificationsPageProps) => {
55
+ const text = { ...DEFAULT_LABELS, ...labels };
56
+ const { notifications, unreadCount, loaded, markAllAsRead, markRead, dismiss, canDismiss } =
57
+ useNotifications();
58
+ const [filter, setFilter] = useState<string>(ALL);
59
+
60
+ const options = useMemo<SegmentedOption<string>[]>(() => {
61
+ const segments: SegmentedOption<string>[] = [
62
+ { value: ALL, label: text.allLabel },
63
+ { value: UNREAD, label: `${text.unreadLabel} (${unreadCount})` },
64
+ ];
65
+ if (attentionLabel) segments.push({ value: ATTENTION, label: attentionLabel });
66
+ for (const [key, meta] of Object.entries(typeMeta ?? {})) {
67
+ const count = notifications.filter((n) => n.type === key).length;
68
+ if (count > 0 || filter === `${TYPE_PREFIX}${key}`) {
69
+ segments.push({ value: `${TYPE_PREFIX}${key}`, label: `${meta.label} (${count})` });
70
+ }
71
+ }
72
+ return segments;
73
+ }, [typeMeta, attentionLabel, notifications, unreadCount, filter, text.allLabel, text.unreadLabel]);
74
+
75
+ const filtered = useMemo(() => {
76
+ if (filter === UNREAD) return notifications.filter((n) => !n.read);
77
+ if (filter === ATTENTION) return notifications.filter((n) => needsAttention(severityOf(n)));
78
+ if (filter.startsWith(TYPE_PREFIX)) {
79
+ const key = filter.slice(TYPE_PREFIX.length);
80
+ return notifications.filter((n) => n.type === key);
81
+ }
82
+ return notifications;
83
+ }, [notifications, filter]);
84
+
85
+ const emptyTitle =
86
+ filter === UNREAD ? text.emptyUnreadTitle : filter === ATTENTION ? text.emptyAttentionTitle : text.emptyTitle;
87
+
88
+ return (
89
+ <div className="udb-notif-page">
90
+ <PageHeader
91
+ title={text.title}
92
+ description={text.description}
93
+ actions={
94
+ unreadCount > 0 && (
95
+ <Button variant="secondary" size="sm" icon={<CheckCheck size={13} />} onClick={markAllAsRead}>
96
+ {text.markAllLabel}
97
+ </Button>
98
+ )
99
+ }
100
+ />
101
+
102
+ <div className="udb-notif-page__filters">
103
+ <Segmented options={options} value={filter} onChange={setFilter} aria-label={text.title} />
104
+ </div>
105
+
106
+ <div className="udb-notif-page__body">
107
+ {!loaded ? (
108
+ <div className="udb-notif-page__loading">
109
+ {[0, 1, 2, 3].map((row) => (
110
+ <div key={row} className="udb-notif-page__skeleton" />
111
+ ))}
112
+ </div>
113
+ ) : (
114
+ <NotificationList
115
+ notifications={filtered}
116
+ typeMeta={typeMeta}
117
+ onMarkRead={markRead}
118
+ onDismiss={canDismiss ? dismiss : undefined}
119
+ timeFormatter={timeFormatter}
120
+ labels={{ ...text, emptyTitle, emptyDescription: text.emptyDescription }}
121
+ />
122
+ )}
123
+ </div>
124
+ </div>
125
+ );
126
+ };
@@ -0,0 +1,8 @@
1
+ export { NotificationItem } from "./NotificationItem";
2
+ export type { NotificationItemProps } from "./NotificationItem";
3
+ export { NotificationList } from "./NotificationList";
4
+ export type { NotificationListProps } from "./NotificationList";
5
+ export { NotificationCenter } from "./NotificationCenter";
6
+ export type { NotificationCenterLabels, NotificationCenterProps } from "./NotificationCenter";
7
+ export { NotificationsPage } from "./NotificationsPage";
8
+ export type { NotificationsPageLabels, NotificationsPageProps } from "./NotificationsPage";
@@ -0,0 +1,16 @@
1
+ export { NotificationsProvider, useNotifications } from "./NotificationsContext";
2
+ export type {
3
+ NotificationsContextValue,
4
+ NotificationsProviderProps,
5
+ } from "./NotificationsContext";
6
+ export { DEFAULT_TIME_AGO_LABELS, severityOf, timeAgo, timestampOf } from "./time";
7
+ export type { TimeAgoLabels } from "./time";
8
+ export type {
9
+ NotificationItemLabels,
10
+ NotificationListLabels,
11
+ NotificationRecord,
12
+ NotificationSeverity,
13
+ NotificationSeverityInput,
14
+ NotificationTypeMeta,
15
+ NotificationTypeMetaEntry,
16
+ } from "./types";
@@ -0,0 +1,42 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { severityOf, timeAgo, timestampOf } from "./time";
3
+ import type { NotificationRecord } from "./types";
4
+
5
+ const NOW = Date.parse("2026-10-23T12:00:00Z");
6
+ const minutesAgo = (n: number) => new Date(NOW - n * 60_000).toISOString();
7
+
8
+ describe("timeAgo", () => {
9
+ it("buckets elapsed time into the label patterns", () => {
10
+ expect(timeAgo(minutesAgo(0.5), {}, NOW)).toBe("just now");
11
+ expect(timeAgo(minutesAgo(5), {}, NOW)).toBe("5m ago");
12
+ expect(timeAgo(minutesAgo(90), {}, NOW)).toBe("1h ago");
13
+ expect(timeAgo(minutesAgo(3 * 24 * 60), {}, NOW)).toBe("3d ago");
14
+ });
15
+
16
+ it("falls back to the locale date beyond a week", () => {
17
+ const old = "2026-09-01T10:00:00Z";
18
+ expect(timeAgo(old, {}, NOW)).toBe(new Date(old).toLocaleDateString());
19
+ });
20
+
21
+ it("honors label overrides and returns empty for invalid input", () => {
22
+ expect(timeAgo(minutesAgo(5), { minutesPattern: "{n} dk önce" }, NOW)).toBe("5 dk önce");
23
+ expect(timeAgo("not-a-date", {}, NOW)).toBe("");
24
+ });
25
+ });
26
+
27
+ describe("timestampOf", () => {
28
+ it("prefers at over createdAt and accepts either", () => {
29
+ expect(timestampOf({ id: "1", type: "x", at: "a", createdAt: "b" })).toBe("a");
30
+ expect(timestampOf({ id: "2", type: "x", createdAt: "b" })).toBe("b");
31
+ expect(timestampOf({ id: "3", type: "x" })).toBeUndefined();
32
+ });
33
+ });
34
+
35
+ describe("severityOf", () => {
36
+ it("normalizes critical to danger and defaults to info", () => {
37
+ const base = { id: "1", type: "x" } as NotificationRecord;
38
+ expect(severityOf({ ...base, severity: "critical" })).toBe("danger");
39
+ expect(severityOf({ ...base, severity: "warning" })).toBe("warning");
40
+ expect(severityOf(base)).toBe("info");
41
+ });
42
+ });
@@ -0,0 +1,55 @@
1
+ import type { NotificationRecord, NotificationSeverity, NotificationSeverityInput } from "./types";
2
+
3
+ const MINUTE = 60_000;
4
+ const HOUR = 60 * MINUTE;
5
+ const DAY = 24 * HOUR;
6
+
7
+ export interface TimeAgoLabels {
8
+ justNow: string;
9
+ minutesPattern: string;
10
+ hoursPattern: string;
11
+ daysPattern: string;
12
+ }
13
+
14
+ export const DEFAULT_TIME_AGO_LABELS: TimeAgoLabels = {
15
+ justNow: "just now",
16
+ minutesPattern: "{n}m ago",
17
+ hoursPattern: "{n}h ago",
18
+ daysPattern: "{n}d ago",
19
+ };
20
+
21
+ const fill = (pattern: string, value: number): string => pattern.replace("{n}", String(value));
22
+
23
+ /** Relative time for feeds; beyond a week it falls back to the locale date. */
24
+ export function timeAgo(
25
+ iso: string,
26
+ labels: Partial<TimeAgoLabels> = {},
27
+ now?: number,
28
+ ): string {
29
+ const text = { ...DEFAULT_TIME_AGO_LABELS, ...labels };
30
+ const time = new Date(iso).getTime();
31
+ if (Number.isNaN(time)) return "";
32
+ const elapsed = (now ?? Date.now()) - time;
33
+ if (elapsed < MINUTE) return text.justNow;
34
+ if (elapsed < HOUR) return fill(text.minutesPattern, Math.floor(elapsed / MINUTE));
35
+ if (elapsed < DAY) return fill(text.hoursPattern, Math.floor(elapsed / HOUR));
36
+ if (elapsed < 7 * DAY) return fill(text.daysPattern, Math.floor(elapsed / DAY));
37
+ return new Date(time).toLocaleDateString();
38
+ }
39
+
40
+ /** The feed tables stamp whichever column they have; `at` wins over `createdAt`. */
41
+ export function timestampOf(record: NotificationRecord): string | undefined {
42
+ return record.at ?? record.createdAt;
43
+ }
44
+
45
+ const SEVERITY_ALIASES: Record<NotificationSeverityInput, NotificationSeverity> = {
46
+ info: "info",
47
+ success: "success",
48
+ warning: "warning",
49
+ danger: "danger",
50
+ critical: "danger",
51
+ };
52
+
53
+ export function severityOf(record: NotificationRecord): NotificationSeverity {
54
+ return record.severity ? SEVERITY_ALIASES[record.severity] : "info";
55
+ }
@@ -0,0 +1,42 @@
1
+ import type { LucideIcon } from "lucide-react";
2
+
3
+ /** Severity buckets the fleet converges on; hosts writing `critical` get `danger`. */
4
+ export type NotificationSeverity = "info" | "success" | "warning" | "danger";
5
+
6
+ export type NotificationSeverityInput = NotificationSeverity | "critical";
7
+
8
+ export interface NotificationRecord {
9
+ id: string;
10
+ /** Domain-specific kind — drives the page segments and row icons through typeMeta. */
11
+ type: string;
12
+ title?: string;
13
+ body?: string;
14
+ read?: boolean;
15
+ /** Either timestamp column is accepted; `at` wins when both are present. */
16
+ at?: string;
17
+ createdAt?: string;
18
+ severity?: NotificationSeverityInput;
19
+ /** Router path — rows navigate (and mark read) when present. */
20
+ link?: string;
21
+ }
22
+
23
+ export interface NotificationTypeMetaEntry {
24
+ /** Segment label on the page; also the row fallback when a record has no title. */
25
+ label: string;
26
+ icon?: LucideIcon;
27
+ }
28
+
29
+ /** Optional per-type registry; segments hide types with zero matching records. */
30
+ export type NotificationTypeMeta = Record<string, NotificationTypeMetaEntry>;
31
+
32
+ export interface NotificationItemLabels {
33
+ markReadLabel: string;
34
+ dismissLabel: string;
35
+ viewLabel: string;
36
+ unreadLabel: string;
37
+ }
38
+
39
+ export interface NotificationListLabels extends NotificationItemLabels {
40
+ emptyTitle: string;
41
+ emptyDescription: string;
42
+ }