beeper-inbox-native 0.2.0 → 0.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.
package/README.md CHANGED
@@ -85,11 +85,15 @@ function CustomInbox() {
85
85
  | Field | |
86
86
  | --- | --- |
87
87
  | `items`, `unreadCount` | Inbox contents and unread total |
88
+ | `unreadByKind` | Unread per kind in the provider's `unreadKinds` (e.g. `{ order: 3 }`), each capped at 100 |
88
89
  | `loading`, `refreshing` | First load, and background refresh |
89
90
  | `connectionState`, `errorMessage` | `"idle" \| "loading" \| "live" \| "error"`, and the last error |
91
+ | `transport` | `"realtime"` while a live connection delivers updates, otherwise `"polling"` |
90
92
  | `subscriber` | The subscriber record, once loaded |
91
93
  | `refresh({ silent? })` | Re-fetch now; `silent` skips the loading state |
92
94
  | `markRead(id)`, `markAllRead()` | Mark items read (optimistic) |
95
+ | `hasMore`, `loadingMore`, `loadMore()` | Whether older items exist, and fetch the next page of them |
96
+ | `archive(id)`, `unarchive(id)` | Dismiss an item from the list (optimistic; it also counts as read), or bring it back |
93
97
  | `registerPushToken(token, options)`, `unregisterPushToken(token)` | Manual push device management |
94
98
  | `handleActionPress(item)` | Run an item's action exactly as the built-in button does, including `onActionPress` |
95
99
 
@@ -98,6 +102,49 @@ analytics and your `onActionPress` routing stay consistent with the built-in UI.
98
102
 
99
103
  `useBeeperInbox` throws if it is used outside `BeeperNativeInboxProvider`.
100
104
 
105
+ ## Swipe to dismiss
106
+
107
+ The package does not ship a swipe gesture, so it adds no gesture-library dependency. Wrap
108
+ your rows in the swipeable you already use and call `archive`:
109
+
110
+ ```tsx
111
+ const { archive } = useBeeperInbox();
112
+
113
+ <Swipeable onSwipeableOpen={() => archive(item._id)}>
114
+ <Row item={item} />
115
+ </Swipeable>
116
+ ```
117
+
118
+ Archived items leave the list at once. Pass `archived` to the provider to show them instead,
119
+ for an "Archived" screen, and call `unarchive(id)` there to restore one.
120
+
121
+ ## Tabs and paging
122
+
123
+ `kind` limits the provider to items whose `metadata.kind` matched at send time. Changing it
124
+ re-fetches, so one provider can drive tabs:
125
+
126
+ ```tsx
127
+ const [tab, setTab] = useState<"all" | "order" | "chat">("all");
128
+
129
+ <BeeperNativeInboxProvider {...props} kind={tab === "all" ? undefined : tab}>
130
+ <Tabs value={tab} onChange={setTab} />
131
+ <BeeperInboxList />
132
+ </BeeperNativeInboxProvider>
133
+ ```
134
+
135
+ For per-tab badges, name the kinds in `unreadKinds`. The counts come back with the inbox itself,
136
+ so they add no requests:
137
+
138
+ ```tsx
139
+ <BeeperNativeInboxProvider {...props} kind={tab === "all" ? undefined : tab} unreadKinds={["order", "chat"]}>
140
+ <Tab label="Kòmand" badge={<BeeperInboxBadge kind="order" />} />
141
+ </BeeperNativeInboxProvider>
142
+ ```
143
+
144
+ `BeeperInboxList` loads older pages as it scrolls. In a custom list, call `loadMore()` from
145
+ `onEndReached` and read `hasMore` and `loadingMore`. `pageSize` (1–100, default 100) sets
146
+ items per request. `unreadCount` is always the whole inbox's count.
147
+
101
148
  ## Push tokens
102
149
 
103
150
  Use a native FCM token for both Android and iOS with the current Beeper push
package/dist/index.d.ts CHANGED
@@ -2,15 +2,28 @@ import * as react_jsx_runtime from 'react/jsx-runtime';
2
2
  import { StyleProp, ViewStyle, TextStyle } from 'react-native';
3
3
  import { ReactNode } from 'react';
4
4
  import { SubscriberRecord, InboxItemRecord, PushPlatform } from 'beeper-sdk';
5
+ export { InboxItemGroup, groupInboxItems } from 'beeper-sdk';
5
6
 
6
7
  type InboxConnectionState = "idle" | "loading" | "live" | "error";
8
+ /**
9
+ * How updates arrive: pushed over a realtime subscription, or fetched on a
10
+ * timer. Starts as "polling" and switches once a subscription delivers.
11
+ */
12
+ type InboxTransport = "polling" | "realtime";
7
13
  interface BeeperInboxCoreState {
8
14
  subscriber: SubscriberRecord | null;
9
15
  items: InboxItemRecord[];
10
16
  unreadCount: number;
17
+ /** Unread per kind named in `unreadKinds`, each capped at 100. Empty otherwise. */
18
+ unreadByKind: Record<string, number>;
11
19
  loading: boolean;
12
20
  refreshing: boolean;
21
+ /** An older page is being fetched by `loadMore()`. */
22
+ loadingMore: boolean;
23
+ /** Older items exist beyond `items`; call `loadMore()` to fetch them. */
24
+ hasMore: boolean;
13
25
  connectionState: InboxConnectionState;
26
+ transport: InboxTransport;
14
27
  errorMessage: string | null;
15
28
  }
16
29
  interface RegisterPushTokenOptions {
@@ -59,7 +72,28 @@ interface BeeperNativeInboxProviderProps {
59
72
  refreshSessionToken?: () => Promise<string>;
60
73
  subscriber: BeeperNativeSubscriber;
61
74
  push?: BeeperNativePushRegistration;
75
+ /**
76
+ * Receive updates over a live connection instead of polling, when the project
77
+ * offers one. Polling (`pollIntervalMs`) resumes if the connection fails.
78
+ * `state.transport` says which is active. Default true.
79
+ */
80
+ realtime?: boolean;
81
+ /** Polling interval when realtime is off or unavailable. Default 15s, minimum 5s. */
62
82
  pollIntervalMs?: number;
83
+ /**
84
+ * Only show items whose `kind` (from `metadata.kind` at send time) is one of
85
+ * these, e.g. `"order"` for an orders tab. Changing it re-fetches.
86
+ */
87
+ kind?: string | string[];
88
+ /** Items per request, 1-100. Default 100. */
89
+ pageSize?: number;
90
+ /** Show archived items instead of active ones, e.g. for an "Archived" screen. */
91
+ archived?: boolean;
92
+ /**
93
+ * Keep `unreadByKind` for these kinds, for per-tab badges. Fetched with the
94
+ * inbox itself, so it adds no requests. Up to 10.
95
+ */
96
+ unreadKinds?: string[];
63
97
  accentColor?: string;
64
98
  /**
65
99
  * Intercepts an inbox item's action press. Return `false` to skip the default
@@ -85,6 +119,15 @@ interface BeeperNativeInbox extends BeeperInboxCoreState {
85
119
  }) => Promise<void>;
86
120
  markRead: (inboxItemId: string) => Promise<void>;
87
121
  markAllRead: () => Promise<void>;
122
+ /** Appends the next older page. No-op when `hasMore` is false. */
123
+ loadMore: () => Promise<void>;
124
+ /**
125
+ * Archives an item, e.g. from a swipe-to-dismiss row. It leaves the list at
126
+ * once, counts as read, and comes back if the request fails.
127
+ */
128
+ archive: (inboxItemId: string) => Promise<void>;
129
+ /** Returns an archived item to the active inbox. */
130
+ unarchive: (inboxItemId: string) => Promise<void>;
88
131
  registerPushToken: (token: string, options: RegisterPushTokenOptions) => Promise<void>;
89
132
  unregisterPushToken: (token: string) => Promise<void>;
90
133
  /**
@@ -94,7 +137,7 @@ interface BeeperNativeInbox extends BeeperInboxCoreState {
94
137
  */
95
138
  handleActionPress: (item: InboxItemRecord) => Promise<void>;
96
139
  }
97
- declare function BeeperNativeInboxProvider({ baseUrl, projectId, publishableKey, sessionToken, refreshSessionToken, subscriber, push, pollIntervalMs, accentColor, onActionPress, children, }: BeeperNativeInboxProviderProps): react_jsx_runtime.JSX.Element;
140
+ declare function BeeperNativeInboxProvider({ baseUrl, projectId, publishableKey, sessionToken, refreshSessionToken, subscriber, push, realtime, pollIntervalMs, kind, pageSize, archived, unreadKinds, accentColor, onActionPress, children, }: BeeperNativeInboxProviderProps): react_jsx_runtime.JSX.Element;
98
141
  /**
99
142
  * Live inbox state and actions, for building your own UI or showing the unread
100
143
  * count elsewhere (a tab bar badge, say). Must be used inside
@@ -105,7 +148,9 @@ declare function BeeperNativeInboxProvider({ baseUrl, projectId, publishableKey,
105
148
  * ```
106
149
  */
107
150
  declare function useBeeperInbox(): BeeperNativeInbox;
108
- declare function BeeperInboxBadge({ onPress, style, textStyle, }: {
151
+ declare function BeeperInboxBadge({ kind, onPress, style, textStyle, }: {
152
+ /** Count only this kind. It must be in the provider's `unreadKinds`. */
153
+ kind?: string;
109
154
  onPress?: () => void;
110
155
  style?: StyleProp<ViewStyle>;
111
156
  textStyle?: StyleProp<TextStyle>;
package/dist/index.js CHANGED
@@ -1,24 +1,58 @@
1
- import { StyleSheet, View, Text, Pressable, ActivityIndicator, FlatList, Linking } from 'react-native';
1
+ import { StyleSheet, View, Text, Pressable, Image, ActivityIndicator, FlatList, Linking } from 'react-native';
2
2
  import { createContext, useMemo, useSyncExternalStore, useEffect, useRef, useContext } from 'react';
3
+ import { ConvexClient } from 'convex/browser';
3
4
  import { BeeperApiError } from 'beeper-sdk';
5
+ export { groupInboxItems } from 'beeper-sdk';
4
6
  import { BeeperWidgetClient } from 'beeper-sdk/widget';
5
7
  import { jsx, jsxs } from 'react/jsx-runtime';
6
8
 
7
9
  // src/index.tsx
10
+ function createConvexRealtimeClient(convexUrl) {
11
+ const client = new ConvexClient(convexUrl);
12
+ return {
13
+ onUpdate(query, args, onResult, onError) {
14
+ const unsubscribe = client.onUpdate(query, args, onResult, onError);
15
+ return () => unsubscribe();
16
+ },
17
+ close: () => client.close()
18
+ };
19
+ }
8
20
  var DEFAULT_POLL_INTERVAL_MS = 15e3;
21
+ var DEFAULT_PAGE_SIZE = 100;
22
+ var REALTIME_RETRY_MS = 6e4;
9
23
  var BeeperInboxCore = class {
10
24
  client;
11
25
  subscriberId;
12
26
  refreshSessionToken;
13
27
  pollIntervalMs;
28
+ kind;
29
+ pageSize;
30
+ archivedView;
31
+ unreadKinds;
32
+ realtimeEnabled;
33
+ createRealtimeClient;
34
+ realtimeClient = null;
35
+ realtimeUnsubscribe = null;
36
+ realtimeRetryTimer = null;
37
+ /** True while a subscription is delivering; polling is off meanwhile. */
38
+ realtimeLive = false;
39
+ /** Where the next `loadMore()` starts. */
40
+ cursor = null;
41
+ /** Set once `loadMore()` has appended a page that refreshes must keep. */
42
+ hasOlderPages = false;
43
+ loadMoreRequest = null;
14
44
  listeners = /* @__PURE__ */ new Set();
15
45
  state = {
16
46
  subscriber: null,
17
47
  items: [],
18
48
  unreadCount: 0,
49
+ unreadByKind: {},
19
50
  loading: false,
20
51
  refreshing: false,
52
+ loadingMore: false,
53
+ hasMore: false,
21
54
  connectionState: "idle",
55
+ transport: "polling",
22
56
  errorMessage: null
23
57
  };
24
58
  pollTimer = null;
@@ -32,6 +66,12 @@ var BeeperInboxCore = class {
32
66
  this.subscriberId = options.subscriberId;
33
67
  this.refreshSessionToken = options.refreshSessionToken;
34
68
  this.pollIntervalMs = Math.max(5e3, options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS);
69
+ this.kind = options.kind;
70
+ this.archivedView = options.archived === true;
71
+ this.unreadKinds = options.unreadKinds?.length ? options.unreadKinds : void 0;
72
+ this.realtimeEnabled = options.realtime !== false;
73
+ this.createRealtimeClient = options.createRealtimeClient ?? createConvexRealtimeClient;
74
+ this.pageSize = Math.min(Math.max(Math.round(options.pageSize ?? DEFAULT_PAGE_SIZE), 1), 100);
35
75
  }
36
76
  getState() {
37
77
  return this.state;
@@ -47,10 +87,14 @@ var BeeperInboxCore = class {
47
87
  }
48
88
  this.started = true;
49
89
  await this.refresh();
90
+ if (this.realtimeEnabled) {
91
+ void this.connectRealtime();
92
+ }
50
93
  }
51
94
  stop() {
52
95
  this.started = false;
53
96
  this.clearPollTimer();
97
+ this.disconnectRealtime();
54
98
  }
55
99
  async refresh(options = {}) {
56
100
  if (this.request) {
@@ -62,14 +106,13 @@ var BeeperInboxCore = class {
62
106
  errorMessage: null
63
107
  });
64
108
  this.request = this.requestWithSessionRetry(async () => {
65
- const result = await this.client.getInbox(this.subscriberId, 100);
66
- this.update({
67
- subscriber: result.subscriber,
68
- items: result.items,
69
- unreadCount: result.unreadCount,
70
- connectionState: "live",
71
- errorMessage: null
109
+ const result = await this.client.getInbox(this.subscriberId, {
110
+ limit: this.pageSize,
111
+ kind: this.kind,
112
+ archived: this.archivedView,
113
+ unreadKinds: this.unreadKinds
72
114
  });
115
+ this.applyFirstPage(result);
73
116
  }).catch((error) => {
74
117
  this.update({
75
118
  connectionState: "error",
@@ -83,16 +126,75 @@ var BeeperInboxCore = class {
83
126
  });
84
127
  return this.request;
85
128
  }
129
+ /**
130
+ * Applies a fresh newest page, from a fetch or a subscription push. Once older
131
+ * pages are loaded, they stay below it rather than dropping the user's scroll
132
+ * position, and the cursor, which already points past them, is kept.
133
+ */
134
+ applyFirstPage(result) {
135
+ let items = result.items;
136
+ if (this.hasOlderPages) {
137
+ items = mergeOlder(result.items, this.state.items);
138
+ } else {
139
+ this.cursor = result.nextCursor ?? null;
140
+ }
141
+ this.update({
142
+ subscriber: result.subscriber,
143
+ items,
144
+ unreadCount: result.unreadCount,
145
+ unreadByKind: result.unreadByKind ?? {},
146
+ hasMore: this.cursor !== null,
147
+ connectionState: "live",
148
+ errorMessage: null
149
+ });
150
+ }
151
+ /**
152
+ * Appends the next older page. No-op while one is in flight or when
153
+ * `hasMore` is false.
154
+ */
155
+ async loadMore() {
156
+ if (this.loadMoreRequest) {
157
+ return this.loadMoreRequest;
158
+ }
159
+ const cursor = this.cursor;
160
+ if (!cursor) {
161
+ return;
162
+ }
163
+ this.update({ loadingMore: true });
164
+ this.loadMoreRequest = this.requestWithSessionRetry(async () => {
165
+ const result = await this.client.getInbox(this.subscriberId, {
166
+ limit: this.pageSize,
167
+ cursor,
168
+ kind: this.kind,
169
+ archived: this.archivedView,
170
+ unreadKinds: this.unreadKinds
171
+ });
172
+ const seen = new Set(this.state.items.map((item) => item._id));
173
+ this.cursor = result.nextCursor ?? null;
174
+ this.hasOlderPages = true;
175
+ this.update({
176
+ items: [...this.state.items, ...result.items.filter((item) => !seen.has(item._id))],
177
+ unreadCount: result.unreadCount,
178
+ unreadByKind: result.unreadByKind ?? {},
179
+ hasMore: this.cursor !== null
180
+ });
181
+ }).finally(() => {
182
+ this.loadMoreRequest = null;
183
+ this.update({ loadingMore: false });
184
+ });
185
+ return this.loadMoreRequest;
186
+ }
86
187
  async markRead(inboxItemId) {
87
188
  const previous = this.state;
88
189
  const now = Date.now();
190
+ const target = this.state.items.find((item) => item._id === inboxItemId && !item.readAt);
89
191
  this.update({
90
192
  items: this.state.items.map((item) => item._id === inboxItemId ? { ...item, readAt: item.readAt ?? now } : item),
91
- unreadCount: Math.max(0, this.state.unreadCount - (this.state.items.some((item) => item._id === inboxItemId && !item.readAt) ? 1 : 0))
193
+ ...this.unreadAfterReading(target)
92
194
  });
93
195
  try {
94
196
  await this.requestWithSessionRetry(() => this.client.markRead(this.subscriberId, [inboxItemId]));
95
- await this.refresh({ silent: true });
197
+ await this.refreshAfterWrite();
96
198
  } catch (error) {
97
199
  this.state = previous;
98
200
  this.emit();
@@ -103,11 +205,41 @@ var BeeperInboxCore = class {
103
205
  const previous = this.state;
104
206
  this.update({
105
207
  items: this.state.items.map((item) => ({ ...item, readAt: item.readAt ?? Date.now() })),
106
- unreadCount: 0
208
+ unreadCount: 0,
209
+ unreadByKind: Object.fromEntries(Object.keys(this.state.unreadByKind).map((kind) => [kind, 0]))
107
210
  });
108
211
  try {
109
212
  await this.requestWithSessionRetry(() => this.client.markAllRead(this.subscriberId));
110
- await this.refresh({ silent: true });
213
+ await this.refreshAfterWrite();
214
+ } catch (error) {
215
+ this.state = previous;
216
+ this.emit();
217
+ throw error;
218
+ }
219
+ }
220
+ /**
221
+ * Archives an item (e.g. swipe to dismiss). It leaves the list at once and
222
+ * counts as read; restored if the request fails.
223
+ */
224
+ async archive(inboxItemId) {
225
+ return this.setArchived(inboxItemId, true);
226
+ }
227
+ /** Returns an archived item to the active inbox. */
228
+ async unarchive(inboxItemId) {
229
+ return this.setArchived(inboxItemId, false);
230
+ }
231
+ async setArchived(inboxItemId, archived) {
232
+ const previous = this.state;
233
+ const target = this.state.items.find((item) => item._id === inboxItemId);
234
+ const leavesView = archived !== this.archivedView;
235
+ this.update({
236
+ items: leavesView ? this.state.items.filter((item) => item._id !== inboxItemId) : this.state.items,
237
+ // Archiving marks the item read on the server.
238
+ ...archived ? this.unreadAfterReading(target?.readAt ? void 0 : target) : {}
239
+ });
240
+ try {
241
+ await this.requestWithSessionRetry(() => archived ? this.client.archive(this.subscriberId, [inboxItemId]) : this.client.unarchive(this.subscriberId, [inboxItemId]));
242
+ await this.refreshAfterWrite();
111
243
  } catch (error) {
112
244
  this.state = previous;
113
245
  this.emit();
@@ -143,6 +275,17 @@ var BeeperInboxCore = class {
143
275
  actionLabel
144
276
  }));
145
277
  }
278
+ /** Unread counters after `item` (if unread and known) becomes read. */
279
+ unreadAfterReading(item) {
280
+ if (!item || item.readAt) {
281
+ return {};
282
+ }
283
+ const unreadByKind = { ...this.state.unreadByKind };
284
+ if (item.kind && item.kind in unreadByKind) {
285
+ unreadByKind[item.kind] = Math.max(0, (unreadByKind[item.kind] ?? 0) - 1);
286
+ }
287
+ return { unreadCount: Math.max(0, this.state.unreadCount - 1), unreadByKind };
288
+ }
146
289
  async requestWithSessionRetry(request) {
147
290
  try {
148
291
  return await request();
@@ -164,8 +307,108 @@ var BeeperInboxCore = class {
164
307
  listener(this.state);
165
308
  }
166
309
  }
310
+ /** A live subscription pushes the write's result, so only a poller re-fetches. */
311
+ async refreshAfterWrite() {
312
+ if (!this.realtimeLive) {
313
+ await this.refresh({ silent: true });
314
+ }
315
+ }
316
+ realtimeArgs() {
317
+ const kinds = this.kind === void 0 ? [] : [this.kind].flat();
318
+ return {
319
+ projectId: this.client.getProjectId(),
320
+ sessionToken: this.client.getSessionToken(),
321
+ subscriberId: this.subscriberId,
322
+ limit: this.pageSize,
323
+ ...kinds.length ? { kinds } : {},
324
+ ...this.archivedView ? { archived: true } : {},
325
+ ...this.unreadKinds ? { unreadKinds: this.unreadKinds } : {}
326
+ };
327
+ }
328
+ async connectRealtime() {
329
+ let convexUrl;
330
+ try {
331
+ convexUrl = (await this.client.getConfig()).convexUrl;
332
+ } catch {
333
+ this.scheduleRealtimeRetry();
334
+ return;
335
+ }
336
+ if (!convexUrl || !this.started) {
337
+ return;
338
+ }
339
+ try {
340
+ this.realtimeClient ??= this.createRealtimeClient(convexUrl);
341
+ } catch {
342
+ return;
343
+ }
344
+ this.subscribeRealtime(false);
345
+ }
346
+ subscribeRealtime(afterSessionRefresh) {
347
+ if (!this.started || !this.realtimeClient) {
348
+ return;
349
+ }
350
+ this.realtimeUnsubscribe?.();
351
+ this.realtimeUnsubscribe = this.realtimeClient.onUpdate("widgetInbox:list", this.realtimeArgs(), (result) => {
352
+ if (!this.started) {
353
+ return;
354
+ }
355
+ this.realtimeLive = true;
356
+ this.clearPollTimer();
357
+ this.update({ transport: "realtime" });
358
+ this.applyFirstPage(result);
359
+ }, (error) => {
360
+ void this.handleRealtimeError(error, afterSessionRefresh);
361
+ });
362
+ }
363
+ async handleRealtimeError(error, afterSessionRefresh) {
364
+ if (!this.started) {
365
+ return;
366
+ }
367
+ if (!afterSessionRefresh && this.refreshSessionToken && /session|token|expired|invalid/i.test(error.message)) {
368
+ try {
369
+ this.client.updateSessionToken(await this.refreshSessionToken());
370
+ this.subscribeRealtime(true);
371
+ return;
372
+ } catch {
373
+ }
374
+ }
375
+ this.realtimeUnsubscribe?.();
376
+ this.realtimeUnsubscribe = null;
377
+ this.realtimeLive = false;
378
+ this.update({ transport: "polling" });
379
+ this.schedulePoll();
380
+ this.scheduleRealtimeRetry();
381
+ }
382
+ scheduleRealtimeRetry() {
383
+ if (!this.started || this.realtimeRetryTimer) {
384
+ return;
385
+ }
386
+ this.realtimeRetryTimer = setTimeout(() => {
387
+ this.realtimeRetryTimer = null;
388
+ if (this.realtimeClient) {
389
+ this.subscribeRealtime(false);
390
+ } else {
391
+ void this.connectRealtime();
392
+ }
393
+ }, REALTIME_RETRY_MS);
394
+ }
395
+ disconnectRealtime() {
396
+ if (this.realtimeRetryTimer) {
397
+ clearTimeout(this.realtimeRetryTimer);
398
+ this.realtimeRetryTimer = null;
399
+ }
400
+ this.realtimeUnsubscribe?.();
401
+ this.realtimeUnsubscribe = null;
402
+ const client = this.realtimeClient;
403
+ this.realtimeClient = null;
404
+ this.realtimeLive = false;
405
+ if (client) {
406
+ void Promise.resolve(client.close()).catch(() => void 0);
407
+ }
408
+ this.update({ transport: "polling" });
409
+ }
167
410
  schedulePoll() {
168
- if (!this.started || this.pollTimer) {
411
+ if (!this.started || this.pollTimer || this.realtimeLive) {
169
412
  return;
170
413
  }
171
414
  this.pollTimer = setTimeout(() => {
@@ -180,6 +423,15 @@ var BeeperInboxCore = class {
180
423
  }
181
424
  }
182
425
  };
426
+ function mergeOlder(head, previous) {
427
+ const last = head[head.length - 1];
428
+ if (!last) {
429
+ return previous;
430
+ }
431
+ const headIds = new Set(head.map((item) => item._id));
432
+ const tail = previous.filter((item) => !headIds.has(item._id) && item.createdAt <= last.createdAt);
433
+ return [...head, ...tail];
434
+ }
183
435
 
184
436
  // src/actionPress.ts
185
437
  async function runActionPress(input) {
@@ -210,7 +462,12 @@ function BeeperNativeInboxProvider({
210
462
  refreshSessionToken,
211
463
  subscriber,
212
464
  push,
465
+ realtime,
213
466
  pollIntervalMs,
467
+ kind,
468
+ pageSize,
469
+ archived,
470
+ unreadKinds,
214
471
  accentColor = "#f97316",
215
472
  onActionPress,
216
473
  children
@@ -224,14 +481,31 @@ function BeeperNativeInboxProvider({
224
481
  }),
225
482
  [baseUrl, projectId, publishableKey, sessionToken]
226
483
  );
484
+ const kindKey = kind === void 0 ? "" : JSON.stringify([kind].flat());
485
+ const unreadKindsKey = unreadKinds?.length ? JSON.stringify(unreadKinds) : "";
227
486
  const core = useMemo(
228
487
  () => new BeeperInboxCore({
229
488
  client,
230
489
  subscriberId: subscriber.subscriberId,
231
490
  refreshSessionToken,
232
- pollIntervalMs
491
+ pollIntervalMs,
492
+ kind: kindKey ? JSON.parse(kindKey) : void 0,
493
+ pageSize,
494
+ archived,
495
+ unreadKinds: unreadKindsKey ? JSON.parse(unreadKindsKey) : void 0,
496
+ realtime
233
497
  }),
234
- [client, pollIntervalMs, refreshSessionToken, subscriber.subscriberId]
498
+ [
499
+ archived,
500
+ realtime,
501
+ client,
502
+ kindKey,
503
+ unreadKindsKey,
504
+ pageSize,
505
+ pollIntervalMs,
506
+ refreshSessionToken,
507
+ subscriber.subscriberId
508
+ ]
235
509
  );
236
510
  const state = useSyncExternalStore(
237
511
  (listener) => core.subscribe(listener),
@@ -272,6 +546,15 @@ function BeeperNativeInboxProvider({
272
546
  markAllRead: async () => {
273
547
  await core.markAllRead();
274
548
  },
549
+ loadMore: async () => {
550
+ await core.loadMore();
551
+ },
552
+ archive: async (inboxItemId) => {
553
+ await core.archive(inboxItemId);
554
+ },
555
+ unarchive: async (inboxItemId) => {
556
+ await core.unarchive(inboxItemId);
557
+ },
275
558
  registerPushToken: async (token, options) => {
276
559
  await core.registerPushToken(token, options);
277
560
  },
@@ -308,39 +591,48 @@ function useBeeperInbox() {
308
591
  return { ...context.state, ...context.actions };
309
592
  }
310
593
  function BeeperInboxBadge({
594
+ kind,
311
595
  onPress,
312
596
  style,
313
597
  textStyle
314
598
  }) {
315
599
  const { state, accentColor } = useNativeInbox();
316
- const content = /* @__PURE__ */ jsx(View, { style: [styles.badge, { backgroundColor: accentColor }, style], children: /* @__PURE__ */ jsx(Text, { style: [styles.badgeText, textStyle], children: state.unreadCount > 99 ? "99+" : state.unreadCount }) });
600
+ const count = kind === void 0 ? state.unreadCount : state.unreadByKind[kind] ?? 0;
601
+ const content = /* @__PURE__ */ jsx(View, { style: [styles.badge, { backgroundColor: accentColor }, style], children: /* @__PURE__ */ jsx(Text, { style: [styles.badgeText, textStyle], children: count > 99 ? "99+" : count }) });
317
602
  return onPress ? /* @__PURE__ */ jsx(Pressable, { accessibilityRole: "button", onPress, children: content }) : content;
318
603
  }
319
604
  function BeeperInboxItem({ item }) {
320
605
  const { core, accentColor, actions } = useNativeInbox();
321
- return /* @__PURE__ */ jsxs(View, { style: styles.item, children: [
322
- /* @__PURE__ */ jsx(Text, { style: styles.itemTitle, children: item.title ?? "Notification" }),
323
- /* @__PURE__ */ jsx(Text, { style: styles.itemBody, children: item.body }),
324
- /* @__PURE__ */ jsxs(View, { style: styles.itemFooter, children: [
325
- /* @__PURE__ */ jsx(Text, { style: styles.itemDate, children: new Date(item.createdAt).toLocaleString() }),
326
- !item.readAt ? /* @__PURE__ */ jsx(
327
- Pressable,
328
- {
329
- accessibilityRole: "button",
330
- accessibilityLabel: "Mark notification as read",
331
- onPress: () => void core.markRead(item._id),
332
- children: /* @__PURE__ */ jsx(Text, { style: [styles.actionText, { color: accentColor }], children: "Mark read" })
333
- }
334
- ) : null,
335
- item.actionUrl ? /* @__PURE__ */ jsx(Pressable, { accessibilityRole: "button", onPress: () => void actions.handleActionPress(item), children: /* @__PURE__ */ jsx(Text, { style: [styles.actionText, { color: accentColor }], children: item.actionLabel ?? "Open" }) }) : null
606
+ return (
607
+ // A resolved item was handled by the sender (e.g. the order was accepted).
608
+ /* @__PURE__ */ jsxs(View, { style: [styles.item, item.resolvedAt ? styles.itemResolved : null], children: [
609
+ /* @__PURE__ */ jsxs(View, { style: styles.itemHeader, children: [
610
+ item.avatarUrl ? /* @__PURE__ */ jsx(Image, { source: { uri: item.avatarUrl }, style: styles.itemAvatar, accessibilityIgnoresInvertColors: true }) : null,
611
+ /* @__PURE__ */ jsx(Text, { style: [styles.itemTitle, styles.itemHeaderTitle], children: item.title ?? "Notification" })
612
+ ] }),
613
+ /* @__PURE__ */ jsx(Text, { style: styles.itemBody, children: item.body }),
614
+ item.imageUrl ? /* @__PURE__ */ jsx(Image, { source: { uri: item.imageUrl }, style: styles.itemImage, accessibilityIgnoresInvertColors: true }) : null,
615
+ /* @__PURE__ */ jsxs(View, { style: styles.itemFooter, children: [
616
+ /* @__PURE__ */ jsx(Text, { style: styles.itemDate, children: new Date(item.createdAt).toLocaleString() }),
617
+ !item.readAt ? /* @__PURE__ */ jsx(
618
+ Pressable,
619
+ {
620
+ accessibilityRole: "button",
621
+ accessibilityLabel: "Mark notification as read",
622
+ onPress: () => void core.markRead(item._id),
623
+ children: /* @__PURE__ */ jsx(Text, { style: [styles.actionText, { color: accentColor }], children: "Mark read" })
624
+ }
625
+ ) : null,
626
+ item.actionUrl ? /* @__PURE__ */ jsx(Pressable, { accessibilityRole: "button", onPress: () => void actions.handleActionPress(item), children: /* @__PURE__ */ jsx(Text, { style: [styles.actionText, { color: accentColor }], children: item.actionLabel ?? "Open" }) }) : null
627
+ ] })
336
628
  ] })
337
- ] });
629
+ );
338
630
  }
339
631
  function BeeperInboxList({
340
632
  style,
341
633
  contentContainerStyle
342
634
  }) {
343
- const { state } = useNativeInbox();
635
+ const { core, state } = useNativeInbox();
344
636
  if (state.loading && state.items.length === 0) {
345
637
  return /* @__PURE__ */ jsx(ActivityIndicator, { accessibilityLabel: "Loading notifications", style: styles.loader });
346
638
  }
@@ -359,7 +651,14 @@ function BeeperInboxList({
359
651
  keyExtractor: (item) => item._id,
360
652
  renderItem,
361
653
  style,
362
- contentContainerStyle
654
+ contentContainerStyle,
655
+ onEndReached: () => {
656
+ if (state.hasMore) {
657
+ void core.loadMore().catch(() => void 0);
658
+ }
659
+ },
660
+ onEndReachedThreshold: 0.5,
661
+ ListFooterComponent: state.loadingMore ? /* @__PURE__ */ jsx(ActivityIndicator, { accessibilityLabel: "Loading more notifications", style: styles.loader }) : null
363
662
  }
364
663
  );
365
664
  }
@@ -404,7 +703,12 @@ var styles = StyleSheet.create({
404
703
  subtitle: { color: "#7d685d", fontSize: 13, marginTop: 2 },
405
704
  listContent: { gap: 8 },
406
705
  item: { backgroundColor: "#fffdf9", borderColor: "#eadbcc", borderRadius: 10, borderWidth: 1, padding: 14 },
706
+ itemResolved: { opacity: 0.65 },
407
707
  itemTitle: { color: "#2b221d", fontSize: 15, fontWeight: "700", marginBottom: 5 },
708
+ itemHeader: { alignItems: "center", flexDirection: "row", gap: 10 },
709
+ itemHeaderTitle: { flexShrink: 1 },
710
+ itemAvatar: { backgroundColor: "#eadbcc", borderRadius: 16, height: 32, marginBottom: 5, width: 32 },
711
+ itemImage: { aspectRatio: 16 / 9, backgroundColor: "#eadbcc", borderRadius: 8, marginTop: 10, width: "100%" },
408
712
  itemBody: { color: "#4e3c34", fontSize: 14, lineHeight: 21 },
409
713
  itemFooter: { alignItems: "center", flexDirection: "row", flexWrap: "wrap", gap: 12, marginTop: 10 },
410
714
  itemDate: { color: "#7d685d", flex: 1, fontSize: 12 },
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../../inbox-core/src/index.ts","../src/actionPress.ts","../src/index.tsx"],"names":[],"mappings":";;;;;;;AAmCA,IAAM,wBAAA,GAA2B,I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E,KAAA,EAAO,WAAW,OAAA,EAAS,EAAA,EAAI,WAAW,QAAA,EAAS;AAAA,EAC5D,OAAO,EAAE,KAAA,EAAO,WAAW,OAAA,EAAS,EAAA,EAAI,WAAW,QAAA;AACrD,CAAC,CAAA","file":"index.js","sourcesContent":["import { BeeperApiError } from \"beeper-sdk\";\nimport type {\n InboxItemRecord,\n PushPlatform,\n SubscriberRecord,\n} from \"beeper-sdk\";\nimport type { BeeperWidgetClient } from \"beeper-sdk/widget\";\n\nexport type InboxConnectionState = \"idle\" | \"loading\" | \"live\" | \"error\";\n\nexport interface BeeperInboxCoreState {\n subscriber: SubscriberRecord | null;\n items: InboxItemRecord[];\n unreadCount: number;\n loading: boolean;\n refreshing: boolean;\n connectionState: InboxConnectionState;\n errorMessage: string | null;\n}\n\nexport interface BeeperInboxCoreOptions {\n client: BeeperWidgetClient;\n subscriberId: string;\n refreshSessionToken?: () => Promise<string>;\n pollIntervalMs?: number;\n}\n\nexport interface RegisterPushTokenOptions {\n platform: PushPlatform;\n deviceLabel?: string;\n metadata?: Record<string, unknown>;\n}\n\nexport type BeeperInboxCoreListener = (state: BeeperInboxCoreState) => void;\n\nconst DEFAULT_POLL_INTERVAL_MS = 15_000;\n\nexport class BeeperInboxCore {\n private readonly client: BeeperWidgetClient;\n private readonly subscriberId: string;\n private readonly refreshSessionToken?: () => Promise<string>;\n private readonly pollIntervalMs: number;\n private readonly listeners = new Set<BeeperInboxCoreListener>();\n private state: BeeperInboxCoreState = {\n subscriber: null,\n items: [],\n unreadCount: 0,\n loading: false,\n refreshing: false,\n connectionState: \"idle\",\n errorMessage: null,\n };\n private pollTimer: ReturnType<typeof setTimeout> | null = null;\n private started = false;\n private request: Promise<void> | null = null;\n\n constructor(options: BeeperInboxCoreOptions) {\n if (!options.subscriberId.trim()) {\n throw new Error(\"A subscriberId is required\");\n }\n this.client = options.client;\n this.subscriberId = options.subscriberId;\n this.refreshSessionToken = options.refreshSessionToken;\n this.pollIntervalMs = Math.max(5_000, options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS);\n }\n\n getState() {\n return this.state;\n }\n\n subscribe(listener: BeeperInboxCoreListener) {\n this.listeners.add(listener);\n listener(this.state);\n return () => this.listeners.delete(listener);\n }\n\n async start() {\n if (this.started) {\n return;\n }\n this.started = true;\n await this.refresh();\n }\n\n stop() {\n this.started = false;\n this.clearPollTimer();\n }\n\n async refresh(options: { silent?: boolean } = {}) {\n if (this.request) {\n return this.request;\n }\n\n this.update({\n ...(options.silent ? { refreshing: true } : { loading: true }),\n connectionState: options.silent ? this.state.connectionState : \"loading\",\n errorMessage: null,\n });\n\n this.request = this.requestWithSessionRetry(async () => {\n const result = await this.client.getInbox(this.subscriberId, 100);\n this.update({\n subscriber: result.subscriber,\n items: result.items,\n unreadCount: result.unreadCount,\n connectionState: \"live\",\n errorMessage: null,\n });\n })\n .catch((error: unknown) => {\n this.update({\n connectionState: \"error\",\n errorMessage: error instanceof Error ? error.message : \"Inbox request failed\",\n });\n throw error;\n })\n .finally(() => {\n this.request = null;\n this.update({ loading: false, refreshing: false });\n this.schedulePoll();\n });\n\n return this.request;\n }\n\n async markRead(inboxItemId: string) {\n const previous = this.state;\n const now = Date.now();\n this.update({\n items: this.state.items.map((item) =>\n item._id === inboxItemId ? { ...item, readAt: item.readAt ?? now } : item,\n ),\n unreadCount: Math.max(\n 0,\n this.state.unreadCount -\n (this.state.items.some((item) => item._id === inboxItemId && !item.readAt) ? 1 : 0),\n ),\n });\n\n try {\n await this.requestWithSessionRetry(() =>\n this.client.markRead(this.subscriberId, [inboxItemId]),\n );\n await this.refresh({ silent: true });\n } catch (error) {\n this.state = previous;\n this.emit();\n throw error;\n }\n }\n\n async markAllRead() {\n const previous = this.state;\n this.update({\n items: this.state.items.map((item) => ({ ...item, readAt: item.readAt ?? Date.now() })),\n unreadCount: 0,\n });\n\n try {\n await this.requestWithSessionRetry(() => this.client.markAllRead(this.subscriberId));\n await this.refresh({ silent: true });\n } catch (error) {\n this.state = previous;\n this.emit();\n throw error;\n }\n }\n\n async registerPushToken(token: string, options: RegisterPushTokenOptions) {\n const normalizedToken = token.trim();\n if (!normalizedToken) {\n throw new Error(\"A push token is required\");\n }\n await this.requestWithSessionRetry(() =>\n this.client.registerPushDevice({\n subscriberId: this.subscriberId,\n pushToken: normalizedToken,\n ...options,\n }),\n );\n }\n\n async unregisterPushToken(token: string) {\n const normalizedToken = token.trim();\n if (!normalizedToken) {\n return;\n }\n await this.requestWithSessionRetry(() =>\n this.client.unregisterPushDevice({\n subscriberId: this.subscriberId,\n pushToken: normalizedToken,\n }),\n );\n }\n\n async logActionClick(item: InboxItemRecord, actionUrl: string, actionLabel?: string) {\n return this.requestWithSessionRetry(() =>\n this.client.logActionClick({\n subscriberId: this.subscriberId,\n inboxItemId: item._id,\n actionUrl,\n actionLabel,\n }),\n );\n }\n\n private async requestWithSessionRetry<T>(request: () => Promise<T>): Promise<T> {\n try {\n return await request();\n } catch (error) {\n if (!(error instanceof BeeperApiError) || error.status !== 401 || !this.refreshSessionToken) {\n throw error;\n }\n const nextToken = await this.refreshSessionToken();\n this.client.updateSessionToken(nextToken);\n return request();\n }\n }\n\n private update(patch: Partial<BeeperInboxCoreState>) {\n this.state = { ...this.state, ...patch };\n this.emit();\n }\n\n private emit() {\n for (const listener of this.listeners) {\n listener(this.state);\n }\n }\n\n private schedulePoll() {\n if (!this.started || this.pollTimer) {\n return;\n }\n this.pollTimer = setTimeout(() => {\n this.pollTimer = null;\n void this.refresh({ silent: true }).catch(() => undefined);\n }, this.pollIntervalMs);\n }\n\n private clearPollTimer() {\n if (this.pollTimer) {\n clearTimeout(this.pollTimer);\n this.pollTimer = null;\n }\n }\n}\n","import type { InboxItemRecord } from \"beeper-sdk\";\n\n/** What `onActionPress` receives when an inbox item's action is pressed. */\nexport interface BeeperNativeActionPress {\n item: InboxItemRecord;\n actionLabel?: string;\n actionUrl: string;\n}\n\n/**\n * Called when an inbox item's action is pressed, before the default behaviour.\n * Return `false` (or resolve to `false`) to stop the package from opening the\n * URL with `Linking.openURL` — e.g. after routing in-app with React Navigation or\n * expo-router. Any other return value lets the default run.\n */\nexport type BeeperNativeActionPressHandler = (\n action: BeeperNativeActionPress,\n) => boolean | void | Promise<boolean | void>;\n\n/**\n * Runs one action press: records the click, lets the host app intercept, then\n * opens the URL unless it declined. Kept free of react-native imports so it can\n * be tested in plain Node.\n */\nexport async function runActionPress(input: {\n item: InboxItemRecord;\n onActionPress?: BeeperNativeActionPressHandler;\n logActionClick: (item: InboxItemRecord, actionUrl: string, actionLabel?: string) => Promise<unknown>;\n openURL: (url: string) => Promise<unknown>;\n}): Promise<void> {\n const actionUrl = input.item.actionUrl?.trim();\n if (!actionUrl) {\n return;\n }\n\n // Click analytics are best-effort. They run alongside the action and must never\n // delay or cancel it: awaiting them first meant a network error or an expired\n // session left the user tapping a button that did nothing.\n void input\n .logActionClick(input.item, actionUrl, input.item.actionLabel)\n .catch(() => undefined);\n\n // A throwing handler propagates and the URL is not opened: that is a bug in the\n // host app and should surface, not be papered over by navigating anyway.\n const shouldOpen =\n (await input.onActionPress?.({\n item: input.item,\n actionLabel: input.item.actionLabel,\n actionUrl,\n })) !== false;\n\n if (!shouldOpen) {\n return;\n }\n\n try {\n await input.openURL(actionUrl);\n } catch {\n // No app can handle this URL scheme on the device. Nothing useful to do.\n }\n}\n","import {\n ActivityIndicator,\n FlatList,\n Linking,\n Pressable,\n StyleSheet,\n Text,\n View,\n type ListRenderItemInfo,\n type StyleProp,\n type TextStyle,\n type ViewStyle,\n} from \"react-native\";\nimport {\n createContext,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useSyncExternalStore,\n type ReactNode,\n} from \"react\";\nimport { BeeperInboxCore } from \"beeper-inbox-core\";\nimport type { BeeperInboxCoreState, RegisterPushTokenOptions } from \"beeper-inbox-core\";\nimport { BeeperWidgetClient } from \"beeper-sdk/widget\";\nimport type { InboxItemRecord, PushPlatform } from \"beeper-sdk\";\n\nimport { runActionPress, type BeeperNativeActionPressHandler } from \"./actionPress\";\n\nexport type { BeeperNativeActionPress, BeeperNativeActionPressHandler } from \"./actionPress\";\n\nexport interface BeeperNativeSubscriber {\n subscriberId: string;\n displayName?: string;\n email?: string;\n metadata?: Record<string, unknown>;\n}\n\nexport interface BeeperNativePushRegistration {\n token?: string;\n platform?: Extract<PushPlatform, \"ios\" | \"android\">;\n deviceLabel?: string;\n metadata?: Record<string, unknown>;\n autoRegister?: boolean;\n autoUnregister?: boolean;\n}\n\nexport interface BeeperNativeInboxProviderProps {\n /**\n * Optional advanced override for the Beeper Widget API origin. Defaults to the\n * hosted Beeper API. Most host apps should not pass this.\n */\n baseUrl?: string;\n projectId: string;\n publishableKey: string;\n sessionToken: string;\n refreshSessionToken?: () => Promise<string>;\n subscriber: BeeperNativeSubscriber;\n push?: BeeperNativePushRegistration;\n pollIntervalMs?: number;\n accentColor?: string;\n /**\n * Intercepts an inbox item's action press. Return `false` to skip the default\n * `Linking.openURL`, e.g. to navigate in-app instead:\n *\n * ```tsx\n * onActionPress={({ actionUrl }) => {\n * if (actionUrl.startsWith(\"myapp://\")) {\n * router.push(toRoute(actionUrl));\n * return false;\n * }\n * }}\n * ```\n */\n onActionPress?: BeeperNativeActionPressHandler;\n children: ReactNode;\n}\n\n/** What `useBeeperInbox()` returns: live inbox state plus the actions on it. */\nexport interface BeeperNativeInbox extends BeeperInboxCoreState {\n /** Re-fetches the inbox. `silent` skips the loading state. */\n refresh: (options?: { silent?: boolean }) => Promise<void>;\n markRead: (inboxItemId: string) => Promise<void>;\n markAllRead: () => Promise<void>;\n registerPushToken: (token: string, options: RegisterPushTokenOptions) => Promise<void>;\n unregisterPushToken: (token: string) => Promise<void>;\n /**\n * Performs an item's action exactly as the built-in item does: records the\n * click, calls `onActionPress`, then opens the URL unless it returned `false`.\n * Use it from custom item UIs so their analytics and routing stay consistent.\n */\n handleActionPress: (item: InboxItemRecord) => Promise<void>;\n}\n\ntype NativeInboxActions = Omit<BeeperNativeInbox, keyof BeeperInboxCoreState>;\n\ninterface NativeInboxContextValue {\n core: BeeperInboxCore;\n state: BeeperInboxCoreState;\n accentColor: string;\n actions: NativeInboxActions;\n}\n\nconst InboxContext = createContext<NativeInboxContextValue | null>(null);\n\nexport function BeeperNativeInboxProvider({\n baseUrl,\n projectId,\n publishableKey,\n sessionToken,\n refreshSessionToken,\n subscriber,\n push,\n pollIntervalMs,\n accentColor = \"#f97316\",\n onActionPress,\n children,\n}: BeeperNativeInboxProviderProps) {\n const client = useMemo(\n () =>\n new BeeperWidgetClient({\n baseUrl,\n projectId,\n publishableKey,\n sessionToken,\n }),\n [baseUrl, projectId, publishableKey, sessionToken],\n );\n const core = useMemo(\n () =>\n new BeeperInboxCore({\n client,\n subscriberId: subscriber.subscriberId,\n refreshSessionToken,\n pollIntervalMs,\n }),\n [client, pollIntervalMs, refreshSessionToken, subscriber.subscriberId],\n );\n const state = useSyncExternalStore(\n (listener) => core.subscribe(listener),\n () => core.getState(),\n () => core.getState(),\n );\n\n useEffect(() => {\n void core.start().catch(() => undefined);\n return () => core.stop();\n }, [core]);\n\n useEffect(() => {\n if (!push?.token || push.autoRegister === false) {\n return;\n }\n void core\n .registerPushToken(push.token, {\n platform: push.platform ?? \"android\",\n deviceLabel: push.deviceLabel,\n metadata: push.metadata,\n })\n .catch(() => undefined);\n\n if (push.autoUnregister) {\n return () => {\n void core.unregisterPushToken(push.token!);\n };\n }\n }, [core, push]);\n\n // Read through a ref so an inline `onActionPress` arrow doesn't rebuild the\n // actions, and every consumer, on each render of the host component.\n const onActionPressRef = useRef(onActionPress);\n useEffect(() => {\n onActionPressRef.current = onActionPress;\n }, [onActionPress]);\n\n const actions = useMemo<NativeInboxActions>(\n () => ({\n refresh: async (options) => {\n await core.refresh(options);\n },\n markRead: async (inboxItemId) => {\n await core.markRead(inboxItemId);\n },\n markAllRead: async () => {\n await core.markAllRead();\n },\n registerPushToken: async (token, options) => {\n await core.registerPushToken(token, options);\n },\n unregisterPushToken: async (token) => {\n await core.unregisterPushToken(token);\n },\n handleActionPress: (item) =>\n runActionPress({\n item,\n onActionPress: onActionPressRef.current,\n logActionClick: (target, actionUrl, actionLabel) =>\n core.logActionClick(target, actionUrl, actionLabel),\n openURL: (url) => Linking.openURL(url),\n }),\n }),\n [core],\n );\n\n const value = useMemo(\n () => ({ core, state, accentColor, actions }),\n [accentColor, actions, core, state],\n );\n return <InboxContext.Provider value={value}>{children}</InboxContext.Provider>;\n}\n\nfunction useNativeInbox() {\n const context = useContext(InboxContext);\n if (!context) {\n throw new Error(\"Beeper inbox components must be inside BeeperNativeInboxProvider\");\n }\n return context;\n}\n\n/**\n * Live inbox state and actions, for building your own UI or showing the unread\n * count elsewhere (a tab bar badge, say). Must be used inside\n * `BeeperNativeInboxProvider`; re-renders when the inbox changes.\n *\n * ```tsx\n * const { items, unreadCount, markRead, handleActionPress } = useBeeperInbox();\n * ```\n */\nexport function useBeeperInbox(): BeeperNativeInbox {\n const context = useContext(InboxContext);\n if (!context) {\n throw new Error(\"useBeeperInbox must be used inside BeeperNativeInboxProvider\");\n }\n return { ...context.state, ...context.actions };\n}\n\nexport function BeeperInboxBadge({\n onPress,\n style,\n textStyle,\n}: {\n onPress?: () => void;\n style?: StyleProp<ViewStyle>;\n textStyle?: StyleProp<TextStyle>;\n}) {\n const { state, accentColor } = useNativeInbox();\n const content = (\n <View style={[styles.badge, { backgroundColor: accentColor }, style]}>\n <Text style={[styles.badgeText, textStyle]}>{state.unreadCount > 99 ? \"99+\" : state.unreadCount}</Text>\n </View>\n );\n return onPress ? <Pressable accessibilityRole=\"button\" onPress={onPress}>{content}</Pressable> : content;\n}\n\nexport function BeeperInboxItem({ item }: { item: InboxItemRecord }) {\n const { core, accentColor, actions } = useNativeInbox();\n\n return (\n <View style={styles.item}>\n <Text style={styles.itemTitle}>{item.title ?? \"Notification\"}</Text>\n <Text style={styles.itemBody}>{item.body}</Text>\n <View style={styles.itemFooter}>\n <Text style={styles.itemDate}>{new Date(item.createdAt).toLocaleString()}</Text>\n {!item.readAt ? (\n <Pressable\n accessibilityRole=\"button\"\n accessibilityLabel=\"Mark notification as read\"\n onPress={() => void core.markRead(item._id)}\n >\n <Text style={[styles.actionText, { color: accentColor }]}>Mark read</Text>\n </Pressable>\n ) : null}\n {item.actionUrl ? (\n <Pressable accessibilityRole=\"button\" onPress={() => void actions.handleActionPress(item)}>\n <Text style={[styles.actionText, { color: accentColor }]}>{item.actionLabel ?? \"Open\"}</Text>\n </Pressable>\n ) : null}\n </View>\n </View>\n );\n}\n\nexport function BeeperInboxList({\n style,\n contentContainerStyle,\n}: {\n style?: StyleProp<ViewStyle>;\n contentContainerStyle?: StyleProp<ViewStyle>;\n}) {\n const { state } = useNativeInbox();\n if (state.loading && state.items.length === 0) {\n return <ActivityIndicator accessibilityLabel=\"Loading notifications\" style={styles.loader} />;\n }\n if (state.errorMessage && state.items.length === 0) {\n return <Text accessibilityRole=\"alert\" style={styles.error}>{state.errorMessage}</Text>;\n }\n if (state.items.length === 0) {\n return <Text style={styles.empty}>No notifications yet.</Text>;\n }\n\n const renderItem = ({ item }: ListRenderItemInfo<InboxItemRecord>) => <BeeperInboxItem item={item} />;\n return (\n <FlatList\n accessibilityLabel=\"Notifications\"\n data={state.items}\n keyExtractor={(item) => item._id}\n renderItem={renderItem}\n style={style}\n contentContainerStyle={contentContainerStyle}\n />\n );\n}\n\nexport function BeeperInboxPanel({\n title = \"Notifications\",\n style,\n}: {\n title?: string;\n style?: StyleProp<ViewStyle>;\n}) {\n const { core, state, accentColor } = useNativeInbox();\n return (\n <View style={[styles.panel, style]}>\n <View style={styles.header}>\n <View>\n <Text style={styles.title}>{title}</Text>\n <Text style={styles.subtitle} accessibilityLiveRegion=\"polite\">\n {state.unreadCount} unread\n </Text>\n </View>\n {state.unreadCount > 0 ? (\n <Pressable accessibilityRole=\"button\" onPress={() => void core.markAllRead()}>\n <Text style={[styles.actionText, { color: accentColor }]}>Mark all read</Text>\n </Pressable>\n ) : null}\n </View>\n <BeeperInboxList contentContainerStyle={styles.listContent} />\n </View>\n );\n}\n\nexport function BeeperInboxRefreshControl() {\n const { core, state } = useNativeInbox();\n return (\n <Pressable accessibilityRole=\"button\" onPress={() => void core.refresh({ silent: true })}>\n <Text style={styles.actionText}>{state.refreshing ? \"Refreshing...\" : \"Refresh\"}</Text>\n </Pressable>\n );\n}\n\nconst styles = StyleSheet.create({\n panel: {\n backgroundColor: \"#fffaf5\",\n borderColor: \"#eadbcc\",\n borderRadius: 14,\n borderWidth: 1,\n padding: 14,\n },\n header: {\n alignItems: \"center\",\n flexDirection: \"row\",\n justifyContent: \"space-between\",\n marginBottom: 12,\n },\n title: { color: \"#2b221d\", fontSize: 18, fontWeight: \"700\" },\n subtitle: { color: \"#7d685d\", fontSize: 13, marginTop: 2 },\n listContent: { gap: 8 },\n item: { backgroundColor: \"#fffdf9\", borderColor: \"#eadbcc\", borderRadius: 10, borderWidth: 1, padding: 14 },\n itemTitle: { color: \"#2b221d\", fontSize: 15, fontWeight: \"700\", marginBottom: 5 },\n itemBody: { color: \"#4e3c34\", fontSize: 14, lineHeight: 21 },\n itemFooter: { alignItems: \"center\", flexDirection: \"row\", flexWrap: \"wrap\", gap: 12, marginTop: 10 },\n itemDate: { color: \"#7d685d\", flex: 1, fontSize: 12 },\n actionText: { fontSize: 13, fontWeight: \"700\", paddingVertical: 8 },\n badge: { alignItems: \"center\", borderRadius: 999, justifyContent: \"center\", minHeight: 24, minWidth: 24, paddingHorizontal: 7 },\n badgeText: { color: \"#fff\", fontSize: 12, fontWeight: \"700\" },\n loader: { padding: 24 },\n empty: { color: \"#7d685d\", padding: 24, textAlign: \"center\" },\n error: { color: \"#a43d28\", padding: 24, textAlign: \"center\" },\n});\n"]}
1
+ {"version":3,"sources":["../../inbox-core/src/index.ts","../src/actionPress.ts","../src/index.tsx"],"names":[],"mappings":";;;;;;;;;AA4BA,SAAS,2BAA2B,SAAA,EAAiB;AACnD,EAAA,MAAM,MAAA,GAAS,IAAI,YAAA,CAAa,SAAS,CAAA;AACzC,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AAS;AAAA,EAC5D,OAAO,EAAE,KAAA,EAAO,WAAW,OAAA,EAAS,EAAA,EAAI,WAAW,QAAA;AACrD,CAAC,CAAA","file":"index.js","sourcesContent":["import { ConvexClient } from \"convex/browser\";\nimport { BeeperApiError } from \"beeper-sdk\";\nimport type {\n InboxItemRecord,\n PushPlatform,\n SubscriberRecord,\n} from \"beeper-sdk\";\nimport type { BeeperWidgetClient, WidgetInboxResult } from \"beeper-sdk/widget\";\n\nexport type InboxConnectionState = \"idle\" | \"loading\" | \"live\" | \"error\";\n\n/**\n * How updates arrive: pushed over a realtime subscription, or fetched on a\n * timer. Starts as \"polling\" and switches once a subscription delivers.\n */\nexport type InboxTransport = \"polling\" | \"realtime\";\n\n/** The subset of a Convex client the core subscribes through. */\nexport interface InboxRealtimeClient {\n onUpdate(\n query: string,\n args: Record<string, unknown>,\n onResult: (result: unknown) => void,\n onError: (error: Error) => void,\n ): () => void;\n close(): void | Promise<void>;\n}\n\nfunction createConvexRealtimeClient(convexUrl: string): InboxRealtimeClient {\n const client = new ConvexClient(convexUrl);\n return {\n onUpdate(query, args, onResult, onError) {\n const unsubscribe = client.onUpdate(query as any, args as any, onResult, onError);\n return () => unsubscribe();\n },\n close: () => client.close(),\n };\n}\n\nexport interface BeeperInboxCoreState {\n subscriber: SubscriberRecord | null;\n items: InboxItemRecord[];\n unreadCount: number;\n /** Unread per kind named in `unreadKinds`, each capped at 100. Empty otherwise. */\n unreadByKind: Record<string, number>;\n loading: boolean;\n refreshing: boolean;\n /** An older page is being fetched by `loadMore()`. */\n loadingMore: boolean;\n /** Older items exist beyond `items`; call `loadMore()` to fetch them. */\n hasMore: boolean;\n connectionState: InboxConnectionState;\n transport: InboxTransport;\n errorMessage: string | null;\n}\n\nexport interface BeeperInboxCoreOptions {\n client: BeeperWidgetClient;\n subscriberId: string;\n refreshSessionToken?: () => Promise<string>;\n pollIntervalMs?: number;\n /** Only items whose `kind` (from `metadata.kind`) is one of these. */\n kind?: string | string[];\n /** Items per request, 1-100. Default 100. */\n pageSize?: number;\n /** Show archived items instead of active ones. */\n archived?: boolean;\n /** Keep `unreadByKind` for these kinds (e.g. your tabs), fetched with the list. */\n unreadKinds?: string[];\n /**\n * Receive updates over a live subscription instead of polling, when the\n * project's widget config offers one. Polling resumes if it fails. Default\n * true.\n */\n realtime?: boolean;\n /** Replaces the Convex client, for tests. */\n createRealtimeClient?: (convexUrl: string) => InboxRealtimeClient;\n}\n\nexport interface RegisterPushTokenOptions {\n platform: PushPlatform;\n deviceLabel?: string;\n metadata?: Record<string, unknown>;\n}\n\nexport type BeeperInboxCoreListener = (state: BeeperInboxCoreState) => void;\n\nconst DEFAULT_POLL_INTERVAL_MS = 15_000;\nconst DEFAULT_PAGE_SIZE = 100;\n/** Wait before retrying a failed subscription; polling covers the gap. */\nconst REALTIME_RETRY_MS = 60_000;\n\nexport class BeeperInboxCore {\n private readonly client: BeeperWidgetClient;\n private readonly subscriberId: string;\n private readonly refreshSessionToken?: () => Promise<string>;\n private readonly pollIntervalMs: number;\n private readonly kind?: string | string[];\n private readonly pageSize: number;\n private readonly archivedView: boolean;\n private readonly unreadKinds?: string[];\n private readonly realtimeEnabled: boolean;\n private readonly createRealtimeClient: (convexUrl: string) => InboxRealtimeClient;\n private realtimeClient: InboxRealtimeClient | null = null;\n private realtimeUnsubscribe: (() => void) | null = null;\n private realtimeRetryTimer: ReturnType<typeof setTimeout> | null = null;\n /** True while a subscription is delivering; polling is off meanwhile. */\n private realtimeLive = false;\n /** Where the next `loadMore()` starts. */\n private cursor: string | null = null;\n /** Set once `loadMore()` has appended a page that refreshes must keep. */\n private hasOlderPages = false;\n private loadMoreRequest: Promise<void> | null = null;\n private readonly listeners = new Set<BeeperInboxCoreListener>();\n private state: BeeperInboxCoreState = {\n subscriber: null,\n items: [],\n unreadCount: 0,\n unreadByKind: {},\n loading: false,\n refreshing: false,\n loadingMore: false,\n hasMore: false,\n connectionState: \"idle\",\n transport: \"polling\",\n errorMessage: null,\n };\n private pollTimer: ReturnType<typeof setTimeout> | null = null;\n private started = false;\n private request: Promise<void> | null = null;\n\n constructor(options: BeeperInboxCoreOptions) {\n if (!options.subscriberId.trim()) {\n throw new Error(\"A subscriberId is required\");\n }\n this.client = options.client;\n this.subscriberId = options.subscriberId;\n this.refreshSessionToken = options.refreshSessionToken;\n this.pollIntervalMs = Math.max(5_000, options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS);\n this.kind = options.kind;\n this.archivedView = options.archived === true;\n this.unreadKinds = options.unreadKinds?.length ? options.unreadKinds : undefined;\n this.realtimeEnabled = options.realtime !== false;\n this.createRealtimeClient = options.createRealtimeClient ?? createConvexRealtimeClient;\n this.pageSize = Math.min(Math.max(Math.round(options.pageSize ?? DEFAULT_PAGE_SIZE), 1), 100);\n }\n\n getState() {\n return this.state;\n }\n\n subscribe(listener: BeeperInboxCoreListener) {\n this.listeners.add(listener);\n listener(this.state);\n return () => this.listeners.delete(listener);\n }\n\n async start() {\n if (this.started) {\n return;\n }\n this.started = true;\n // The HTTP load paints first; the subscription then takes over updates.\n await this.refresh();\n if (this.realtimeEnabled) {\n void this.connectRealtime();\n }\n }\n\n stop() {\n this.started = false;\n this.clearPollTimer();\n this.disconnectRealtime();\n }\n\n async refresh(options: { silent?: boolean } = {}) {\n if (this.request) {\n return this.request;\n }\n\n this.update({\n ...(options.silent ? { refreshing: true } : { loading: true }),\n connectionState: options.silent ? this.state.connectionState : \"loading\",\n errorMessage: null,\n });\n\n this.request = this.requestWithSessionRetry(async () => {\n const result = await this.client.getInbox(this.subscriberId, {\n limit: this.pageSize,\n kind: this.kind,\n archived: this.archivedView,\n unreadKinds: this.unreadKinds,\n });\n this.applyFirstPage(result);\n })\n .catch((error: unknown) => {\n this.update({\n connectionState: \"error\",\n errorMessage: error instanceof Error ? error.message : \"Inbox request failed\",\n });\n throw error;\n })\n .finally(() => {\n this.request = null;\n this.update({ loading: false, refreshing: false });\n this.schedulePoll();\n });\n\n return this.request;\n }\n\n /**\n * Applies a fresh newest page, from a fetch or a subscription push. Once older\n * pages are loaded, they stay below it rather than dropping the user's scroll\n * position, and the cursor, which already points past them, is kept.\n */\n private applyFirstPage(result: WidgetInboxResult) {\n let items = result.items;\n if (this.hasOlderPages) {\n items = mergeOlder(result.items, this.state.items);\n } else {\n this.cursor = result.nextCursor ?? null;\n }\n this.update({\n subscriber: result.subscriber,\n items,\n unreadCount: result.unreadCount,\n unreadByKind: result.unreadByKind ?? {},\n hasMore: this.cursor !== null,\n connectionState: \"live\",\n errorMessage: null,\n });\n }\n\n /**\n * Appends the next older page. No-op while one is in flight or when\n * `hasMore` is false.\n */\n async loadMore() {\n if (this.loadMoreRequest) {\n return this.loadMoreRequest;\n }\n const cursor = this.cursor;\n if (!cursor) {\n return;\n }\n\n this.update({ loadingMore: true });\n this.loadMoreRequest = this.requestWithSessionRetry(async () => {\n const result = await this.client.getInbox(this.subscriberId, {\n limit: this.pageSize,\n cursor,\n kind: this.kind,\n archived: this.archivedView,\n unreadKinds: this.unreadKinds,\n });\n const seen = new Set(this.state.items.map((item) => item._id));\n this.cursor = result.nextCursor ?? null;\n this.hasOlderPages = true;\n this.update({\n items: [...this.state.items, ...result.items.filter((item) => !seen.has(item._id))],\n unreadCount: result.unreadCount,\n unreadByKind: result.unreadByKind ?? {},\n hasMore: this.cursor !== null,\n });\n }).finally(() => {\n this.loadMoreRequest = null;\n this.update({ loadingMore: false });\n });\n\n return this.loadMoreRequest;\n }\n\n async markRead(inboxItemId: string) {\n const previous = this.state;\n const now = Date.now();\n const target = this.state.items.find((item) => item._id === inboxItemId && !item.readAt);\n this.update({\n items: this.state.items.map((item) =>\n item._id === inboxItemId ? { ...item, readAt: item.readAt ?? now } : item,\n ),\n ...this.unreadAfterReading(target),\n });\n\n try {\n await this.requestWithSessionRetry(() =>\n this.client.markRead(this.subscriberId, [inboxItemId]),\n );\n await this.refreshAfterWrite();\n } catch (error) {\n this.state = previous;\n this.emit();\n throw error;\n }\n }\n\n async markAllRead() {\n const previous = this.state;\n this.update({\n items: this.state.items.map((item) => ({ ...item, readAt: item.readAt ?? Date.now() })),\n unreadCount: 0,\n unreadByKind: Object.fromEntries(\n Object.keys(this.state.unreadByKind).map((kind) => [kind, 0]),\n ),\n });\n\n try {\n await this.requestWithSessionRetry(() => this.client.markAllRead(this.subscriberId));\n await this.refreshAfterWrite();\n } catch (error) {\n this.state = previous;\n this.emit();\n throw error;\n }\n }\n\n /**\n * Archives an item (e.g. swipe to dismiss). It leaves the list at once and\n * counts as read; restored if the request fails.\n */\n async archive(inboxItemId: string) {\n return this.setArchived(inboxItemId, true);\n }\n\n /** Returns an archived item to the active inbox. */\n async unarchive(inboxItemId: string) {\n return this.setArchived(inboxItemId, false);\n }\n\n private async setArchived(inboxItemId: string, archived: boolean) {\n const previous = this.state;\n const target = this.state.items.find((item) => item._id === inboxItemId);\n // Archiving leaves the active view and unarchiving leaves the archived one;\n // the other direction doesn't change what this view shows.\n const leavesView = archived !== this.archivedView;\n this.update({\n items: leavesView\n ? this.state.items.filter((item) => item._id !== inboxItemId)\n : this.state.items,\n // Archiving marks the item read on the server.\n ...(archived ? this.unreadAfterReading(target?.readAt ? undefined : target) : {}),\n });\n\n try {\n await this.requestWithSessionRetry(() =>\n archived\n ? this.client.archive(this.subscriberId, [inboxItemId])\n : this.client.unarchive(this.subscriberId, [inboxItemId]),\n );\n await this.refreshAfterWrite();\n } catch (error) {\n this.state = previous;\n this.emit();\n throw error;\n }\n }\n\n async registerPushToken(token: string, options: RegisterPushTokenOptions) {\n const normalizedToken = token.trim();\n if (!normalizedToken) {\n throw new Error(\"A push token is required\");\n }\n await this.requestWithSessionRetry(() =>\n this.client.registerPushDevice({\n subscriberId: this.subscriberId,\n pushToken: normalizedToken,\n ...options,\n }),\n );\n }\n\n async unregisterPushToken(token: string) {\n const normalizedToken = token.trim();\n if (!normalizedToken) {\n return;\n }\n await this.requestWithSessionRetry(() =>\n this.client.unregisterPushDevice({\n subscriberId: this.subscriberId,\n pushToken: normalizedToken,\n }),\n );\n }\n\n async logActionClick(item: InboxItemRecord, actionUrl: string, actionLabel?: string) {\n return this.requestWithSessionRetry(() =>\n this.client.logActionClick({\n subscriberId: this.subscriberId,\n inboxItemId: item._id,\n actionUrl,\n actionLabel,\n }),\n );\n }\n\n /** Unread counters after `item` (if unread and known) becomes read. */\n private unreadAfterReading(item: InboxItemRecord | undefined) {\n if (!item || item.readAt) {\n return {};\n }\n const unreadByKind = { ...this.state.unreadByKind };\n if (item.kind && item.kind in unreadByKind) {\n unreadByKind[item.kind] = Math.max(0, (unreadByKind[item.kind] ?? 0) - 1);\n }\n return { unreadCount: Math.max(0, this.state.unreadCount - 1), unreadByKind };\n }\n\n private async requestWithSessionRetry<T>(request: () => Promise<T>): Promise<T> {\n try {\n return await request();\n } catch (error) {\n if (!(error instanceof BeeperApiError) || error.status !== 401 || !this.refreshSessionToken) {\n throw error;\n }\n const nextToken = await this.refreshSessionToken();\n this.client.updateSessionToken(nextToken);\n return request();\n }\n }\n\n private update(patch: Partial<BeeperInboxCoreState>) {\n this.state = { ...this.state, ...patch };\n this.emit();\n }\n\n private emit() {\n for (const listener of this.listeners) {\n listener(this.state);\n }\n }\n\n /** A live subscription pushes the write's result, so only a poller re-fetches. */\n private async refreshAfterWrite() {\n if (!this.realtimeLive) {\n await this.refresh({ silent: true });\n }\n }\n\n private realtimeArgs(): Record<string, unknown> {\n const kinds = this.kind === undefined ? [] : [this.kind].flat();\n return {\n projectId: this.client.getProjectId(),\n sessionToken: this.client.getSessionToken(),\n subscriberId: this.subscriberId,\n limit: this.pageSize,\n ...(kinds.length ? { kinds } : {}),\n ...(this.archivedView ? { archived: true } : {}),\n ...(this.unreadKinds ? { unreadKinds: this.unreadKinds } : {}),\n };\n }\n\n private async connectRealtime() {\n let convexUrl: string | undefined;\n try {\n convexUrl = (await this.client.getConfig()).convexUrl;\n } catch {\n this.scheduleRealtimeRetry();\n return;\n }\n if (!convexUrl || !this.started) {\n // No realtime endpoint offered: polling stays in charge.\n return;\n }\n try {\n this.realtimeClient ??= this.createRealtimeClient(convexUrl);\n } catch {\n return;\n }\n this.subscribeRealtime(false);\n }\n\n private subscribeRealtime(afterSessionRefresh: boolean) {\n if (!this.started || !this.realtimeClient) {\n return;\n }\n this.realtimeUnsubscribe?.();\n this.realtimeUnsubscribe = this.realtimeClient.onUpdate(\n \"widgetInbox:list\",\n this.realtimeArgs(),\n (result) => {\n if (!this.started) {\n return;\n }\n this.realtimeLive = true;\n this.clearPollTimer();\n this.update({ transport: \"realtime\" });\n this.applyFirstPage(result as WidgetInboxResult);\n },\n (error) => {\n void this.handleRealtimeError(error, afterSessionRefresh);\n },\n );\n }\n\n private async handleRealtimeError(error: Error, afterSessionRefresh: boolean) {\n if (!this.started) {\n return;\n }\n // The subscription carries the session token in its args, so an expired\n // token surfaces here rather than as a 401. Refresh it once and resubscribe.\n if (\n !afterSessionRefresh &&\n this.refreshSessionToken &&\n /session|token|expired|invalid/i.test(error.message)\n ) {\n try {\n this.client.updateSessionToken(await this.refreshSessionToken());\n this.subscribeRealtime(true);\n return;\n } catch {\n // Fall through to polling.\n }\n }\n\n this.realtimeUnsubscribe?.();\n this.realtimeUnsubscribe = null;\n this.realtimeLive = false;\n this.update({ transport: \"polling\" });\n this.schedulePoll();\n this.scheduleRealtimeRetry();\n }\n\n private scheduleRealtimeRetry() {\n if (!this.started || this.realtimeRetryTimer) {\n return;\n }\n this.realtimeRetryTimer = setTimeout(() => {\n this.realtimeRetryTimer = null;\n if (this.realtimeClient) {\n this.subscribeRealtime(false);\n } else {\n void this.connectRealtime();\n }\n }, REALTIME_RETRY_MS);\n }\n\n private disconnectRealtime() {\n if (this.realtimeRetryTimer) {\n clearTimeout(this.realtimeRetryTimer);\n this.realtimeRetryTimer = null;\n }\n this.realtimeUnsubscribe?.();\n this.realtimeUnsubscribe = null;\n const client = this.realtimeClient;\n this.realtimeClient = null;\n this.realtimeLive = false;\n if (client) {\n void Promise.resolve(client.close()).catch(() => undefined);\n }\n this.update({ transport: \"polling\" });\n }\n\n private schedulePoll() {\n if (!this.started || this.pollTimer || this.realtimeLive) {\n return;\n }\n this.pollTimer = setTimeout(() => {\n this.pollTimer = null;\n void this.refresh({ silent: true }).catch(() => undefined);\n }, this.pollIntervalMs);\n }\n\n private clearPollTimer() {\n if (this.pollTimer) {\n clearTimeout(this.pollTimer);\n this.pollTimer = null;\n }\n }\n}\n\n/**\n * The fresh newest page followed by previously loaded items older than it.\n * Items are newest first, so \"older\" is anything past the page's last item.\n */\nfunction mergeOlder(head: InboxItemRecord[], previous: InboxItemRecord[]): InboxItemRecord[] {\n const last = head[head.length - 1];\n if (!last) {\n return previous;\n }\n const headIds = new Set(head.map((item) => item._id));\n const tail = previous.filter(\n (item) => !headIds.has(item._id) && item.createdAt <= last.createdAt,\n );\n return [...head, ...tail];\n}\n","import type { InboxItemRecord } from \"beeper-sdk\";\n\n/** What `onActionPress` receives when an inbox item's action is pressed. */\nexport interface BeeperNativeActionPress {\n item: InboxItemRecord;\n actionLabel?: string;\n actionUrl: string;\n}\n\n/**\n * Called when an inbox item's action is pressed, before the default behaviour.\n * Return `false` (or resolve to `false`) to stop the package from opening the\n * URL with `Linking.openURL` — e.g. after routing in-app with React Navigation or\n * expo-router. Any other return value lets the default run.\n */\nexport type BeeperNativeActionPressHandler = (\n action: BeeperNativeActionPress,\n) => boolean | void | Promise<boolean | void>;\n\n/**\n * Runs one action press: records the click, lets the host app intercept, then\n * opens the URL unless it declined. Kept free of react-native imports so it can\n * be tested in plain Node.\n */\nexport async function runActionPress(input: {\n item: InboxItemRecord;\n onActionPress?: BeeperNativeActionPressHandler;\n logActionClick: (item: InboxItemRecord, actionUrl: string, actionLabel?: string) => Promise<unknown>;\n openURL: (url: string) => Promise<unknown>;\n}): Promise<void> {\n const actionUrl = input.item.actionUrl?.trim();\n if (!actionUrl) {\n return;\n }\n\n // Click analytics are best-effort. They run alongside the action and must never\n // delay or cancel it: awaiting them first meant a network error or an expired\n // session left the user tapping a button that did nothing.\n void input\n .logActionClick(input.item, actionUrl, input.item.actionLabel)\n .catch(() => undefined);\n\n // A throwing handler propagates and the URL is not opened: that is a bug in the\n // host app and should surface, not be papered over by navigating anyway.\n const shouldOpen =\n (await input.onActionPress?.({\n item: input.item,\n actionLabel: input.item.actionLabel,\n actionUrl,\n })) !== false;\n\n if (!shouldOpen) {\n return;\n }\n\n try {\n await input.openURL(actionUrl);\n } catch {\n // No app can handle this URL scheme on the device. Nothing useful to do.\n }\n}\n","import {\n ActivityIndicator,\n FlatList,\n Image,\n Linking,\n Pressable,\n StyleSheet,\n Text,\n View,\n type ListRenderItemInfo,\n type StyleProp,\n type TextStyle,\n type ViewStyle,\n} from \"react-native\";\nimport {\n createContext,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useSyncExternalStore,\n type ReactNode,\n} from \"react\";\nimport { BeeperInboxCore } from \"beeper-inbox-core\";\nimport type { BeeperInboxCoreState, RegisterPushTokenOptions } from \"beeper-inbox-core\";\nimport { BeeperWidgetClient } from \"beeper-sdk/widget\";\nimport type { InboxItemRecord, PushPlatform } from \"beeper-sdk\";\n\nimport { runActionPress, type BeeperNativeActionPressHandler } from \"./actionPress\";\n\nexport type { BeeperNativeActionPress, BeeperNativeActionPressHandler } from \"./actionPress\";\n// Re-exported so custom lists can fold rows without importing beeper-sdk directly.\nexport { groupInboxItems } from \"beeper-sdk\";\nexport type { InboxItemGroup } from \"beeper-sdk\";\n\nexport interface BeeperNativeSubscriber {\n subscriberId: string;\n displayName?: string;\n email?: string;\n metadata?: Record<string, unknown>;\n}\n\nexport interface BeeperNativePushRegistration {\n token?: string;\n platform?: Extract<PushPlatform, \"ios\" | \"android\">;\n deviceLabel?: string;\n metadata?: Record<string, unknown>;\n autoRegister?: boolean;\n autoUnregister?: boolean;\n}\n\nexport interface BeeperNativeInboxProviderProps {\n /**\n * Optional advanced override for the Beeper Widget API origin. Defaults to the\n * hosted Beeper API. Most host apps should not pass this.\n */\n baseUrl?: string;\n projectId: string;\n publishableKey: string;\n sessionToken: string;\n refreshSessionToken?: () => Promise<string>;\n subscriber: BeeperNativeSubscriber;\n push?: BeeperNativePushRegistration;\n /**\n * Receive updates over a live connection instead of polling, when the project\n * offers one. Polling (`pollIntervalMs`) resumes if the connection fails.\n * `state.transport` says which is active. Default true.\n */\n realtime?: boolean;\n /** Polling interval when realtime is off or unavailable. Default 15s, minimum 5s. */\n pollIntervalMs?: number;\n /**\n * Only show items whose `kind` (from `metadata.kind` at send time) is one of\n * these, e.g. `\"order\"` for an orders tab. Changing it re-fetches.\n */\n kind?: string | string[];\n /** Items per request, 1-100. Default 100. */\n pageSize?: number;\n /** Show archived items instead of active ones, e.g. for an \"Archived\" screen. */\n archived?: boolean;\n /**\n * Keep `unreadByKind` for these kinds, for per-tab badges. Fetched with the\n * inbox itself, so it adds no requests. Up to 10.\n */\n unreadKinds?: string[];\n accentColor?: string;\n /**\n * Intercepts an inbox item's action press. Return `false` to skip the default\n * `Linking.openURL`, e.g. to navigate in-app instead:\n *\n * ```tsx\n * onActionPress={({ actionUrl }) => {\n * if (actionUrl.startsWith(\"myapp://\")) {\n * router.push(toRoute(actionUrl));\n * return false;\n * }\n * }}\n * ```\n */\n onActionPress?: BeeperNativeActionPressHandler;\n children: ReactNode;\n}\n\n/** What `useBeeperInbox()` returns: live inbox state plus the actions on it. */\nexport interface BeeperNativeInbox extends BeeperInboxCoreState {\n /** Re-fetches the inbox. `silent` skips the loading state. */\n refresh: (options?: { silent?: boolean }) => Promise<void>;\n markRead: (inboxItemId: string) => Promise<void>;\n markAllRead: () => Promise<void>;\n /** Appends the next older page. No-op when `hasMore` is false. */\n loadMore: () => Promise<void>;\n /**\n * Archives an item, e.g. from a swipe-to-dismiss row. It leaves the list at\n * once, counts as read, and comes back if the request fails.\n */\n archive: (inboxItemId: string) => Promise<void>;\n /** Returns an archived item to the active inbox. */\n unarchive: (inboxItemId: string) => Promise<void>;\n registerPushToken: (token: string, options: RegisterPushTokenOptions) => Promise<void>;\n unregisterPushToken: (token: string) => Promise<void>;\n /**\n * Performs an item's action exactly as the built-in item does: records the\n * click, calls `onActionPress`, then opens the URL unless it returned `false`.\n * Use it from custom item UIs so their analytics and routing stay consistent.\n */\n handleActionPress: (item: InboxItemRecord) => Promise<void>;\n}\n\ntype NativeInboxActions = Omit<BeeperNativeInbox, keyof BeeperInboxCoreState>;\n\ninterface NativeInboxContextValue {\n core: BeeperInboxCore;\n state: BeeperInboxCoreState;\n accentColor: string;\n actions: NativeInboxActions;\n}\n\nconst InboxContext = createContext<NativeInboxContextValue | null>(null);\n\nexport function BeeperNativeInboxProvider({\n baseUrl,\n projectId,\n publishableKey,\n sessionToken,\n refreshSessionToken,\n subscriber,\n push,\n realtime,\n pollIntervalMs,\n kind,\n pageSize,\n archived,\n unreadKinds,\n accentColor = \"#f97316\",\n onActionPress,\n children,\n}: BeeperNativeInboxProviderProps) {\n const client = useMemo(\n () =>\n new BeeperWidgetClient({\n baseUrl,\n projectId,\n publishableKey,\n sessionToken,\n }),\n [baseUrl, projectId, publishableKey, sessionToken],\n );\n // Keyed by value so an inline `kind={[\"order\", \"chat\"]}` doesn't rebuild the\n // core, and refetch, on every render.\n const kindKey = kind === undefined ? \"\" : JSON.stringify([kind].flat());\n const unreadKindsKey = unreadKinds?.length ? JSON.stringify(unreadKinds) : \"\";\n const core = useMemo(\n () =>\n new BeeperInboxCore({\n client,\n subscriberId: subscriber.subscriberId,\n refreshSessionToken,\n pollIntervalMs,\n kind: kindKey ? (JSON.parse(kindKey) as string[]) : undefined,\n pageSize,\n archived,\n unreadKinds: unreadKindsKey ? (JSON.parse(unreadKindsKey) as string[]) : undefined,\n realtime,\n }),\n [\n archived,\n realtime,\n client,\n kindKey,\n unreadKindsKey,\n pageSize,\n pollIntervalMs,\n refreshSessionToken,\n subscriber.subscriberId,\n ],\n );\n const state = useSyncExternalStore(\n (listener) => core.subscribe(listener),\n () => core.getState(),\n () => core.getState(),\n );\n\n useEffect(() => {\n void core.start().catch(() => undefined);\n return () => core.stop();\n }, [core]);\n\n useEffect(() => {\n if (!push?.token || push.autoRegister === false) {\n return;\n }\n void core\n .registerPushToken(push.token, {\n platform: push.platform ?? \"android\",\n deviceLabel: push.deviceLabel,\n metadata: push.metadata,\n })\n .catch(() => undefined);\n\n if (push.autoUnregister) {\n return () => {\n void core.unregisterPushToken(push.token!);\n };\n }\n }, [core, push]);\n\n // Read through a ref so an inline `onActionPress` arrow doesn't rebuild the\n // actions, and every consumer, on each render of the host component.\n const onActionPressRef = useRef(onActionPress);\n useEffect(() => {\n onActionPressRef.current = onActionPress;\n }, [onActionPress]);\n\n const actions = useMemo<NativeInboxActions>(\n () => ({\n refresh: async (options) => {\n await core.refresh(options);\n },\n markRead: async (inboxItemId) => {\n await core.markRead(inboxItemId);\n },\n markAllRead: async () => {\n await core.markAllRead();\n },\n loadMore: async () => {\n await core.loadMore();\n },\n archive: async (inboxItemId) => {\n await core.archive(inboxItemId);\n },\n unarchive: async (inboxItemId) => {\n await core.unarchive(inboxItemId);\n },\n registerPushToken: async (token, options) => {\n await core.registerPushToken(token, options);\n },\n unregisterPushToken: async (token) => {\n await core.unregisterPushToken(token);\n },\n handleActionPress: (item) =>\n runActionPress({\n item,\n onActionPress: onActionPressRef.current,\n logActionClick: (target, actionUrl, actionLabel) =>\n core.logActionClick(target, actionUrl, actionLabel),\n openURL: (url) => Linking.openURL(url),\n }),\n }),\n [core],\n );\n\n const value = useMemo(\n () => ({ core, state, accentColor, actions }),\n [accentColor, actions, core, state],\n );\n return <InboxContext.Provider value={value}>{children}</InboxContext.Provider>;\n}\n\nfunction useNativeInbox() {\n const context = useContext(InboxContext);\n if (!context) {\n throw new Error(\"Beeper inbox components must be inside BeeperNativeInboxProvider\");\n }\n return context;\n}\n\n/**\n * Live inbox state and actions, for building your own UI or showing the unread\n * count elsewhere (a tab bar badge, say). Must be used inside\n * `BeeperNativeInboxProvider`; re-renders when the inbox changes.\n *\n * ```tsx\n * const { items, unreadCount, markRead, handleActionPress } = useBeeperInbox();\n * ```\n */\nexport function useBeeperInbox(): BeeperNativeInbox {\n const context = useContext(InboxContext);\n if (!context) {\n throw new Error(\"useBeeperInbox must be used inside BeeperNativeInboxProvider\");\n }\n return { ...context.state, ...context.actions };\n}\n\nexport function BeeperInboxBadge({\n kind,\n onPress,\n style,\n textStyle,\n}: {\n /** Count only this kind. It must be in the provider's `unreadKinds`. */\n kind?: string;\n onPress?: () => void;\n style?: StyleProp<ViewStyle>;\n textStyle?: StyleProp<TextStyle>;\n}) {\n const { state, accentColor } = useNativeInbox();\n const count = kind === undefined ? state.unreadCount : (state.unreadByKind[kind] ?? 0);\n const content = (\n <View style={[styles.badge, { backgroundColor: accentColor }, style]}>\n <Text style={[styles.badgeText, textStyle]}>{count > 99 ? \"99+\" : count}</Text>\n </View>\n );\n return onPress ? <Pressable accessibilityRole=\"button\" onPress={onPress}>{content}</Pressable> : content;\n}\n\nexport function BeeperInboxItem({ item }: { item: InboxItemRecord }) {\n const { core, accentColor, actions } = useNativeInbox();\n\n return (\n // A resolved item was handled by the sender (e.g. the order was accepted).\n <View style={[styles.item, item.resolvedAt ? styles.itemResolved : null]}>\n <View style={styles.itemHeader}>\n {item.avatarUrl ? (\n <Image source={{ uri: item.avatarUrl }} style={styles.itemAvatar} accessibilityIgnoresInvertColors />\n ) : null}\n <Text style={[styles.itemTitle, styles.itemHeaderTitle]}>{item.title ?? \"Notification\"}</Text>\n </View>\n <Text style={styles.itemBody}>{item.body}</Text>\n {item.imageUrl ? (\n <Image source={{ uri: item.imageUrl }} style={styles.itemImage} accessibilityIgnoresInvertColors />\n ) : null}\n <View style={styles.itemFooter}>\n <Text style={styles.itemDate}>{new Date(item.createdAt).toLocaleString()}</Text>\n {!item.readAt ? (\n <Pressable\n accessibilityRole=\"button\"\n accessibilityLabel=\"Mark notification as read\"\n onPress={() => void core.markRead(item._id)}\n >\n <Text style={[styles.actionText, { color: accentColor }]}>Mark read</Text>\n </Pressable>\n ) : null}\n {item.actionUrl ? (\n <Pressable accessibilityRole=\"button\" onPress={() => void actions.handleActionPress(item)}>\n <Text style={[styles.actionText, { color: accentColor }]}>{item.actionLabel ?? \"Open\"}</Text>\n </Pressable>\n ) : null}\n </View>\n </View>\n );\n}\n\nexport function BeeperInboxList({\n style,\n contentContainerStyle,\n}: {\n style?: StyleProp<ViewStyle>;\n contentContainerStyle?: StyleProp<ViewStyle>;\n}) {\n const { core, state } = useNativeInbox();\n if (state.loading && state.items.length === 0) {\n return <ActivityIndicator accessibilityLabel=\"Loading notifications\" style={styles.loader} />;\n }\n if (state.errorMessage && state.items.length === 0) {\n return <Text accessibilityRole=\"alert\" style={styles.error}>{state.errorMessage}</Text>;\n }\n if (state.items.length === 0) {\n return <Text style={styles.empty}>No notifications yet.</Text>;\n }\n\n const renderItem = ({ item }: ListRenderItemInfo<InboxItemRecord>) => <BeeperInboxItem item={item} />;\n return (\n <FlatList\n accessibilityLabel=\"Notifications\"\n data={state.items}\n keyExtractor={(item) => item._id}\n renderItem={renderItem}\n style={style}\n contentContainerStyle={contentContainerStyle}\n onEndReached={() => {\n if (state.hasMore) {\n void core.loadMore().catch(() => undefined);\n }\n }}\n onEndReachedThreshold={0.5}\n ListFooterComponent={\n state.loadingMore ? (\n <ActivityIndicator accessibilityLabel=\"Loading more notifications\" style={styles.loader} />\n ) : null\n }\n />\n );\n}\n\nexport function BeeperInboxPanel({\n title = \"Notifications\",\n style,\n}: {\n title?: string;\n style?: StyleProp<ViewStyle>;\n}) {\n const { core, state, accentColor } = useNativeInbox();\n return (\n <View style={[styles.panel, style]}>\n <View style={styles.header}>\n <View>\n <Text style={styles.title}>{title}</Text>\n <Text style={styles.subtitle} accessibilityLiveRegion=\"polite\">\n {state.unreadCount} unread\n </Text>\n </View>\n {state.unreadCount > 0 ? (\n <Pressable accessibilityRole=\"button\" onPress={() => void core.markAllRead()}>\n <Text style={[styles.actionText, { color: accentColor }]}>Mark all read</Text>\n </Pressable>\n ) : null}\n </View>\n <BeeperInboxList contentContainerStyle={styles.listContent} />\n </View>\n );\n}\n\nexport function BeeperInboxRefreshControl() {\n const { core, state } = useNativeInbox();\n return (\n <Pressable accessibilityRole=\"button\" onPress={() => void core.refresh({ silent: true })}>\n <Text style={styles.actionText}>{state.refreshing ? \"Refreshing...\" : \"Refresh\"}</Text>\n </Pressable>\n );\n}\n\nconst styles = StyleSheet.create({\n panel: {\n backgroundColor: \"#fffaf5\",\n borderColor: \"#eadbcc\",\n borderRadius: 14,\n borderWidth: 1,\n padding: 14,\n },\n header: {\n alignItems: \"center\",\n flexDirection: \"row\",\n justifyContent: \"space-between\",\n marginBottom: 12,\n },\n title: { color: \"#2b221d\", fontSize: 18, fontWeight: \"700\" },\n subtitle: { color: \"#7d685d\", fontSize: 13, marginTop: 2 },\n listContent: { gap: 8 },\n item: { backgroundColor: \"#fffdf9\", borderColor: \"#eadbcc\", borderRadius: 10, borderWidth: 1, padding: 14 },\n itemResolved: { opacity: 0.65 },\n itemTitle: { color: \"#2b221d\", fontSize: 15, fontWeight: \"700\", marginBottom: 5 },\n itemHeader: { alignItems: \"center\", flexDirection: \"row\", gap: 10 },\n itemHeaderTitle: { flexShrink: 1 },\n itemAvatar: { backgroundColor: \"#eadbcc\", borderRadius: 16, height: 32, marginBottom: 5, width: 32 },\n itemImage: { aspectRatio: 16 / 9, backgroundColor: \"#eadbcc\", borderRadius: 8, marginTop: 10, width: \"100%\" },\n itemBody: { color: \"#4e3c34\", fontSize: 14, lineHeight: 21 },\n itemFooter: { alignItems: \"center\", flexDirection: \"row\", flexWrap: \"wrap\", gap: 12, marginTop: 10 },\n itemDate: { color: \"#7d685d\", flex: 1, fontSize: 12 },\n actionText: { fontSize: 13, fontWeight: \"700\", paddingVertical: 8 },\n badge: { alignItems: \"center\", borderRadius: 999, justifyContent: \"center\", minHeight: 24, minWidth: 24, paddingHorizontal: 7 },\n badgeText: { color: \"#fff\", fontSize: 12, fontWeight: \"700\" },\n loader: { padding: 24 },\n empty: { color: \"#7d685d\", padding: 24, textAlign: \"center\" },\n error: { color: \"#a43d28\", padding: 24, textAlign: \"center\" },\n});\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "beeper-inbox-native",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -19,7 +19,8 @@
19
19
  ],
20
20
  "sideEffects": false,
21
21
  "dependencies": {
22
- "beeper-sdk": "^0.2.0"
22
+ "convex": "^1.32.0",
23
+ "beeper-sdk": "^0.3.0"
23
24
  },
24
25
  "peerDependencies": {
25
26
  "react": ">=18",