@marktiderman/genesis-ui-native 2.2.0 → 2.3.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.
Files changed (77) hide show
  1. package/README.md +82 -0
  2. package/dist/chunk-7PCWEY6R.js +27 -0
  3. package/dist/chunk-7PCWEY6R.js.map +1 -0
  4. package/dist/chunk-D5RKSPMH.js +24 -0
  5. package/dist/chunk-D5RKSPMH.js.map +1 -0
  6. package/dist/{chunk-5HRGIA6F.js → chunk-EFXCJ5AN.js} +76 -3
  7. package/dist/chunk-EFXCJ5AN.js.map +1 -0
  8. package/dist/{chunk-ULS7I6ZS.js → chunk-ERHGCWTY.js} +81 -12
  9. package/dist/chunk-ERHGCWTY.js.map +1 -0
  10. package/dist/{chunk-2WCXMJL6.js → chunk-FIITITXO.js} +67 -108
  11. package/dist/chunk-FIITITXO.js.map +1 -0
  12. package/dist/chunk-FZY2IXOX.js +1559 -0
  13. package/dist/chunk-FZY2IXOX.js.map +1 -0
  14. package/dist/{chunk-TXJT55JC.js → chunk-W7BK3ARU.js} +715 -293
  15. package/dist/chunk-W7BK3ARU.js.map +1 -0
  16. package/dist/components/index.d.ts +142 -17
  17. package/dist/components/index.js +6 -4
  18. package/dist/data/index.d.ts +7 -1
  19. package/dist/data/index.js +31 -6
  20. package/dist/data/index.js.map +1 -1
  21. package/dist/hooks/index.js +2 -1
  22. package/dist/icons/lucide.d.ts +7 -0
  23. package/dist/icons/lucide.js +47 -0
  24. package/dist/icons/lucide.js.map +1 -0
  25. package/dist/index.d.ts +3 -2
  26. package/dist/index.js +7 -6
  27. package/dist/layouts/index.d.ts +320 -4
  28. package/dist/layouts/index.js +3 -3
  29. package/dist/native-modules-BSVaEb3D.d.ts +206 -0
  30. package/package.json +34 -5
  31. package/src/__tests__/fake-modules.tsx +134 -0
  32. package/src/__tests__/native-modules-lists.test.tsx +70 -0
  33. package/src/__tests__/native-modules.test.tsx +631 -0
  34. package/src/components/__tests__/sheet.test.tsx +193 -0
  35. package/src/components/__tests__/toast.test.tsx +15 -0
  36. package/src/components/avatar.tsx +69 -16
  37. package/src/components/date-time-picker.tsx +128 -10
  38. package/src/components/drawer.tsx +158 -68
  39. package/src/components/dropdown-menu.tsx +7 -6
  40. package/src/components/glass-surface.tsx +150 -0
  41. package/src/components/icon.tsx +66 -0
  42. package/src/components/image.tsx +89 -0
  43. package/src/components/index.ts +33 -2
  44. package/src/components/list-item.tsx +29 -9
  45. package/src/components/popover.tsx +12 -9
  46. package/src/components/segmented-control.tsx +7 -1
  47. package/src/components/sheet.tsx +276 -133
  48. package/src/components/skeleton.tsx +75 -53
  49. package/src/components/toast.tsx +185 -87
  50. package/src/data/NativeResourcePage.tsx +48 -3
  51. package/src/data/__tests__/resource-page-offline.test.tsx +47 -0
  52. package/src/hooks/use-reduced-motion.ts +24 -10
  53. package/src/icon-names.ts +49 -0
  54. package/src/icons/lucide.ts +88 -0
  55. package/src/layouts/__tests__/google-sign-in.test.tsx +26 -0
  56. package/src/layouts/__tests__/inbox-page.test.tsx +155 -0
  57. package/src/layouts/__tests__/keyboard-scroll.test.tsx +42 -1
  58. package/src/layouts/__tests__/settings-page-native-look.test.tsx +142 -0
  59. package/src/layouts/__tests__/thread-page.test.tsx +128 -0
  60. package/src/layouts/auth-screen.tsx +6 -3
  61. package/src/layouts/google-sign-in.tsx +42 -0
  62. package/src/layouts/inbox-page.tsx +408 -0
  63. package/src/layouts/index.ts +37 -2
  64. package/src/layouts/keyboard.tsx +61 -9
  65. package/src/layouts/notifications-page.tsx +133 -16
  66. package/src/layouts/settings-page.tsx +117 -14
  67. package/src/layouts/settings-sub-page.tsx +9 -3
  68. package/src/layouts/thread-page.tsx +444 -0
  69. package/src/native-modules.tsx +186 -0
  70. package/dist/chunk-2WCXMJL6.js.map +0 -1
  71. package/dist/chunk-5HRGIA6F.js.map +0 -1
  72. package/dist/chunk-F2TGDKOO.js +0 -43
  73. package/dist/chunk-F2TGDKOO.js.map +0 -1
  74. package/dist/chunk-FZTUSM56.js +0 -935
  75. package/dist/chunk-FZTUSM56.js.map +0 -1
  76. package/dist/chunk-TXJT55JC.js.map +0 -1
  77. package/dist/chunk-ULS7I6ZS.js.map +0 -1
