diff --git a/client/scripts/theme-baseline.json b/client/scripts/theme-baseline.json index f6ee62c99..0d6556315 100644 --- a/client/scripts/theme-baseline.json +++ b/client/scripts/theme-baseline.json @@ -72,7 +72,6 @@ "components/Map/poiCategories.ts": 7, "components/Map/ratingBadge.ts": 2, "components/Map/reservationsMapbox.ts": 1, - "components/Notifications/InAppNotificationItem.tsx": 1, "components/PDF/TripPDF.tsx": 53, "components/Packing/PackingListPanelBagModal.tsx": 2, "components/Packing/PackingListPanelCategoryGroup.tsx": 5, @@ -295,7 +294,6 @@ "pages/FilesPage.tsx": 11, "pages/ForgotPasswordPage.tsx": 18, "pages/HelpPage.tsx": 21, - "pages/InAppNotificationsPage.tsx": 2, "pages/JoinTripPage.tsx": 4, "pages/JourneyDetailPage.tsx": 53, "pages/JourneyPage.tsx": 64, diff --git a/client/src/components/Layout/InAppNotificationBell.tsx b/client/src/components/Layout/InAppNotificationBell.tsx index e18935bad..6353594a2 100644 --- a/client/src/components/Layout/InAppNotificationBell.tsx +++ b/client/src/components/Layout/InAppNotificationBell.tsx @@ -5,7 +5,7 @@ import { Bell, Trash2, CheckCheck } from 'lucide-react' import { useTranslation } from '../../i18n' import { useInAppNotificationStore } from '../../store/inAppNotificationStore.ts' import { useAuthStore } from '../../store/authStore' -import InAppNotificationItem from '../Notifications/InAppNotificationItem.tsx' +import NotificationDayList from '../Notifications/NotificationDayList' import ConfirmDialog from '../shared/ConfirmDialog' export default function InAppNotificationBell(): React.ReactElement { @@ -73,9 +73,9 @@ export default function InAppNotificationBell(): React.ReactElement { position: 'fixed', top: 'var(--nav-h)', insetInlineEnd: 8, - width: 380, + width: 400, maxWidth: 'calc(100vw - 16px)', - maxHeight: 'min(480px, calc(100vh - var(--nav-h) - 16px))', + maxHeight: 'min(560px, calc(100vh - var(--nav-h) - 16px))', zIndex: 9999, display: 'flex', flexDirection: 'column', @@ -119,7 +119,7 @@ export default function InAppNotificationBell(): React.ReactElement { {/* Notification list */} -
+
{isLoading && notifications.length === 0 ? (
@@ -133,9 +133,7 @@ export default function InAppNotificationBell(): React.ReactElement {

{t('notifications.emptyDescription')}

) : ( - notifications.slice(0, 10).map(n => ( - setOpen(false)} /> - )) + setOpen(false)} compact /> )}
diff --git a/client/src/components/Notifications/InAppNotificationItem.tsx b/client/src/components/Notifications/InAppNotificationItem.tsx index 2d3ad386e..1679e8219 100644 --- a/client/src/components/Notifications/InAppNotificationItem.tsx +++ b/client/src/components/Notifications/InAppNotificationItem.tsx @@ -1,29 +1,53 @@ import React from 'react' -import { User, Check, X, ArrowRight, Trash2, CheckCheck, Mail } from 'lucide-react' +import { Check, X, ArrowRight, Trash2, CheckCheck, Mail } from 'lucide-react' import { useTranslation } from '../../i18n' import type { InAppNotification } from '../../store/inAppNotificationStore' import { compactTime, useNotificationItemActions } from './useNotificationItemActions' - -function relativeTime(dateStr: string, locale: string): string { - return compactTime(dateStr, locale === 'ar' ? 'الآن' : 'just now') -} +import { KIND_LOOK, createdAt, kindOf } from './notificationModel' interface NotificationItemProps { notification: InAppNotification onClose?: () => void } -/** The round tool beside a notification, quiet until it is pointed at. */ -const TOOL = 'grid place-items-center w-7 h-7 rounded-lg transition-colors text-content-faint hover:text-content hover:bg-surface-card focus-visible:bg-surface-card focus-visible:text-content' +/** The quiet tool beside a notification, forward only when it is pointed at. */ +const TOOL = 'grid place-items-center w-7 h-7 rounded-lg transition-colors text-content-faint hover:text-content hover:bg-surface-secondary focus-visible:bg-surface-secondary focus-visible:text-content' -/** An answer or a way on, as a pill under the words. */ -const PILL = 'inline-flex items-center gap-1.5 h-7 px-3 rounded-full text-caption font-medium transition-colors' +/** An answer or a way on, as a button under the words. */ +const ACTION = 'inline-flex items-center gap-1.5 h-8 px-3 rounded-lg text-caption font-semibold transition-colors' + +/** Under an hour it reads "5m"; after that the clock time, since the list is headed by its day. */ +function timeOf(value: string, locale: string, justNow: string): string { + const date = createdAt(value) + if (Date.now() - date.getTime() < 3_600_000) return compactTime(date.toISOString(), justNow) + return new Intl.DateTimeFormat(locale, { hour: '2-digit', minute: '2-digit' }).format(date) +} + +/** The tile on the start side: the kind's symbol on its colour, and who sent it as a small face on its corner. */ +function KindTile({ notification }: { notification: InAppNotification }) { + const { icon: Icon, tone } = KIND_LOOK[kindOf(notification.title_key)] + const initial = notification.sender_username?.charAt(0).toUpperCase() + return ( + + + + + {notification.sender_avatar ? ( + + ) : initial ? ( + + {initial} + + ) : null} + + ) +} /** - * One notification, as a card in the list: who sent it, what it says, and what - * can be done with it. Unread ones carry a dot in the accent and a faint - * ground; the tools to mark and delete come forward when the card is pointed - * at or focused, so a list reads as messages rather than as rows of buttons. + * One notification: a tile that says at a glance what it is about and who sent + * it, the message itself, and what can be done with it. Unread ones are set in + * bold with a dot in the accent; marking and deleting come forward when the row + * is pointed at or focused, so a list reads as messages rather than as buttons. */ export default function InAppNotificationItem({ notification, onClose }: NotificationItemProps): React.ReactElement { const { t, locale } = useTranslation() @@ -32,112 +56,96 @@ export default function InAppNotificationItem({ notification, onClose }: Notific const titleText = t(notification.title_key, notification.title_params) const bodyText = t(notification.text_key, notification.text_params) - const hasUnknownTitle = titleText === notification.title_key - const hasUnknownBody = bodyText === notification.text_key const unread = !notification.is_read const answered = notification.response !== null + const { positive_text_key: yesKey, negative_text_key: noKey, navigate_text_key: goKey } = notification + const asks = notification.type === 'boolean' && yesKey && noKey + const leads = notification.type === 'navigate' && goKey && notification.navigate_target return ( -
- {unread && } +
+ -
- {/* Sender avatar */} -
- {notification.sender_avatar ? ( - - ) : ( -
- {notification.sender_username - ? notification.sender_username.charAt(0).toUpperCase() - : } -
- )} -
- - {/* Content */} -
-
-

- {hasUnknownTitle ? notification.title_key : titleText} -

-
- - {relativeTime(notification.created_at, locale)} - -
- {notification.is_read ? ( - - ) : ( - - )} - -
+ ) : ( + + )} +
+
-

- {hasUnknownBody ? notification.text_key : bodyText} -

+

{bodyText}

- {/* Boolean actions */} - {notification.type === 'boolean' && notification.positive_text_key && notification.negative_text_key && ( -
- - -
- )} - - {/* Navigate action */} - {notification.type === 'navigate' && notification.navigate_text_key && notification.navigate_target && ( + {asks && ( +
- )} -
+ +
+ )} + + {leads && ( + + )}
) diff --git a/client/src/components/Notifications/NotificationDayList.tsx b/client/src/components/Notifications/NotificationDayList.tsx new file mode 100644 index 000000000..193e4588e --- /dev/null +++ b/client/src/components/Notifications/NotificationDayList.tsx @@ -0,0 +1,56 @@ +import React, { useMemo } from 'react'; +import { useTranslation } from '../../i18n'; +import type { InAppNotification } from '../../store/inAppNotificationStore'; +import InAppNotificationItem from './InAppNotificationItem'; +import { groupByDay } from './notificationModel'; + +interface NotificationDayListProps { + notifications: InAppNotification[]; + /** Closes the bell's panel after a notification led somewhere. */ + onClose?: () => void; + /** The bell's panel: headings stick to its top and the days need no cards of their own. */ + compact?: boolean; +} + +/** + * The notifications cut into days, each under its heading (Today, Yesterday, + * a weekday, then the date). On the page every day is a card of its own; in + * the bell's panel the headings stay at the top while the day scrolls by. + */ +export default function NotificationDayList({ + notifications, + onClose, + compact = false, +}: NotificationDayListProps): React.ReactElement { + const { locale } = useTranslation(); + const groups = useMemo(() => groupByDay(notifications, locale), [notifications, locale]); + + return ( +
+ {groups.map((group) => ( +
+

+ {group.label} +

+
+ {group.items.map((n) => ( + + ))} +
+
+ ))} +
+ ); +} diff --git a/client/src/components/Notifications/notificationModel.test.tsx b/client/src/components/Notifications/notificationModel.test.tsx new file mode 100644 index 000000000..5353cc69d --- /dev/null +++ b/client/src/components/Notifications/notificationModel.test.tsx @@ -0,0 +1,91 @@ +/** + * FE-NOTIF-MODEL-001 to FE-NOTIF-MODEL-007 + * + * What a notification's tile shows, how the server's time is read, and how the + * list is cut into days under headings in the reader's language. + */ +import { describe, expect, it } from 'vitest'; + +import { render, screen } from '../../../tests/helpers/render'; +import type { InAppNotification } from '../../store/inAppNotificationStore'; +import NotificationDayList from './NotificationDayList'; +import { KIND_LOOK, createdAt, dayLabel, groupByDay, kindOf } from './notificationModel'; + +const note = (id: number, created_at: string, title_key = 'notif.trip_invite.title'): InAppNotification => ({ + id, + type: 'simple', + scope: 'trip', + target: 1, + sender_id: null, + sender_username: null, + sender_avatar: null, + recipient_id: 1, + title_key, + title_params: {}, + text_key: 'notifications.empty', + text_params: {}, + positive_text_key: null, + negative_text_key: null, + response: null, + navigate_text_key: null, + navigate_target: null, + is_read: false, + created_at, +}); + +const NOW = new Date(2026, 9, 24, 15, 0); +const at = (days: number, hour = 10) => new Date(2026, 9, 24 - days, hour, 0); + +describe('notificationModel', () => { + it('FE-NOTIF-MODEL-001: every known title has its kind, anything else is the plain bell', () => { + expect(kindOf('notif.collab_message.title')).toBe('message'); + expect(kindOf('notif.replica_failure.title')).toBe('alert'); + expect(kindOf('plugin.something.title')).toBe('other'); + for (const look of Object.values(KIND_LOOK)) expect(look.tone).toMatch(/^bg-/); + }); + + it("FE-NOTIF-MODEL-002: the server's UTC text is read as UTC, an ISO string as it is", () => { + expect(createdAt('2026-10-24 08:30:00').toISOString()).toBe('2026-10-24T08:30:00.000Z'); + expect(createdAt('2026-10-24T08:30:00.000Z').toISOString()).toBe('2026-10-24T08:30:00.000Z'); + }); + + it('FE-NOTIF-MODEL-003: today and yesterday by name, the week by weekday, older by date', () => { + expect(dayLabel(at(0), 'en', NOW)).toBe('Today'); + expect(dayLabel(at(1), 'en', NOW)).toBe('Yesterday'); + expect(dayLabel(at(3), 'en', NOW)).toBe('Wednesday'); + expect(dayLabel(at(20), 'en', NOW)).toBe('October 4'); + expect(dayLabel(new Date(2025, 11, 31), 'en', NOW)).toBe('December 31, 2025'); + }); + + it('FE-NOTIF-MODEL-004: the headings follow the language', () => { + expect(dayLabel(at(0), 'de', NOW)).toBe('Heute'); + expect(dayLabel(at(1), 'de', NOW)).toBe('Gestern'); + }); + + it('FE-NOTIF-MODEL-005: the list is cut into days in the order it came', () => { + const groups = groupByDay( + [note(1, at(0, 12).toISOString()), note(2, at(0, 9).toISOString()), note(3, at(2).toISOString())], + 'en', + NOW + ); + expect(groups.map((g) => [g.label, g.items.map((n) => n.id)])).toEqual([ + ['Today', [1, 2]], + ['Thursday', [3]], + ]); + }); + + it('FE-NOTIF-MODEL-006: an empty list has no days', () => { + expect(groupByDay([], 'en', NOW)).toEqual([]); + }); +}); + +describe('NotificationDayList', () => { + it('FE-NOTIF-MODEL-007: each day is a section under its heading', () => { + const now = new Date(); + const yesterday = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1, 12); + render(); + expect(screen.getByRole('heading', { name: 'Today' })).toBeInTheDocument(); + expect(screen.getByRole('heading', { name: 'Yesterday' })).toBeInTheDocument(); + expect(screen.getAllByRole('region')).toHaveLength(2); + }); +}); diff --git a/client/src/components/Notifications/notificationModel.ts b/client/src/components/Notifications/notificationModel.ts new file mode 100644 index 000000000..c4b20f00b --- /dev/null +++ b/client/src/components/Notifications/notificationModel.ts @@ -0,0 +1,119 @@ +import type { LucideIcon } from 'lucide-react'; +import { + Backpack, + Bell, + BookmarkPlus, + CalendarDays, + Images, + ListChecks, + MessageCircle, + Mountain, + Plane, + Sparkles, + Ticket, + TriangleAlert, +} from 'lucide-react'; + +import type { InAppNotification } from '../../store/inAppNotificationStore'; + +/** What a notification is about, read from its title key: it picks the symbol and colour of its tile. */ +export type NotificationKind = + | 'trip' + | 'message' + | 'booking' + | 'packing' + | 'todo' + | 'vacay' + | 'collection' + | 'photos' + | 'tour' + | 'update' + | 'alert' + | 'other'; + +const KIND_BY_TITLE: Record = { + 'notif.trip_invite.title': 'trip', + 'notif.trip_reminder.title': 'trip', + 'notif.collab_message.title': 'message', + 'notif.booking_change.title': 'booking', + 'notif.packing_tagged.title': 'packing', + 'notif.todo_due.title': 'todo', + 'notif.vacay_invite.title': 'vacay', + 'notif.vacay_share.title': 'vacay', + 'notif.collection_invite.title': 'collection', + 'notif.photos_shared.title': 'photos', + 'notif.wanderer_source_hint.title': 'tour', + 'notif.paddle_region_requested.title': 'tour', + 'notif.version_available.title': 'update', + 'notifications.versionAvailable.title': 'update', + 'notif.replica_failure.title': 'alert', + 'notifications.synologySessionCleared.title': 'alert', +}; + +export function kindOf(titleKey: string): NotificationKind { + return KIND_BY_TITLE[titleKey] ?? 'other'; +} + +/** The symbol of each kind and the tinted tile it sits on. */ +export const KIND_LOOK: Record = { + trip: { icon: Plane, tone: 'bg-info-soft text-info' }, + message: { icon: MessageCircle, tone: 'bg-success-soft text-success' }, + booking: { icon: Ticket, tone: 'bg-warning-soft text-warning' }, + packing: { icon: Backpack, tone: 'bg-warning-soft text-warning' }, + todo: { icon: ListChecks, tone: 'bg-success-soft text-success' }, + vacay: { icon: CalendarDays, tone: 'bg-info-soft text-info' }, + collection: { icon: BookmarkPlus, tone: 'bg-accent-subtle text-accent' }, + photos: { icon: Images, tone: 'bg-warning-soft text-warning' }, + tour: { icon: Mountain, tone: 'bg-success-soft text-success' }, + update: { icon: Sparkles, tone: 'bg-accent-subtle text-accent' }, + alert: { icon: TriangleAlert, tone: 'bg-danger-soft text-danger' }, + other: { icon: Bell, tone: 'bg-surface-secondary text-content-secondary' }, +}; + +/** + * When a notification was made. The server writes `YYYY-MM-DD HH:MM:SS` in UTC, + * which a bare `new Date()` would read as local time. + */ +export function createdAt(value: string): Date { + return new Date(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}/.test(value) ? `${value.replace(' ', 'T')}Z` : value); +} + +const dayStart = (d: Date) => new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime(); + +/** + * The heading of the day a notification belongs to, in the reader's language: + * today and yesterday by name, the rest of the week by weekday, anything older + * by its date (with the year when it is not this one). + */ +export function dayLabel(date: Date, locale: string, now: Date = new Date()): string { + const days = Math.round((dayStart(now) - dayStart(date)) / 86_400_000); + if (days <= 1) { + const word = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' }).format(-Math.max(days, 0), 'day'); + return word.charAt(0).toLocaleUpperCase(locale) + word.slice(1); + } + if (days < 7) return new Intl.DateTimeFormat(locale, { weekday: 'long' }).format(date); + return new Intl.DateTimeFormat(locale, { + day: 'numeric', + month: 'long', + ...(date.getFullYear() === now.getFullYear() ? {} : { year: 'numeric' }), + }).format(date); +} + +export interface NotificationGroup { + key: string; + label: string; + items: InAppNotification[]; +} + +/** The list cut into days, in the order it came (newest first). */ +export function groupByDay(list: InAppNotification[], locale: string, now: Date = new Date()): NotificationGroup[] { + const groups: NotificationGroup[] = []; + for (const n of list) { + const date = createdAt(n.created_at); + const key = String(dayStart(date)); + const current = groups[groups.length - 1]; + if (current?.key === key) current.items.push(n); + else groups.push({ key, label: dayLabel(date, locale, now), items: [n] }); + } + return groups; +} diff --git a/client/src/pages/InAppNotificationsPage.tsx b/client/src/pages/InAppNotificationsPage.tsx index 962680330..0efa68a6d 100644 --- a/client/src/pages/InAppNotificationsPage.tsx +++ b/client/src/pages/InAppNotificationsPage.tsx @@ -6,7 +6,7 @@ import HelpAnchor from '../components/Help/HelpAnchor' import EmptyState from '../components/shared/EmptyState' import ConfirmDialog from '../components/shared/ConfirmDialog' import { Spinner } from '../components/shared/Spinner' -import InAppNotificationItem from '../components/Notifications/InAppNotificationItem.tsx' +import NotificationDayList from '../components/Notifications/NotificationDayList' import { useInAppNotifications } from './inAppNotifications/useInAppNotifications' export default function InAppNotificationsPage(): React.ReactElement { @@ -88,27 +88,25 @@ function InAppNotificationsPageDesktop(): React.ReactElement {
- {/* Notification list */} -
- {isLoading && displayed.length === 0 ? ( -
- -
- ) : displayed.length === 0 ? ( + {/* The list, one card per day. */} + {isLoading && displayed.length === 0 ? ( +
+ +
+ ) : displayed.length === 0 ? ( +
- ) : ( - displayed.map(n => ( - - )) - )} +
+ ) : ( + + )} - {/* Infinite scroll trigger */} - {hasMore && ( -
- {isLoading && } -
- )} -
+ {/* Infinite scroll trigger */} + {hasMore && ( +
+ {isLoading && } +
+ )}