create-expo-boilerplate 1.1.2 → 1.2.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 (99) hide show
  1. package/README.md +38 -0
  2. package/dist/add.js +218 -0
  3. package/dist/generate.js +3 -1
  4. package/dist/index.js +35 -5
  5. package/dist/manifest.js +51 -0
  6. package/dist/modules/index.js +7 -0
  7. package/dist/modules/notifications.js +241 -0
  8. package/dist/modules/shared.js +67 -0
  9. package/dist/modules/subscriptions.js +223 -0
  10. package/dist/modules/types.js +57 -0
  11. package/dist/steps/format.js +11 -2
  12. package/dist/steps/javascript.js +14 -7
  13. package/dist/steps/readme.js +1 -0
  14. package/dist/steps/styling.js +1 -0
  15. package/dist/template.js +2 -0
  16. package/dist/versions.js +8 -0
  17. package/modules/notifications/files/plugins/withAndroidDefaultNotificationChannel.js +64 -0
  18. package/modules/notifications/files/src/notifications/NotificationProvider.tsx +309 -0
  19. package/modules/notifications/files/src/notifications/NotificationRoot.tsx +21 -0
  20. package/modules/notifications/files/src/notifications/README.md +763 -0
  21. package/modules/notifications/files/src/notifications/__tests__/NotificationProvider.test.tsx +358 -0
  22. package/modules/notifications/files/src/notifications/__tests__/pendingPress.test.ts +61 -0
  23. package/modules/notifications/files/src/notifications/__tests__/permissionState.test.ts +92 -0
  24. package/modules/notifications/files/src/notifications/__tests__/routing.test.ts +109 -0
  25. package/modules/notifications/files/src/notifications/__tests__/service.test.ts +189 -0
  26. package/modules/notifications/files/src/notifications/backgroundHandler.ts +158 -0
  27. package/modules/notifications/files/src/notifications/channels.ts +70 -0
  28. package/modules/notifications/files/src/notifications/components/NotificationPermissionBanner.tsx +134 -0
  29. package/modules/notifications/files/src/notifications/config.ts +179 -0
  30. package/modules/notifications/files/src/notifications/index.ts +90 -0
  31. package/modules/notifications/files/src/notifications/log.ts +57 -0
  32. package/modules/notifications/files/src/notifications/navigation.ts +11 -0
  33. package/modules/notifications/files/src/notifications/pendingPress.ts +86 -0
  34. package/modules/notifications/files/src/notifications/permissionState.ts +75 -0
  35. package/modules/notifications/files/src/notifications/routing.ts +99 -0
  36. package/modules/notifications/files/src/notifications/service.ts +476 -0
  37. package/modules/notifications/files/src/notifications/setup.ts +18 -0
  38. package/modules/notifications/files/src/notifications/types.ts +74 -0
  39. package/modules/notifications/files/src/notifications/useNotificationPermission.ts +80 -0
  40. package/modules/notifications/files/src/notifications/useNotificationSync.ts +71 -0
  41. package/modules/notifications/files/src/notifications/useNotifications.ts +13 -0
  42. package/modules/notifications/overlays/react-navigation/src/navigation/navigationRef.ts +6 -0
  43. package/modules/notifications/overlays/react-navigation/src/notifications/navigation.ts +38 -0
  44. package/modules/notifications/overlays/styling/stylesheet/src/notifications/components/NotificationPermissionBanner.tsx +134 -0
  45. package/modules/notifications/overlays/styling/tailwind/src/notifications/components/NotificationPermissionBanner.tsx +108 -0
  46. package/modules/notifications/translations/ar.json +12 -0
  47. package/modules/notifications/translations/en.json +12 -0
  48. package/modules/notifications/translations/es.json +12 -0
  49. package/modules/subscriptions/files/src/app/subscription.tsx +1 -0
  50. package/modules/subscriptions/files/src/subscription/README.md +215 -0
  51. package/modules/subscriptions/files/src/subscription/SubscriptionProvider.tsx +562 -0
  52. package/modules/subscriptions/files/src/subscription/SubscriptionRoot.tsx +30 -0
  53. package/modules/subscriptions/files/src/subscription/__tests__/SubscriptionProvider.test.tsx +931 -0
  54. package/modules/subscriptions/files/src/subscription/__tests__/UnlockModal.test.tsx +79 -0
  55. package/modules/subscriptions/files/src/subscription/__tests__/config.test.ts +23 -0
  56. package/modules/subscriptions/files/src/subscription/__tests__/introOffer.test.ts +93 -0
  57. package/modules/subscriptions/files/src/subscription/__tests__/offeringContent.test.ts +215 -0
  58. package/modules/subscriptions/files/src/subscription/__tests__/planChange.test.ts +356 -0
  59. package/modules/subscriptions/files/src/subscription/__tests__/purchaseErrors.test.ts +111 -0
  60. package/modules/subscriptions/files/src/subscription/__tests__/service.test.ts +369 -0
  61. package/modules/subscriptions/files/src/subscription/__tests__/statusNotice.test.ts +259 -0
  62. package/modules/subscriptions/files/src/subscription/__tests__/subscriptionState.test.ts +690 -0
  63. package/modules/subscriptions/files/src/subscription/components/CrossPlatformNotice.tsx +94 -0
  64. package/modules/subscriptions/files/src/subscription/components/PremiumGate.tsx +74 -0
  65. package/modules/subscriptions/files/src/subscription/components/SubscriptionStatusNotice.tsx +153 -0
  66. package/modules/subscriptions/files/src/subscription/components/UnlockModal.tsx +223 -0
  67. package/modules/subscriptions/files/src/subscription/config.ts +54 -0
  68. package/modules/subscriptions/files/src/subscription/index.ts +95 -0
  69. package/modules/subscriptions/files/src/subscription/introOffer.ts +61 -0
  70. package/modules/subscriptions/files/src/subscription/management.ts +30 -0
  71. package/modules/subscriptions/files/src/subscription/navigation.ts +15 -0
  72. package/modules/subscriptions/files/src/subscription/offeringContent.ts +259 -0
  73. package/modules/subscriptions/files/src/subscription/planChange.ts +219 -0
  74. package/modules/subscriptions/files/src/subscription/purchaseErrors.ts +140 -0
  75. package/modules/subscriptions/files/src/subscription/screens/PaywallScreen.tsx +466 -0
  76. package/modules/subscriptions/files/src/subscription/service.ts +270 -0
  77. package/modules/subscriptions/files/src/subscription/statusNotice.ts +189 -0
  78. package/modules/subscriptions/files/src/subscription/subscriptionState.ts +485 -0
  79. package/modules/subscriptions/files/src/subscription/types.ts +164 -0
  80. package/modules/subscriptions/files/src/subscription/useSubscriptionUser.ts +29 -0
  81. package/modules/subscriptions/overlays/react-navigation/src/navigation/navigationRef.ts +6 -0
  82. package/modules/subscriptions/overlays/react-navigation/src/subscription/navigation.ts +14 -0
  83. package/modules/subscriptions/overlays/styling/stylesheet/src/subscription/components/CrossPlatformNotice.tsx +94 -0
  84. package/modules/subscriptions/overlays/styling/stylesheet/src/subscription/components/SubscriptionStatusNotice.tsx +153 -0
  85. package/modules/subscriptions/overlays/styling/stylesheet/src/subscription/components/UnlockModal.tsx +227 -0
  86. package/modules/subscriptions/overlays/styling/stylesheet/src/subscription/screens/PaywallScreen.tsx +467 -0
  87. package/modules/subscriptions/overlays/styling/tailwind/src/subscription/components/CrossPlatformNotice.tsx +74 -0
  88. package/modules/subscriptions/overlays/styling/tailwind/src/subscription/components/SubscriptionStatusNotice.tsx +136 -0
  89. package/modules/subscriptions/overlays/styling/tailwind/src/subscription/components/UnlockModal.tsx +181 -0
  90. package/modules/subscriptions/overlays/styling/tailwind/src/subscription/screens/PaywallScreen.tsx +364 -0
  91. package/modules/subscriptions/translations/ar.json +128 -0
  92. package/modules/subscriptions/translations/en.json +112 -0
  93. package/modules/subscriptions/translations/es.json +112 -0
  94. package/package.json +3 -2
  95. package/template/jest.config.js +3 -1
  96. package/template/jest.setup.ts +36 -10
  97. package/template/src/localization/__tests__/i18n.test.ts +25 -0
  98. package/template/src/services/client.ts +14 -5
  99. package/template/src/shared/components/__tests__/Button.test.tsx +24 -0