@@ -0,0 +1,128 @@
1
+ // @feat:inbox-thread
2
+ import { forwardRef, useImperativeHandle, type ReactNode } from "react";
3
+ import { fireEvent, render, screen } from "@testing-library/react";
4
+ import { describe, expect, it, vi } from "vitest";
5
+ import { ThreadPage, getThreadPageStackOptions, readReceiptFor, type ThreadMessage } from "../thread-page";
6
+ import { KeyboardScrollProvider, type KeyboardScrollProps } from "../keyboard";
7
+
8
+ const messages: ThreadMessage[] = [
9
+ { id: "1", body: "The save button does nothing", mine: true, timestamp: "2026-10-24T09:00:00Z" },
10
+ { id: "2", body: "Thanks, we're on it.", mine: false, authorName: "Support", timestamp: "2026-10-24T09:05:00Z" },
11
+ { id: "3", body: "It happens on every screen", mine: true, timestamp: "2026-10-24T09:10:00Z", attachments: [{ id: "s", uri: "file:///shot.png", width: 390, height: 844 }] },
12
+ ];
13
+
14
+ const composer = (over: Partial<Parameters<typeof ThreadPage>[0]["composer"] & object> = {}) => ({
15
+ value: "",
16
+ onChangeText: vi.fn(),
17
+ onSend: vi.fn(),
18
+ ...over,
19
+ });
20
+
21
+ describe("readReceiptFor", () => {
22
+ it("is my newest message sent before the other side read the thread", () => {
23
+ expect(readReceiptFor(messages, "2026-10-24T09:11:00Z")).toBe("3");
24
+ expect(readReceiptFor(messages, "2026-10-24T09:06:00Z")).toBe("1");
25
+ expect(readReceiptFor(messages, "2026-10-24T08:00:00Z")).toBeNull();
26
+ expect(readReceiptFor(messages, null)).toBeNull();
27
+ });
28
+
29
+ it("never marks a message that is still sending or failed", () => {
30
+ const pending: ThreadMessage[] = [...messages, { id: "4", body: "x", mine: true, timestamp: "2026-10-24T09:12:00Z", status: "sending" }];
31
+ expect(readReceiptFor(pending, "2026-10-24T09:20:00Z")).toBe("3");
32
+ });
33
+ });
34
+
35
+ describe("ThreadPage", () => {
36
+ it("renders messages oldest first, theirs with the author's name, and attachments", () => {
37
+ render(<ThreadPage testID="t" messages={messages} composer={composer()} />);
38
+ const list = screen.getByTestId("t-messages");
39
+ const ids = [...list.querySelectorAll('[data-testid^="t-message-"]')].map((el) => el.getAttribute("data-testid")).filter((id) => !id!.endsWith("-time"));
40
+ expect(ids).toEqual(["t-message-1", "t-message-2", "t-message-3"]);
41
+ expect(list.textContent).toContain("Support");
42
+ expect(screen.getByTestId("t-attachment-s")).toBeTruthy();
43
+ expect(screen.getByTestId("t-message-1").getAttribute("aria-label")).toMatch(/^You, The save button does nothing/);
44
+ });
45
+
46
+ it("shows the read receipt under my newest read message", () => {
47
+ render(<ThreadPage testID="t" messages={messages} composer={composer()} readAt="2026-10-24T09:11:00Z" readLabel="Seen" />);
48
+ expect(screen.getByTestId("t-read-receipt").textContent).toBe("Seen");
49
+ });
50
+
51
+ it("sends from the composer, and won't send a blank message", () => {
52
+ const c = composer({ value: " " });
53
+ const { rerender } = render(<ThreadPage testID="t" messages={messages} composer={c} />);
54
+ expect((screen.getByTestId("t-composer-send") as HTMLButtonElement).disabled).toBe(true);
55
+ const typed = composer({ value: "More detail" });
56
+ rerender(<ThreadPage testID="t" messages={messages} composer={typed} />);
57
+ fireEvent.change(screen.getByTestId("t-composer-input"), { target: { value: "More detail!" } });
58
+ expect(typed.onChangeText).toHaveBeenCalledWith("More detail!");
59
+ fireEvent.click(screen.getByTestId("t-composer-send"));
60
+ expect(typed.onSend).toHaveBeenCalled();
61
+ });
62
+
63
+ it("shows a spinner instead of Send while sending", () => {
64
+ render(<ThreadPage testID="t" messages={messages} composer={composer({ value: "x", sending: true })} />);
65
+ expect(screen.getByTestId("t-composer-sending")).toBeTruthy();
66
+ expect(screen.queryByTestId("t-composer-send")).toBeNull();
67
+ });
68
+
69
+ it("is read-only with no composer, and says why", () => {
70
+ render(<ThreadPage testID="t" messages={messages} composer={null} closedNotice="This report is closed." />);
71
+ expect(screen.queryByTestId("t-composer")).toBeNull();
72
+ expect(screen.getByTestId("t-closed").textContent).toBe("This report is closed.");
73
+ });
74
+
75
+ it("retries a failed message on tap", () => {
76
+ const onRetry = vi.fn();
77
+ render(<ThreadPage testID="t" messages={[{ id: "f", body: "hi", mine: true, timestamp: "2026-10-24T09:00:00Z", status: "failed", onRetry }]} composer={composer()} />);
78
+ expect(screen.getByTestId("t-message-f-time").textContent).toMatch(/Not sent/);
79
+ fireEvent.click(screen.getByTestId("t-message-f"));
80
+ expect(onRetry).toHaveBeenCalled();
81
+ });
82
+
83
+ it("loads earlier messages from the top", () => {
84
+ const onLoadEarlier = vi.fn();
85
+ render(<ThreadPage testID="t" messages={messages} composer={composer()} hasEarlier onLoadEarlier={onLoadEarlier} />);
86
+ fireEvent.click(screen.getByTestId("t-earlier"));
87
+ expect(onLoadEarlier).toHaveBeenCalled();
88
+ });
89
+
90
+ it("fills the composer accessory and header slots", () => {
91
+ const Attach = ({ testID }: { testID: string }) => <button data-testid={testID}>Attach</button>;
92
+ render(<ThreadPage testID="t" messages={messages} composer={composer()} header={<span data-testid="about" />} slots={{ composerAccessory: Attach }} />);
93
+ expect(screen.getByTestId("t-composer-accessory")).toBeTruthy();
94
+ expect(screen.getByTestId("about")).toBeTruthy();
95
+ });
96
+
97
+ it("shows the empty state for a thread with no messages", () => {
98
+ render(<ThreadPage testID="t" messages={[]} composer={composer()} emptyTitle="Say hello" />);
99
+ expect(screen.getByTestId("t-empty").textContent).toContain("Say hello");
100
+ });
101
+
102
+ it("falls back to a KeyboardAvoidingView without a keyboard scroll view", () => {
103
+ render(<ThreadPage testID="t" messages={messages} composer={composer()} />);
104
+ expect(screen.getByTestId("t-kav")).toBeTruthy();
105
+ expect(screen.queryByTestId("t-keyboard")).toBeNull();
106
+ });
107
+
108
+ it("puts the messages and the composer in the app's keyboard scroll view, and scrolls to the newest", () => {
109
+ const scrollToEnd = vi.fn();
110
+ const Scroll = forwardRef<unknown, KeyboardScrollProps & { children?: ReactNode }>(function Scroll({ children, testID }, ref) {
111
+ useImperativeHandle(ref, () => ({ scrollToEnd }));
112
+ return <div data-testid={testID}>{children}</div>;
113
+ });
114
+ render(
115
+ <KeyboardScrollProvider component={Scroll}>
116
+ <ThreadPage testID="t" messages={messages} composer={composer()} />
117
+ </KeyboardScrollProvider>,
118
+ );
119
+ const scroll = screen.getByTestId("t-keyboard");
120
+ expect(scroll.querySelector('[data-testid="t-composer-input"]')).toBeTruthy();
121
+ expect(screen.queryByTestId("t-kav")).toBeNull();
122
+ expect(scrollToEnd).toHaveBeenCalled();
123
+ });
124
+
125
+ it("composes a standard header by default", () => {
126
+ expect(getThreadPageStackOptions({ headerTitle: "Report" })).toEqual({ title: "Report" });
127
+ });
128
+ });
@@ -7,7 +7,8 @@
7
7
  *