@@ -123,12 +123,13 @@ function resolveSpecifier(fromFile, spec) {
123
123
  // `import … from '…'`, `export … from '…'` (possibly multi-line) and `import '…'`.
124
124
  const FROM_STATEMENT_RE = /^(?:import|export)\b[^;'"]*?\bfrom\s*['"]([^'"]+)['"];?[ \t]*\n?/gm;
125
125
  const SIDE_EFFECT_IMPORT_RE = /^import\s*['"]([^'"]+)['"];?[ \t]*\n?/gm;
126
- export async function convertToJavaScript(files, pkg, options) {
127
- const all = await files.list();
128
- // 1. Declaration files carry nothing at runtime.
129
- await files.remove(...all.filter((f) => f.endsWith('.d.ts')));
130
- // 2. Transpile.
131
- const sources = all.filter((f) => /\.tsx?$/.test(f) && !f.endsWith('.d.ts'));
126
+ /**
127
+ * Transpiles `sources` (.ts/.tsx, project-relative) to .js/.jsx in place.
128
+ * Files that only held types are deleted, along with every import / re-export
129
+ * among `sources` that pointed at them. Used for whole projects and for the
130
+ * files a module adds to a JavaScript project.
131
+ */
132
+ export async function transpileFiles(files, sources) {
132
133
  const output = new Map(); // new path → code
133
134
  const emptied = new Set(); // old path without extension
134
135
  for (const rel of sources) {
@@ -140,7 +141,6 @@ export async function convertToJavaScript(files, pkg, options) {
140
141
  output.set(jsName(rel), code);
141
142
  await files.remove(rel);
142
143
  }
143
- // 3. Drop imports / re-exports of modules that were types only.
144
144
  const pointsAtEmptied = (fromFile, spec) => {
145
145
  const base = resolveSpecifier(fromFile, spec);
146
146
  return base !== null && (emptied.has(base) || emptied.has(`${base}/index`));
@@ -150,6 +150,13 @@ export async function convertToJavaScript(files, pkg, options) {
150
150
  const cleaned = code.replace(FROM_STATEMENT_RE, drop).replace(SIDE_EFFECT_IMPORT_RE, drop);
151
151
  await files.write(rel, cleaned);
152
152
  }
153
+ }
154
+ export async function convertToJavaScript(files, pkg, options) {
155
+ const all = await files.list();
156
+ // 1. Declaration files carry nothing at runtime.
157
+ await files.remove(...all.filter((f) => f.endsWith('.d.ts')));
158
+ // 2–3. Transpile, and drop imports of modules that were types only.
159
+ await transpileFiles(files, all.filter((f) => /\.tsx?$/.test(f) && !f.endsWith('.d.ts')));
153
160
  // 4. Config that names TS files.
154
161
  await files.remove('tsconfig.json', 'tsconfig.test.json');
155
162
  await files.write('jsconfig.json', `${JSON.stringify({
@@ -90,6 +90,7 @@ export function renderReadme(o) {
90
90
  if (o.husky) {
91
91
  push('', '## Git hooks', '', `- **pre-commit** — blocks direct commits to \`main\`/\`master\`${ts ? ', type-checks,' : ','} and runs lint-staged (${o.eslint ? '`eslint --fix`' : '`prettier --write`'} on staged files).`, '- **commit-msg** — [Conventional Commits](https://www.conventionalcommits.org/) via Commitlint (`feat: …`, `fix: …`).', `- **post-merge** — reinstalls dependencies when the lockfile changed.`);
92
92
  }
93
+ push('', '## Adding modules', '', 'Larger features are added with the CLI that created this app, from the project root. It writes the variant for this stack (recorded in `boilerplate.json`), wires it in, and lists what is left to do:', '', '```bash', 'npx create-expo-boilerplate add notifications # push + local notifications (Firebase Cloud Messaging + NotifyKit)', 'npx create-expo-boilerplate add subscriptions # in-app subscriptions (RevenueCat): paywall, premium gate', 'npx create-expo-boilerplate add notifications --dry-run # list the changes, write nothing', '```', '', 'Commit first: it refuses to run on uncommitted changes, so the module lands as one diff you can review.');
93
94
  push('', '## AI assistant skills', '', '`.skills/` holds task-specific instructions (API hooks, UI, localization) for Claude, Cursor and friends — reference them in prompts, e.g. `@.skills/api-hook-creation.md`.' +
94
95
  (ts ? '' : ' Their code samples are TypeScript; drop the type annotations.'), '');
95
96
  return `${lines.join('\n')}\n`;
@@ -8,6 +8,7 @@ const UNISTYLES_REGION_FILES = [
8
8
  'babel.config.js',
9
9
  'eslint.config.js',
10
10
  'src/styles/themes.ts',
11
+ 'jest.setup.ts',
11
12
  ];
12
13
  /**
13
14
  * Styling-specific sections of `.skills/ui-creation.md`. Each overlay ships a
package/dist/template.js CHANGED
@@ -8,6 +8,8 @@ const here = dirname(fileURLToPath(import.meta.url));
8
8
  /** Root of the published package (`cli/` in the repo). */
9
9
  export const PACKAGE_ROOT = resolve(here, '..');
10
10
  export const OVERLAYS_DIR = join(PACKAGE_ROOT, 'overlays');
11
+ /** Source for `add <module>` — see src/modules/. */
12
+ export const MODULES_DIR = join(PACKAGE_ROOT, 'modules');
11
13
  const PACKAGED_TEMPLATE_DIR = join(PACKAGE_ROOT, 'template');
12
14
  /** The boilerplate itself — the repo root, one level above `cli/`. */
13
15
  const REPO_ROOT = resolve(PACKAGE_ROOT, '..');
package/dist/versions.js CHANGED
@@ -13,6 +13,14 @@ export const VERSIONS = {
13
13
  // Tailwind styling (Uniwind compiles Tailwind v4 at bundle time)
14
14
  uniwind: '^1.13.1',
15
15
  tailwindcss: '^4.3.3',
16
+ // `add notifications`. Messaging's peer pins the exact app version, so bump both together.
17
+ '@react-native-firebase/app': '^27.1.1',
18
+ '@react-native-firebase/messaging': '^27.1.1',
19
+ 'react-native-notify-kit': '^10.10.0',
20
+ // `add subscriptions`. Pinned to the 10.x line the module was built and run
21
+ // against; 11.0 (Oct 2026) is a major and needs its own pass.
22
+ 'react-native-purchases': '^10.16.0',
23
+ '@gorhom/bottom-sheet': '^5.2.14',
16
24
  };
17
25
  export function pick(...names) {
18
26
  return Object.fromEntries(names.map((name) => [name, VERSIONS[name]]));
@@ -0,0 +1,64 @@
1
+ const { withAndroidManifest, AndroidConfig } = require('expo/config-plugins');
2
+
3
+ /**
4
+ * Writes `com.google.firebase.messaging.default_notification_channel_id` into
5
+ * the Android manifest.
6
+ *
7
+ * Without it, a remote push whose payload carries no `channel_id` lands on a
8
+ * channel Android invents at IMPORTANCE_DEFAULT — which is below the threshold
9
+ * for heads-up, so the notification appears silently in the tray instead of
10
+ * over the screen. Backends often don't send `channel_id`, so the fallback is
11
+ * declared here.
12
+ *
13
+ * The value MUST match `DEFAULT_CHANNEL_ID` in `src/notifications/config.ts`.
14
+ * If the two drift apart, FCM points at a channel the app never creates and
15
+ * every remote notification quietly loses its heads-up treatment — with nothing
16
+ * in the logs to say so.
17
+ *
18
+ * ── Why `tools:replace` is not optional ──────────────────────────────────────
19
+ * `@react-native-firebase/messaging` ships its OWN copy of this meta-data with
20
+ * an EMPTY value. Two manifests declaring the same `meta-data` name with
21
+ * different values is a hard merge conflict, and the build fails at
22
+ * `processDebugMainManifest` rather than picking one:
23
+ *
24
+ * Attribute meta-data#...default_notification_channel_id@value
25
+ * value=(general.v1) is also present at [:react-native-firebase_messaging]
26
+ * value=(). Suggestion: add 'tools:replace="android:value"'.
27
+ *
28
+ * The marker tells the merger this declaration deliberately wins over the
29
+ * library's placeholder, which is exactly the intent.
30
+ */
31
+ const CHANNEL_ID = 'general.v1';
32
+ const META_DATA_NAME = 'com.google.firebase.messaging.default_notification_channel_id';
33
+
34
+ module.exports = function withAndroidDefaultNotificationChannel(config) {
35
+ return withAndroidManifest(config, (cfg) => {
36
+ // Guarantees `xmlns:tools` exists on <manifest>. Without the namespace the
37
+ // `tools:replace` attribute below is not merger syntax, just an unknown
38
+ // attribute the build rejects, with an error that doesn't point here.
39
+ cfg.modResults = AndroidConfig.Manifest.ensureToolsAvailable(cfg.modResults);
40
+
41
+ const application = AndroidConfig.Manifest.getMainApplicationOrThrow(cfg.modResults);
42
+
43
+ application['meta-data'] = application['meta-data'] ?? [];
44
+
45
+ const existing = application['meta-data'].find(
46
+ (item) => item.$?.['android:name'] === META_DATA_NAME,
47
+ );
48
+
49
+ if (existing) {
50
+ existing.$['android:value'] = CHANNEL_ID;
51
+ existing.$['tools:replace'] = 'android:value';
52
+ } else {
53
+ application['meta-data'].push({
54
+ $: {
55
+ 'android:name': META_DATA_NAME,
56
+ 'android:value': CHANNEL_ID,
57
+ 'tools:replace': 'android:value',
58
+ },
59
+ });
60
+ }
61
+
62
+ return cfg;
63
+ });
64
+ };
@@ -0,0 +1,309 @@
1
+ import React, {
2
+ createContext,
3
+ useCallback,
4
+ useContext,
5
+ useEffect,
6
+ useMemo,
7
+ useRef,
8
+ useState,
9
+ } from 'react';
10
+ import { AppState } from 'react-native';
11
+
12
+ import { CLEAR_BADGE_ON_OPEN, DEFAULT_CHANNEL_ID } from './config';
13
+ import { logNotification } from './log';
14
+ import { canOpenRoute, resolveRoute } from './routing';
15
+ import {
16
+ clearBadge,
17
+ displayForegroundNotification,
18
+ getFcmToken,
19
+ getInitialPayload,
20
+ getPermissionState,
21
+ onForegroundMessage,
22
+ onNotificationPress,
23
+ onTokenRefresh,
24
+ openNotificationSettings,
25
+ requestPermission as requestPermissionFromOs,
26
+ } from './service';
27
+ import type { NotificationContextValue, NotificationPermissionState } from './types';
28
+ import { useNotificationSync } from './useNotificationSync';
29
+
30
+ export const NotificationContext = createContext<NotificationContextValue | null>(null);
31
+
32
+ /**
33
+ * How long a route stays deduplicated after being navigated to.
34
+ *
35
+ * Long enough to absorb the same tap arriving down two delivery paths, short
36
+ * enough that a user who genuinely taps two notifications in a row still gets the
37
+ * second one.
38
+ */
39
+ const DUPLICATE_TAP_MS = 2000;
40
+
41
+ interface NotificationProviderProps {
42
+ children: React.ReactNode;
43
+ /** Gates token registration and route delivery. */
44
+ isLoggedIn: boolean;
45
+ /** See `navigation.ts`. Injected so the provider never imports the router. */
46
+ onNavigate: (route: string) => void;
47
+ }
48
+
49
+ /**
50
+ * Owns every notification listener in the app, and the cold-start queue.
51
+ *
52
+ * It deliberately NEVER calls `requestPermission`. It reads permission and
53
+ * exposes a request function, but the only consumer of that function is
54
+ * `useNotificationPermission`, which only a screen deliberately mounts. That
55
+ * is what keeps "never ask on mount, only on a tap" a structural property
56
+ * rather than a convention someone breaks in six months.
57
+ */
58
+ export function NotificationProvider({
59
+ children,
60
+ isLoggedIn,
61
+ onNavigate,
62
+ }: NotificationProviderProps): React.JSX.Element {
63
+ const [permission, setPermission] = useState<NotificationPermissionState>('undetermined');
64
+ const [fcmToken, setFcmToken] = useState<string | null>(null);
65
+ const { registerToken } = useNotificationSync();
66
+
67
+ /**
68
+ * Whether the OS prompt is still reachable.
69
+ *
70
+ * No API reports this, so it is tracked here: once a request comes back
71
+ * denied, the prompt is spent on iOS and the banner has to offer Settings
72
+ * instead. A ref rather than state — it feeds the next permission read rather
73
+ * than the render.
74
+ */
75
+ const canAskAgainRef = useRef(true);
76
+
77
+ /**
78
+ * A route resolved from a notification before the app could navigate.
79
+ *
80
+ * This queue is why cold start works. A tap on a killed app resolves its
81
+ * payload during the first render pass, possibly before the navigator exists.
82
+ * Pushing immediately either throws or lands on an auth-guarded route that
83
+ * bounces the user straight back out.
84
+ */
85
+ const pendingRouteRef = useRef<string | null>(null);
86
+ const [isNavigatorReady, setNavigatorReady] = useState(false);
87
+
88
+ const refreshPermission = useCallback(async () => {
89
+ const next = await getPermissionState(canAskAgainRef.current);
90
+ setPermission((current) => {
91
+ if (current !== next) logNotification('PERMISSION', next);
92
+ return next;
93
+ });
94
+ }, []);
95
+
96
+ const requestPermission = useCallback(async () => {
97
+ const { state, granted } = await requestPermissionFromOs();
98
+ if (!granted) canAskAgainRef.current = false;
99
+ setPermission(state);
100
+ return state;
101
+ }, []);
102
+
103
+ // ── Permission, re-read whenever the app comes back to the front ───────────
104
+ //
105
+ // The user can leave for system settings, flip the switch, and return. Only a
106
+ // fresh read closes that loop — nothing notifies the app that it happened.
107
+ useEffect(() => {
108
+ void refreshPermission();
109
+
110
+ const subscription = AppState.addEventListener('change', (state) => {
111
+ if (state === 'active') void refreshPermission();
112
+ });
113
+
114
+ return () => subscription.remove();
115
+ }, [refreshPermission]);
116
+
117
+ // ── Badge, cleared whenever the app is opened (see CLEAR_BADGE_ON_OPEN) ────
118
+ useEffect(() => {
119
+ if (!CLEAR_BADGE_ON_OPEN) return;
120
+
121
+ void clearBadge();
122
+ const subscription = AppState.addEventListener('change', (state) => {
123
+ if (state === 'active') void clearBadge();
124
+ });
125
+
126
+ return () => subscription.remove();
127
+ }, []);
128
+
129
+ // ── Token, once permission actually allows delivery ───────────────────────
130
+ //
131
+ // Gated on BOTH login and granted permission. A token fetched before the user
132
+ // agrees is one the backend will happily send to and the OS will silently
133
+ // discard, which looks like a broken backend rather than a missing
134
+ // permission.
135
+ useEffect(() => {
136
+ if (!isLoggedIn || permission !== 'granted') return;
137
+
138
+ let cancelled = false;
139
+
140
+ void (async () => {
141
+ const token = await getFcmToken();
142
+ if (cancelled || !token) return;
143
+ setFcmToken(token);
144
+ await registerToken(token);
145
+ })();
146
+
147
+ const unsubscribe = onTokenRefresh((token) => {
148
+ setFcmToken(token);
149
+ void registerToken(token);
150
+ });
151
+
152
+ return () => {
153
+ cancelled = true;
154
+ unsubscribe();
155
+ };
156
+ }, [isLoggedIn, permission, registerToken]);
157
+
158
+ // ── Navigation, deferred until it can actually succeed ────────────────────
159
+
160
+ /**
161
+ * The last route actually navigated to, and when.
162
+ *
163
+ * One tap can now reach the app down two paths — Firebase's
164
+ * `onNotificationOpenedApp` and NotifyKit's background-press queue — and
165
+ * which one carries it depends on who owned the notification natively. Both
166
+ * resolve to the same route, so a tap that arrives twice would push the same
167
+ * screen twice and leave a duplicate on the back stack.
168
+ *
169
+ * Deduplicated on the route rather than a notification id because the id is
170
+ * the one thing the two paths do NOT agree on: Firebase reports the FCM
171
+ * `messageId`, NotifyKit reports its own notification id, and neither is
172
+ * carried in the parsed payload. The window only has to outlast the gap
173
+ * between two deliveries of one tap, which is milliseconds.
174
+ */
175
+ const lastNavigationRef = useRef<{ route: string; at: number } | null>(null);
176
+
177
+ const navigateOnce = useCallback(
178
+ (route: string) => {
179
+ const previous = lastNavigationRef.current;
180
+
181
+ if (previous && previous.route === route && Date.now() - previous.at < DUPLICATE_TAP_MS) {
182
+ logNotification('ROUTE ignored — same route already delivered for this tap', route);
183
+ return;
184
+ }
185
+
186
+ lastNavigationRef.current = { route, at: Date.now() };
187
+ logNotification('ROUTE navigating', route);
188
+ onNavigate(route);
189
+ },
190
+ [onNavigate],
191
+ );
192
+
193
+ const deliverRoute = useCallback(
194
+ (route: string | null) => {
195
+ // Every branch below is logged. A tap that appears to do nothing is the
196
+ // hardest failure here to diagnose, and there are three distinct reasons
197
+ // for it — no route mapped, navigator not ready, route gated — that are
198
+ // indistinguishable from the outside.
199
+ if (!route) {
200
+ logNotification('ROUTE none — opening the app without navigating');
201
+ return;
202
+ }
203
+
204
+ if (!isNavigatorReady) {
205
+ logNotification('ROUTE queued until the navigator is ready', route);
206
+ pendingRouteRef.current = route;
207
+ return;
208
+ }
209
+
210
+ // Silently dropped rather than queued indefinitely: a gated route for a
211
+ // logged-out user is not going to become deliverable during this launch,
212
+ // and holding it would fire it the moment they signed in for an unrelated
213
+ // reason.
214
+ if (!canOpenRoute(route, isLoggedIn)) {
215
+ logNotification('ROUTE dropped — requires sign-in', route);
216
+ return;
217
+ }
218
+
219
+ navigateOnce(route);
220
+ },
221
+ [isLoggedIn, isNavigatorReady, navigateOnce],
222
+ );
223
+
224
+ // The navigator is mounted by the time an effect in a child of the router
225
+ // runs, so a single frame's deferral is enough to make `push` safe.
226
+ useEffect(() => {
227
+ const handle = requestAnimationFrame(() => setNavigatorReady(true));
228
+ return () => cancelAnimationFrame(handle);
229
+ }, []);
230
+
231
+ useEffect(() => {
232
+ if (!isNavigatorReady) return;
233
+
234
+ const queued = pendingRouteRef.current;
235
+ if (!queued) return;
236
+
237
+ pendingRouteRef.current = null;
238
+
239
+ if (!canOpenRoute(queued, isLoggedIn)) {
240
+ logNotification('ROUTE dropped from queue — requires sign-in', queued);
241
+ return;
242
+ }
243
+
244
+ logNotification('ROUTE navigating from queue', queued);
245
+ navigateOnce(queued);
246
+ }, [isLoggedIn, isNavigatorReady, navigateOnce]);
247
+
248
+ // ── Cold start ────────────────────────────────────────────────────────────
249
+ //
250
+ // Guarded by a ref rather than an empty dependency array. `deliverRoute`
251
+ // changes identity as auth and navigator readiness resolve, so an honest
252
+ // dependency list re-runs this several times per launch and re-navigates on
253
+ // each — but silencing the linter to force `[]` costs the whole component its
254
+ // React Compiler optimisation. The ref gets both: real dependencies, and the
255
+ // read happening exactly once.
256
+ const hasHandledColdStartRef = useRef(false);
257
+
258
+ useEffect(() => {
259
+ if (hasHandledColdStartRef.current) return;
260
+ hasHandledColdStartRef.current = true;
261
+
262
+ void (async () => {
263
+ const payload = await getInitialPayload();
264
+ // Safe to run before the navigator exists — `deliverRoute` parks the
265
+ // route in `pendingRouteRef` and the flush effect above delivers it.
266
+ if (payload) deliverRoute(resolveRoute(payload));
267
+ })();
268
+ }, [deliverRoute]);
269
+
270
+ // ── Taps while running ────────────────────────────────────────────────────
271
+ useEffect(
272
+ () => onNotificationPress((payload) => deliverRoute(resolveRoute(payload))),
273
+ [deliverRoute],
274
+ );
275
+
276
+ // ── Foreground messages ───────────────────────────────────────────────────
277
+ //
278
+ // FCM draws nothing in the foreground on either platform, so without this the
279
+ // notification is delivered and invisible.
280
+ useEffect(
281
+ () =>
282
+ onForegroundMessage((title, body, payload) => {
283
+ if (!title && !body) return;
284
+ void displayForegroundNotification(title, body, payload, DEFAULT_CHANNEL_ID);
285
+ }),
286
+ [],
287
+ );
288
+
289
+ const value = useMemo<NotificationContextValue>(
290
+ () => ({
291
+ permission,
292
+ fcmToken,
293
+ refreshPermission,
294
+ requestPermission,
295
+ openSettings: openNotificationSettings,
296
+ }),
297
+ [permission, fcmToken, refreshPermission, requestPermission],
298
+ );
299
+
300
+ return <NotificationContext.Provider value={value}>{children}</NotificationContext.Provider>;
301
+ }
302
+
303
+ export function useNotificationContext(): NotificationContextValue {
304
+ const context = useContext(NotificationContext);
305
+ if (!context) {
306
+ throw new Error('useNotificationContext must be used within <NotificationProvider>');
307
+ }
308
+ return context;
309
+ }
@@ -0,0 +1,21 @@
1
+ import React from 'react';
2
+
3
+ import { useIsLoggedIn } from '@/features/auth';
4
+
5
+ import { navigateFromNotification } from './navigation';
6
+ import { NotificationProvider } from './NotificationProvider';
7
+
8
+ /**
9
+ * `NotificationProvider` wired to this app: the session from the auth feature
10
+ * and the navigator from `navigation.ts`. Rendered once, in `AppProviders`,
11
+ * around the navigation root.
12
+ */
13
+ export function NotificationRoot({ children }: { children: React.ReactNode }): React.JSX.Element {
14
+ const isLoggedIn = useIsLoggedIn();
15
+
16
+ return (
17
+ <NotificationProvider isLoggedIn={isLoggedIn} onNavigate={navigateFromNotification}>
18
+ {children}
19
+ </NotificationProvider>
20
+ );
21
+ }