8
8
  * The form stays above the keyboard on small phones: with the app's
9
9
  * `KeyboardScrollProvider` (react-native-keyboard-controller), else with
10
- * `KeyboardAvoidingView`. In development, on
10
+ * `KeyboardAvoidingView`. With the provider's `toolbar` (`KeyboardToolbar`),
11
+ * a previous / next / done bar rides above the keyboard. In development, on
11
12
  * iOS, it warns when a third-party provider is offered without Sign in with
12
13
  * Apple (App Store Review Guideline 4.8 rejects that). `appleProvider()`
13
14
  * adds Apple's own button in one line.
@@ -31,7 +32,7 @@ import {
31
32
  type SocialAuthProvider,
32
33
  } from "./auth";
33
34
  import { ScreenContainer } from "./screen-container";
34
- import { useKeyboardScroll } from "./keyboard";
35
+ import { KEYBOARD_TOOLBAR_HEIGHT, useKeyboardScroll, useKeyboardToolbar } from "./keyboard";
35
36
 
36
37
  /** The parts of an {@link AuthScreen} that `slots` and `slotProps` reach. */
37
38
  export type AuthScreenSlotMap = {
@@ -80,6 +81,7 @@ export function AuthScreen({
80
81
  onForgotPassword && (form.mode ?? "password") === "password" ? <ForgotPasswordLink onPress={onForgotPassword} /> : null;
81
82
  const formProps: AuthFormProps = { ...form, belowFields: form.belowFields ?? forgot, testID: form.testID ?? `${testID}-form` };
82
83
  const KeyboardScroll = useKeyboardScroll();
84
+ const KeyboardToolbar = useKeyboardToolbar();
83
85
  const content = (
84
86
  <>
85
87
  {branding ? renderSlot(AuthBranding, slots.branding, { ...branding, testID: branding.testID ?? `${testID}-branding` }, slotProps.branding) : null}
@@ -97,11 +99,12 @@ export function AuthScreen({
97
99
  testID={`${testID}-keyboard`}
98
100
  keyboardShouldPersistTaps="handled"
99
101
  contentInsetAdjustmentBehavior="automatic"
100
- bottomOffset={24}
102
+ bottomOffset={KeyboardToolbar ? 24 + KEYBOARD_TOOLBAR_HEIGHT : 24}
101
103
  contentContainerStyle={{ flexGrow: 1, justifyContent: "center", gap: 24, paddingHorizontal: 24, paddingVertical: 32 }}
102
104
  >
103
105
  {content}
104
106
  </KeyboardScroll>
107
+ {KeyboardToolbar ? <KeyboardToolbar /> : null}
105
108
  </ScreenContainer>
106
109
  );
107
110
  }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Google sign-in for `AuthScreen` / `SocialAuthRow`: the provider entry,
3
+ * drawn as the row's outline button. Nothing here imports
4
+ * `@react-native-google-signin/google-signin`; sign in with
5
+ * `signInWithGoogle` from `@marktiderman/genesis-supabase/native`.
6
+ *
7
+ * ```tsx
8
+ * <AuthScreen providers={[appleProvider({ apple, onPress: onApple }), googleProvider({ onPress: onGoogle })]} … />
9
+ * ```
10
+ *
11
+ * Google's branding guidelines want its "G" mark on the button: pass it as
12
+ * `icon` (Genesis ships no Google artwork). On iOS, offer Sign in with Apple
13
+ * too (App Store Review Guideline 4.8); `AuthScreen` warns in development
14
+ * when it's missing.
15
+ *
16
+ * @stability Beta
17
+ */
18
+ import type { ReactNode } from "react";
19
+ import type { SocialAuthProvider } from "./auth";
20
+
21
+ export interface GoogleProviderOptions {
22
+ /** Usually `() => signInWithGoogle(supabase, GoogleOneTapSignIn, { digest })`. */
23
+ onPress: () => void | Promise<void>;
24
+ /** Default "Continue with Google", Google's own wording. */
25
+ label?: string;
26
+ /** Google's "G" mark, as the app draws it. */
27
+ icon?: ReactNode;
28
+ disabled?: boolean;
29
+ /** `false` (or `null`) gives `null`, so a switched-off provider goes in the list as is. Default true. */
30
+ enabled?: boolean | null;
31
+ }
32
+
33
+ /**
34
+ * A `SocialAuthProvider` (id `"google"`) for `AuthScreen`'s `providers`, or
35
+ * `null` when `enabled` is false.
36
+ *
37
+ * @stability Beta
38
+ */
39
+ export function googleProvider({ onPress, label = "Continue with Google", icon, disabled, enabled = true }: GoogleProviderOptions): SocialAuthProvider | null {
40
+ if (!enabled) return null;
41
+ return { id: "google", label, icon, onPress, disabled };
42
+ }
@@ -0,0 +1,408 @@
1
+ /**
2
+ * InboxPage — a list of conversations or tickets: unread state, a time, a
3
+ * preview line, swipe actions, pull to refresh, paging and an empty state.
4
+ *
5
+ * Generic: the rows are whatever the app has (support reports, direct
6
+ * messages, an idea board). Data and actions come in as props; the layout
7
+ * draws them the platform's way. On iOS it is the Settings app's inset
8
+ * grouped style, like `SettingsPage`: the page is `groupedBackground`, the
9
+ * rows one rounded group on `surface` with hairline separators that start at
10
+ * the text. On Android rows are full width.
11
+ *
12
+ * Swipe actions: each row's `swipeActions` are always reachable without a
13
+ * gesture library, as VoiceOver / TalkBack custom actions and on long press
14
+ * (a menu). For the swipe itself, fill the `swipeable` slot with your
15
+ * gesture-handler wrapper (`ReanimatedSwipeable` from
16
+ * react-native-gesture-handler, an optional peer); it receives the actions
17
+ * and the row.
18
+ *
19
+ * Slots: `row`, `swipeable`, `header` (above the group), `footer` (below it,
20
+ * the paging spinner by default) and `empty`. `slots` swaps a part for your
21
+ * component (same props), `slotProps` feeds the default more props, `null`
22
+ * drops it.
23
+ *
24
+ * Header: `getInboxPageStackOptions()` for `<Stack.Screen options>`.
25
+ *
26
+ * @stability Beta
27
+ */
28
+ import { Fragment, useState, type ReactNode } from "react";
29
+ import { renderSlot, type SlotPropsFor, type Slots } from "@marktiderman/genesis-core/slots";
30
+ import { ActivityIndicator, Alert, FlatList, Platform, Pressable, RefreshControl, StyleSheet, View } from "react-native";
31
+ import { SafeAreaView } from "react-native-safe-area-context";
32
+ import { useThemeRoles } from "../hooks/use-theme-roles";
33
+ import { NativeEmptyState } from "../components/empty-state";
34
+ import { NativeText } from "../components/text";
35
+ import { NativeButton } from "../components/button";
36
+ import { NativeBadge } from "../components/badge";
37
+ import { composeHeaderOptions, type ScreenHeaderProps } from "./screen-container";
38
+
39
+ /** An action on a row: swipe, long press, or an accessibility action. */
40
+ export interface InboxSwipeAction {
41
+ id: string;
42
+ label: string;
43
+ onPress: () => void;
44
+ /** Destructive tone (delete, leave). */
45
+ destructive?: boolean;
46
+ }
47
+
48
+ export interface InboxItem {
49
+ /** Stable id for keying. */
50
+ id: string;
51
+ title: string;
52
+ /** The latest message or a summary, at most two lines. */
53
+ preview?: string;
54
+ /** When it last changed. Shown as a short time or date. */
55
+ timestamp?: string | Date;
56
+ /** Something new the person hasn't read: a dot, and the title in bold. */
57
+ unread?: boolean;
58
+ /** How many unread messages; shown as a count instead of the dot when above 0. */
59
+ unreadCount?: number;
60
+ /** A short status shown under the preview ("In progress", "12 votes"). */
61
+ meta?: string;
62
+ /** Replaces the unread dot (an avatar, an icon). */
63
+ leading?: ReactNode;
64
+ /** Shown at the end of the row (a vote button, a badge). Replaces the chevron. */
65
+ trailing?: ReactNode;
66
+ /** Opens the conversation. Rows with `onPress` show a chevron unless `trailing` is set. */
67
+ onPress?: () => void;
68
+ swipeActions?: InboxSwipeAction[];
69
+ /** testID override. Default `<page testID>-row-<id>`. */
70
+ testID?: string;
71
+ }
72
+
73
+ /** The parts `slots` and `slotProps` reach, with the props each receives. */
74
+ export type InboxPageSlotMap = {
75
+ row: InboxItem & { testID: string; isFirst: boolean; isLast: boolean; timeLabel: string | null };
76
+ swipeable: { actions: InboxSwipeAction[]; testID: string; children?: ReactNode };
77
+ header: { testID: string };
78
+ footer: { loadingMore: boolean; testID: string };
79
+ empty: { title: string; body: string; actionLabel?: string; onAction?: () => void; testID: string };
80
+ };
81
+
82
+ export interface InboxPageProps extends ScreenHeaderProps {
83
+ /** Newest first, as they should show. Empty → the empty state. */
84
+ items: InboxItem[];
85
+ refreshing?: boolean;
86
+ onRefresh?: () => void | Promise<void>;
87
+ /** Called near the end of the list, to load the next page. */
88
+ onEndReached?: () => void;
89
+ /** A next page is loading: the default footer shows a spinner. */
90
+ loadingMore?: boolean;
91
+ /** Above the group (a filter, a call to action). Prefer `slots.header` for a component. */
92
+ header?: ReactNode;
93
+ /** An optional title over the group, in the Settings header style. */
94
+ sectionTitle?: string;
95
+ emptyTitle?: string;
96
+ emptyBody?: string;
97
+ /** The first page is loading: a spinner instead of the empty state. */
98
+ loading?: boolean;
99
+ /** The read failed: the empty slot shows `errorTitle` / `errorBody` instead (and pull to refresh retries). */
100
+ error?: boolean;
101
+ errorTitle?: string;
102
+ errorBody?: string;
103
+ /** A button in the empty state ("Send feedback"). */
104
+ emptyActionLabel?: string;
105
+ onEmptyAction?: () => void;
106
+ /** How a row's time reads. Default: the time today, "Yesterday", the weekday this week, else the date. */
107
+ formatTime?: (date: Date, now: Date) => string;
108
+ /** The clock, for tests. */
109
+ now?: () => Date;
110
+ slots?: Slots<InboxPageSlotMap>;
111
+ slotProps?: SlotPropsFor<InboxPageSlotMap>;
112
+ /** testID on the root. Default `"inbox-page"`. */
113
+ testID?: string;
114
+ }
115
+
116
+ /** `<Stack.Screen options>` for an InboxPage: a large title that collapses on scroll. */
117
+ export function getInboxPageStackOptions(props: ScreenHeaderProps & { headerTitle?: string }): Record<string, unknown> {
118
+ return composeHeaderOptions({
119
+ headerTitle: props.headerTitle ?? "Inbox",
120
+ large: props.large ?? true,
121
+ scrollEdgeBehavior: props.scrollEdgeBehavior ?? "match",
122
+ headerLeft: props.headerLeft,
123
+ headerRight: props.headerRight,
124
+ headerOptions: props.headerOptions,
125
+ });
126
+ }
127
+
128
+ const DAY_MS = 24 * 60 * 60 * 1000;
129
+
130
+ /** The default row time: `9:41`, `Yesterday`, `Monday`, then a short date. */
131
+ export function formatInboxTime(date: Date, now: Date): string {
132
+ const start = (d: Date) => new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
133
+ const days = Math.round((start(now) - start(date)) / DAY_MS);
134
+ if (days <= 0) return date.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" });
135
+ if (days === 1) return "Yesterday";
136
+ if (days < 7) return date.toLocaleDateString(undefined, { weekday: "long" });
137
+ return date.toLocaleDateString(undefined, { day: "numeric", month: "short", year: date.getFullYear() === now.getFullYear() ? undefined : "numeric" });
138
+ }
139
+
140
+ /** UIKit's inset grouped margin on a phone, in points (as SettingsPage). */
141
+ const IOS_GROUP_MARGIN = 16;
142
+
143
+ function iosGroupRadius(): number {
144
+ return Number.parseFloat(String(Platform.Version)) >= 26 ? 26 : 10;
145
+ }
146
+
147
+ export function InboxPage({
148
+ items,
149
+ refreshing,
150
+ onRefresh,
151
+ onEndReached,
152
+ loadingMore = false,
153
+ header,
154
+ sectionTitle,
155
+ emptyTitle,
156
+ emptyBody,
157
+ emptyActionLabel,
158
+ onEmptyAction,
159
+ loading = false,
160
+ error = false,
161
+ errorTitle,
162
+ errorBody,
163
+ formatTime = formatInboxTime,
164
+ now = () => new Date(),
165
+ slots = {},
166
+ slotProps = {},
167
+ testID = "inbox-page",
168
+ }: InboxPageProps) {
169
+ const colors = useThemeRoles();
170
+ const clock = now();
171
+ const rows: InboxPageSlotMap["row"][] = items.map((item, index) => ({
172
+ ...item,
173
+ testID: item.testID ?? `${testID}-row-${item.id}`,
174
+ isFirst: index === 0,
175
+ isLast: index === items.length - 1,
176
+ timeLabel: item.timestamp ? formatTime(typeof item.timestamp === "string" ? new Date(item.timestamp) : item.timestamp, clock) : null,
177
+ }));
178
+
179
+ const headerNode = (
180
+ <View>
181
+ {header ?? renderSlot(EmptyPart, slots.header, { testID: `${testID}-header` }, slotProps.header)}
182
+ {sectionTitle ? <SectionTitle title={sectionTitle} testID={`${testID}-section-title`} /> : null}
183
+ </View>
184
+ );
185
+
186
+ if (items.length === 0) {
187
+ return (
188
+ <SafeAreaView testID={testID} edges={["left", "right", "bottom"]} style={{ flex: 1, backgroundColor: colors.groupedBackground }}>
189
+ {headerNode}
190
+ {loading ? (
191
+ <View testID={`${testID}-loading`} style={{ paddingVertical: 32 }}>
192
+ <ActivityIndicator accessibilityLabel="Loading" />
193
+ </View>
194
+ ) : (
195
+ renderSlot(
196
+ DefaultEmpty,
197
+ slots.empty,
198
+ error
199
+ ? {
200
+ title: errorTitle ?? "Couldn't load this",
201
+ body: errorBody ?? "Check your connection, then pull to refresh.",
202
+ actionLabel: onRefresh ? "Try again" : undefined,
203
+ onAction: onRefresh ? () => void onRefresh() : undefined,
204
+ testID: `${testID}-error`,
205
+ }
206
+ : {
207
+ title: emptyTitle ?? "Nothing here yet",
208
+ body: emptyBody ?? "When there's something new, it shows up here.",
209
+ actionLabel: emptyActionLabel,
210
+ onAction: onEmptyAction,
211
+ testID: `${testID}-empty`,
212
+ },
213
+ slotProps.empty,
214
+ )
215
+ )}
216
+ </SafeAreaView>
217
+ );
218
+ }
219
+
220
+ return (
221
+ <SafeAreaView testID={testID} edges={["left", "right", "bottom"]} style={{ flex: 1, backgroundColor: colors.groupedBackground }}>
222
+ <FlatList
223
+ testID={`${testID}-list`}
224
+ data={rows}
225
+ keyExtractor={(row) => row.id}
226
+ contentInsetAdjustmentBehavior="automatic"
227
+ // The header can hold a text field (the idea board's "Suggest"): its button's first tap
228
+ // must press it, not only close the keyboard.
229
+ keyboardShouldPersistTaps="handled"
230
+ ListHeaderComponent={headerNode}
231
+ ListFooterComponent={renderSlot(DefaultFooter, slots.footer, { loadingMore, testID: `${testID}-footer` }, slotProps.footer)}
232
+ contentContainerStyle={{ paddingTop: 8, paddingBottom: 32 }}
233
+ onEndReached={onEndReached}
234
+ onEndReachedThreshold={0.5}
235
+ refreshControl={onRefresh ? <RefreshControl testID={`${testID}-refresh`} refreshing={!!refreshing} onRefresh={onRefresh} /> : undefined}
236
+ renderItem={({ item: row }) => {
237
+ const content = renderSlot(DefaultRow, slots.row, row, slotProps.row);
238
+ const actions = row.swipeActions ?? [];
239
+ return (
240
+ <Fragment>
241
+ {actions.length && slots.swipeable !== null
242
+ ? renderSlot(PassThroughSwipeable, slots.swipeable, { actions, testID: `${row.testID}-swipe`, children: content }, slotProps.swipeable)
243
+ : content}
244
+ </Fragment>
245
+ );
246
+ }}
247
+ />
248
+ </SafeAreaView>
249
+ );
250
+ }
251
+
252
+ function EmptyPart(_props: InboxPageSlotMap["header"]) {
253
+ return null;
254
+ }
255
+
256
+ /** The default `swipeable`: no gesture, just the row (its actions are on long press and in the accessibility actions). */
257
+ function PassThroughSwipeable({ children }: InboxPageSlotMap["swipeable"]) {
258
+ return <>{children}</>;
259
+ }
260
+
261
+ function SectionTitle({ title, testID }: { title: string; testID: string }) {
262
+ const colors = useThemeRoles();
263
+ const ios = Platform.OS === "ios";
264
+ return (
265
+ <NativeText
266
+ testID={testID}
267
+ accessibilityRole="header"
268
+ className={ios ? "px-4 pb-1.5 pt-2" : "px-4 pb-2 pt-4 text-primary"}
269
+ style={
270
+ ios
271
+ ? { marginHorizontal: IOS_GROUP_MARGIN, color: colors.secondaryLabel, fontSize: 13, lineHeight: 18, textTransform: "uppercase" }
272
+ : { fontSize: 14, lineHeight: 20, fontWeight: "500" }
273
+ }
274
+ >
275
+ {title}
276
+ </NativeText>
277
+ );
278
+ }
279
+
280
+ /** Opens a row's actions as a menu (long press). */
281
+ export function showInboxActions(title: string, actions: InboxSwipeAction[], cancelLabel = "Cancel"): void {
282
+ Alert.alert(title, undefined, [
283
+ ...actions.map((a) => ({ text: a.label, style: a.destructive ? ("destructive" as const) : ("default" as const), onPress: a.onPress })),
284
+ { text: cancelLabel, style: "cancel" as const },
285
+ ]);
286
+ }
287
+
288
+ function DefaultRow(row: InboxPageSlotMap["row"]) {
289
+ const colors = useThemeRoles();
290
+ const ios = Platform.OS === "ios";
291
+ const [pressed, setPressed] = useState(false);
292
+ const actions = row.swipeActions ?? [];
293
+ const radius = iosGroupRadius();
294
+ const unreadLabel = row.unreadCount && row.unreadCount > 0 ? `${row.unreadCount} unread` : row.unread ? "Unread" : null;
295
+ const label = [unreadLabel, row.title, row.timeLabel, row.preview, row.meta].filter(Boolean).join(", ");
296
+ return (
297
+ <View
298
+ testID={`${row.testID}-cell`}
299
+ style={[
300
+ { backgroundColor: colors.surface },
301
+ ios
302
+ ? {
303
+ marginHorizontal: IOS_GROUP_MARGIN,
304
+ borderTopLeftRadius: row.isFirst ? radius : 0,
305
+ borderTopRightRadius: row.isFirst ? radius : 0,
306
+ borderBottomLeftRadius: row.isLast ? radius : 0,
307
+ borderBottomRightRadius: row.isLast ? radius : 0,
308
+ overflow: "hidden",
309
+ }
310
+ : null,
311
+ ]}
312
+ >
313
+ <Pressable
314
+ testID={row.testID}
315
+ accessibilityRole={row.onPress ? "button" : undefined}
316
+ accessibilityLabel={label}
317
+ accessibilityActions={actions.map((a) => ({ name: a.id, label: a.label }))}
318
+ onAccessibilityAction={(event) => actions.find((a) => a.id === event.nativeEvent.actionName)?.onPress()}
319
+ onPress={row.onPress}
320
+ onLongPress={actions.length ? () => showInboxActions(row.title, actions) : undefined}
321
+ onPressIn={() => setPressed(true)}
322
+ onPressOut={() => setPressed(false)}
323
+ style={{ flexDirection: "row", alignItems: "center", paddingHorizontal: 16, paddingVertical: 11, minHeight: 60, backgroundColor: pressed && row.onPress ? colors.fill : undefined }}
324
+ >
325
+ <View style={{ width: 18, alignItems: "flex-start" }}>
326
+ {row.leading ?? (row.unreadCount && row.unreadCount > 0 ? null : <UnreadDot unread={!!row.unread} testID={`${row.testID}-unread`} color={colors.tint} />)}
327
+ </View>
328
+ <View style={{ flex: 1, minWidth: 0 }}>
329
+ <View style={{ flexDirection: "row", alignItems: "baseline" }}>
330
+ <NativeText
331
+ numberOfLines={1}
332
+ style={{ flex: 1, color: colors.label, fontSize: 17, lineHeight: 22, fontWeight: row.unread || (row.unreadCount ?? 0) > 0 ? "600" : "400" }}
333
+ >
334
+ {row.title}
335
+ </NativeText>
336
+ {row.timeLabel ? (
337
+ <NativeText testID={`${row.testID}-time`} style={{ marginLeft: 8, color: colors.secondaryLabel, fontSize: 15, lineHeight: 20 }}>
338
+ {row.timeLabel}
339
+ </NativeText>
340
+ ) : null}
341
+ </View>
342
+ {row.preview ? (
343
+ <NativeText numberOfLines={2} style={{ marginTop: 2, color: colors.secondaryLabel, fontSize: 15, lineHeight: 20 }}>
344
+ {row.preview}
345
+ </NativeText>
346
+ ) : null}
347
+ {row.meta ? (
348
+ <NativeText testID={`${row.testID}-meta`} style={{ marginTop: 4, color: colors.tertiaryLabel, fontSize: 13, lineHeight: 18 }}>
349
+ {row.meta}
350
+ </NativeText>
351
+ ) : null}
352
+ </View>
353
+ {row.unreadCount && row.unreadCount > 0 ? (
354
+ <View style={{ marginLeft: 8 }}>
355
+ <NativeBadge testID={`${row.testID}-count`}>{String(row.unreadCount)}</NativeBadge>
356
+ </View>
357
+ ) : null}
358
+ {row.trailing ? <View style={{ marginLeft: 8 }}>{row.trailing}</View> : row.onPress ? <Chevron color={colors.tertiaryLabel} /> : null}
359
+ </Pressable>
360
+ {row.isLast ? null : (
361
+ <View accessibilityElementsHidden importantForAccessibility="no-hide-descendants" style={{ flexDirection: "row", height: StyleSheet.hairlineWidth }}>
362
+ <View style={{ width: 34 }} />
363
+ <View testID={`${row.testID}-separator-line`} style={{ flex: 1, backgroundColor: colors.separator }} />
364
+ </View>
365
+ )}
366
+ </View>
367
+ );
368
+ }
369
+
370
+ function Chevron({ color }: { color: unknown }) {
371
+ return (
372
+ <NativeText accessibilityElementsHidden importantForAccessibility="no" style={{ marginLeft: 8, color: color as string, fontSize: 20, lineHeight: 22 }}>
373
+ ›
374
+ </NativeText>
375
+ );
376
+ }
377
+
378
+ function UnreadDot({ unread, testID, color }: { unread: boolean; testID: string; color: unknown }) {
379
+ if (!unread) return <View testID={testID} style={{ width: 10, height: 10 }} />;
380
+ return <View testID={testID} style={{ width: 10, height: 10, borderRadius: 5, backgroundColor: color as string }} />;
381
+ }
382
+
383
+ function DefaultFooter({ loadingMore, testID }: InboxPageSlotMap["footer"]) {
384
+ if (!loadingMore) return null;
385
+ return (
386
+ <View testID={testID} style={{ paddingVertical: 16 }}>
387
+ <ActivityIndicator accessibilityLabel="Loading more" />
388
+ </View>
389
+ );
390
+ }
391
+
392
+ function DefaultEmpty({ title, body, actionLabel, onAction, testID }: InboxPageSlotMap["empty"]) {
393
+ return (
394
+ <NativeEmptyState
395
+ variant="first-run"
396
+ title={title}
397
+ body={body}
398
+ testID={testID}
399
+ primaryAction={
400
+ actionLabel && onAction ? (
401
+ <NativeButton onPress={onAction} testID={`${testID}-action`}>
402
+ {actionLabel}
403
+ </NativeButton>
404
+ ) : undefined
405
+ }
406
+ />
407
+ );
408
+ }