beeper-inbox-react 0.3.0 → 0.4.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/dist/index.js CHANGED
@@ -27,6 +27,37 @@ const DEFAULT_CONFIG = {
27
27
  */
28
28
  const DEFAULT_BEEPER_WIDGET_API_BASE_URL = "https://exciting-guineapig-440.convex.site";
29
29
  const Ctx = createContext(null);
30
+ /**
31
+ * Registers a component that reads `items`. The list is loaded (and kept live)
32
+ * only while the panel is open or something has registered; otherwise only the
33
+ * unread counts are, which costs a counter read instead of a page of items.
34
+ */
35
+ const ItemsDemandCtx = createContext(null);
36
+ /** Items per page: the first page, and each "Show older". */
37
+ const INBOX_PAGE_SIZE = 20;
38
+ /**
39
+ * A fresh newest page followed by already loaded items older than it, so a
40
+ * live update doesn't drop pages fetched with "Show older".
41
+ */
42
+ function mergeOlderItems(head, previous) {
43
+ const last = head[head.length - 1];
44
+ if (!last) {
45
+ return previous;
46
+ }
47
+ const headIds = new Set(head.map((item) => item._id));
48
+ return [
49
+ ...head,
50
+ ...previous.filter((item) => !headIds.has(item._id) && item.createdAt <= last.createdAt),
51
+ ];
52
+ }
53
+ /** Wait before retrying a failed subscription; polling covers the gap. */
54
+ const REALTIME_RETRY_MS = 60_000;
55
+ /** Polling doubles its interval per consecutive failure, up to this. */
56
+ const MAX_POLL_BACKOFF_MS = 5 * 60_000;
57
+ /** True when the page is in the background. Always false outside the DOM. */
58
+ function isPageHidden() {
59
+ return typeof document !== "undefined" && document.hidden === true;
60
+ }
30
61
  function parseTokenExpiryMs(token) {
31
62
  const segments = token.split(".");
32
63
  const payload = segments.length >= 3 ? segments[1] : segments[0];
@@ -57,6 +88,73 @@ function parseTokenExpiryMs(token) {
57
88
  function isSessionExpiringSoon(expiresAt, now = Date.now()) {
58
89
  return Boolean(expiresAt && expiresAt - now <= 30_000);
59
90
  }
91
+ /**
92
+ * How long a fetched widget config is reused by later loads in the tab. Config
93
+ * is the dashboard's look-and-feel settings, so a few minutes' lag is fine, and
94
+ * it saves one request (and its rate-limit write) per page load.
95
+ */
96
+ const CONFIG_CACHE_MS = 10 * 60_000;
97
+ function storedConfigKey(baseUrl, projectId) {
98
+ return `beeper:widget-config:${baseUrl}:${projectId}`;
99
+ }
100
+ function readStoredConfig(baseUrl, projectId) {
101
+ try {
102
+ if (typeof window === "undefined" || !window.sessionStorage) {
103
+ return undefined;
104
+ }
105
+ const raw = window.sessionStorage.getItem(storedConfigKey(baseUrl, projectId));
106
+ const stored = raw ? JSON.parse(raw) : null;
107
+ if (!stored?.config || !stored.savedAt || Date.now() - stored.savedAt > CONFIG_CACHE_MS) {
108
+ return undefined;
109
+ }
110
+ return stored.config;
111
+ }
112
+ catch {
113
+ return undefined;
114
+ }
115
+ }
116
+ function writeStoredConfig(baseUrl, projectId, config) {
117
+ try {
118
+ if (typeof window !== "undefined" && window.sessionStorage) {
119
+ window.sessionStorage.setItem(storedConfigKey(baseUrl, projectId), JSON.stringify({ savedAt: Date.now(), config }));
120
+ }
121
+ }
122
+ catch {
123
+ // Storage full or blocked: the next load fetches it again.
124
+ }
125
+ }
126
+ function storedSessionKey(projectId, subscriberId) {
127
+ return `beeper:widget-session:${projectId}:${subscriberId}`;
128
+ }
129
+ /** A session minted earlier in this tab, if it is still good for a while. */
130
+ function readStoredSession(projectId, subscriberId) {
131
+ try {
132
+ if (typeof window === "undefined" || !window.sessionStorage) {
133
+ return "";
134
+ }
135
+ const key = storedSessionKey(projectId, subscriberId);
136
+ const token = window.sessionStorage.getItem(key) ?? "";
137
+ const expiresAt = parseTokenExpiryMs(token);
138
+ if (!token || !expiresAt || isSessionExpiringSoon(expiresAt)) {
139
+ window.sessionStorage.removeItem(key);
140
+ return "";
141
+ }
142
+ return token;
143
+ }
144
+ catch {
145
+ return "";
146
+ }
147
+ }
148
+ function writeStoredSession(projectId, subscriberId, token) {
149
+ try {
150
+ if (typeof window !== "undefined" && window.sessionStorage) {
151
+ window.sessionStorage.setItem(storedSessionKey(projectId, subscriberId), token);
152
+ }
153
+ }
154
+ catch {
155
+ // Storage full or blocked: the next load just mints a new session.
156
+ }
157
+ }
60
158
  function resolveTheme(theme) {
61
159
  if (theme === "system") {
62
160
  if (typeof window === "undefined") {
@@ -167,9 +265,23 @@ function buildKindsQuery(activeKinds, unreadKinds) {
167
265
  ...unreadKinds.map((kind) => `&unreadKind=${encodeURIComponent(kind)}`),
168
266
  ].join("");
169
267
  }
170
- export function BeeperInboxProvider({ baseUrl = DEFAULT_BEEPER_WIDGET_API_BASE_URL, projectId, publishableKey, sessionToken, getSessionToken, sessionEndpoint = "/api/beeper/widget-session", sessionRequestHeaders, subscriber, theme = "system", customization, push, actionLinkTarget = "auto", onActionClick, pollIntervalMs = 15000, onEvent, tabs, defaultTab, children, }) {
268
+ export function BeeperInboxProvider({ baseUrl = DEFAULT_BEEPER_WIDGET_API_BASE_URL, projectId, publishableKey, sessionToken, getSessionToken, sessionEndpoint = "/api/beeper/widget-session", sessionRequestHeaders, persistSession = true, subscriber, theme = "system", customization, push, actionLinkTarget = "auto", onActionClick, pollIntervalMs = 15000, onEvent, tabs, defaultTab, children, }) {
171
269
  const [open, setOpen] = useState(false);
172
270
  const [items, setItems] = useState([]);
271
+ const [hasMore, setHasMore] = useState(false);
272
+ const [loadingMore, setLoadingMore] = useState(false);
273
+ /** Where the next "Show older" page starts. */
274
+ const cursorRef = useRef(null);
275
+ /** Set once "Show older" has appended a page that live updates must keep. */
276
+ const hasOlderPagesRef = useRef(false);
277
+ const loadMoreRef = useRef(null);
278
+ const [itemsDemand, setItemsDemand] = useState(0);
279
+ const registerItemsDemand = useCallback(() => {
280
+ setItemsDemand((count) => count + 1);
281
+ return () => setItemsDemand((count) => count - 1);
282
+ }, []);
283
+ // The list is only loaded while something shows it; otherwise only counts.
284
+ const wantsItems = open || itemsDemand > 0;
173
285
  const [unreadCount, setUnreadCount] = useState(0);
174
286
  const [unreadByKind, setUnreadByKind] = useState({});
175
287
  // Keyed by value so an inline `tabs={[...]}` doesn't refetch on every render.
@@ -185,10 +297,13 @@ export function BeeperInboxProvider({ baseUrl = DEFAULT_BEEPER_WIDGET_API_BASE_U
185
297
  const [errorMessage, setErrorMessage] = useState(null);
186
298
  const [serverConfig, setServerConfig] = useState(DEFAULT_CONFIG);
187
299
  const [realtimeConvexUrl, setRealtimeConvexUrl] = useState(null);
188
- const [runtimeSessionToken, setRuntimeSessionToken] = useState(sessionToken ?? "");
189
- const [runtimeSessionExpiresAt, setRuntimeSessionExpiresAt] = useState(parseTokenExpiryMs(sessionToken ?? ""));
190
- const runtimeSessionTokenRef = useRef(sessionToken ?? "");
191
- const runtimeSessionExpiresAtRef = useRef(parseTokenExpiryMs(sessionToken ?? ""));
300
+ // A passed token wins; otherwise one minted on an earlier load of this tab.
301
+ const [initialSessionToken] = useState(() => sessionToken ??
302
+ (persistSession ? readStoredSession(projectId, subscriber.subscriberId) : ""));
303
+ const [runtimeSessionToken, setRuntimeSessionToken] = useState(initialSessionToken);
304
+ const [runtimeSessionExpiresAt, setRuntimeSessionExpiresAt] = useState(parseTokenExpiryMs(initialSessionToken));
305
+ const runtimeSessionTokenRef = useRef(initialSessionToken);
306
+ const runtimeSessionExpiresAtRef = useRef(parseTokenExpiryMs(initialSessionToken));
192
307
  const [convexClient, setConvexClient] = useState(null);
193
308
  const convexClientRef = useRef(null);
194
309
  const [reconnectNonce, setReconnectNonce] = useState(0);
@@ -196,19 +311,42 @@ export function BeeperInboxProvider({ baseUrl = DEFAULT_BEEPER_WIDGET_API_BASE_U
196
311
  const eventRef = useRef(onEvent);
197
312
  const triggerRef = useRef(null);
198
313
  const hasLoadedOnceRef = useRef(false);
314
+ /** Set once the config request settles, so we know whether realtime will deliver. */
315
+ const [configResolved, setConfigResolved] = useState(false);
316
+ /** The subscription errored; polling covers until it delivers again. */
317
+ const [realtimeFailed, setRealtimeFailed] = useState(false);
318
+ /** True while a subscription is delivering; writes then skip the re-fetch. */
319
+ const realtimeLiveRef = useRef(false);
199
320
  useEffect(() => {
200
321
  eventRef.current = onEvent;
201
322
  }, [onEvent]);
323
+ // Read through refs so an inline `subscriber={{ ... }}`, headers object or
324
+ // `getSessionToken` arrow doesn't rebuild every callback, and resubscribe or
325
+ // refetch, on each render. Only the subscriber's id changes what we load.
326
+ const subscriberRef = useRef(subscriber);
327
+ const getSessionTokenRef = useRef(getSessionToken);
328
+ const sessionRequestHeadersRef = useRef(sessionRequestHeaders);
329
+ useEffect(() => {
330
+ subscriberRef.current = subscriber;
331
+ getSessionTokenRef.current = getSessionToken;
332
+ sessionRequestHeadersRef.current = sessionRequestHeaders;
333
+ }, [getSessionToken, sessionRequestHeaders, subscriber]);
334
+ const hasGetSessionToken = Boolean(getSessionToken);
335
+ const canRefreshSession = hasGetSessionToken || Boolean(sessionEndpoint);
202
336
  const emitEvent = useCallback((event) => {
203
337
  eventRef.current?.(event);
204
338
  }, []);
205
339
  useEffect(() => {
206
- setRuntimeSessionToken(sessionToken ?? "");
207
- setRuntimeSessionExpiresAt(parseTokenExpiryMs(sessionToken ?? ""));
208
- runtimeSessionTokenRef.current = sessionToken ?? "";
209
- runtimeSessionExpiresAtRef.current = parseTokenExpiryMs(sessionToken ?? "");
210
- }, [sessionToken]);
340
+ const next = sessionToken ??
341
+ (persistSession ? readStoredSession(projectId, subscriber.subscriberId) : "");
342
+ setRuntimeSessionToken(next);
343
+ setRuntimeSessionExpiresAt(parseTokenExpiryMs(next));
344
+ runtimeSessionTokenRef.current = next;
345
+ runtimeSessionExpiresAtRef.current = parseTokenExpiryMs(next);
346
+ }, [persistSession, projectId, sessionToken, subscriber.subscriberId]);
211
347
  const resolveSessionToken = useCallback(async () => {
348
+ const subscriber = subscriberRef.current;
349
+ const getSessionToken = getSessionTokenRef.current;
212
350
  if (getSessionToken) {
213
351
  return getSessionToken(subscriber);
214
352
  }
@@ -221,7 +359,7 @@ export function BeeperInboxProvider({ baseUrl = DEFAULT_BEEPER_WIDGET_API_BASE_U
221
359
  method: "POST",
222
360
  headers: {
223
361
  "content-type": "application/json",
224
- ...(sessionRequestHeaders ?? {}),
362
+ ...(sessionRequestHeadersRef.current ?? {}),
225
363
  },
226
364
  body: JSON.stringify({
227
365
  projectId,
@@ -240,7 +378,7 @@ export function BeeperInboxProvider({ baseUrl = DEFAULT_BEEPER_WIDGET_API_BASE_U
240
378
  throw new Error(payload?.error ?? "Failed to mint Beeper widget session token");
241
379
  }
242
380
  return token;
243
- }, [getSessionToken, projectId, sessionEndpoint, sessionRequestHeaders, subscriber]);
381
+ }, [projectId, sessionEndpoint]);
244
382
  const refreshSession = useCallback(async () => {
245
383
  if (sessionRefreshRef.current) {
246
384
  return sessionRefreshRef.current;
@@ -254,6 +392,9 @@ export function BeeperInboxProvider({ baseUrl = DEFAULT_BEEPER_WIDGET_API_BASE_U
254
392
  .then((next) => {
255
393
  setRuntimeSessionToken(next);
256
394
  runtimeSessionTokenRef.current = next;
395
+ if (persistSession && !sessionToken) {
396
+ writeStoredSession(projectId, subscriber.subscriberId, next);
397
+ }
257
398
  const nextExpiresAt = parseTokenExpiryMs(next);
258
399
  setRuntimeSessionExpiresAt(nextExpiresAt);
259
400
  runtimeSessionExpiresAtRef.current = nextExpiresAt;
@@ -279,23 +420,28 @@ export function BeeperInboxProvider({ baseUrl = DEFAULT_BEEPER_WIDGET_API_BASE_U
279
420
  });
280
421
  sessionRefreshRef.current = request;
281
422
  return request;
282
- }, [emitEvent, projectId, resolveSessionToken, subscriber.subscriberId]);
423
+ }, [
424
+ emitEvent,
425
+ persistSession,
426
+ projectId,
427
+ resolveSessionToken,
428
+ sessionToken,
429
+ subscriber.subscriberId,
430
+ ]);
283
431
  const ensureSession = useCallback(async () => {
284
432
  const now = Date.now();
285
433
  const currentToken = runtimeSessionTokenRef.current;
286
434
  const currentExpiresAt = runtimeSessionExpiresAtRef.current;
287
435
  if (currentToken) {
288
- const canRefresh = Boolean(getSessionToken) || Boolean(sessionEndpoint);
289
- if (isSessionExpiringSoon(currentExpiresAt, now) && canRefresh) {
436
+ if (isSessionExpiringSoon(currentExpiresAt, now) && canRefreshSession) {
290
437
  return refreshSession();
291
438
  }
292
439
  return currentToken;
293
440
  }
294
441
  return refreshSession();
295
442
  }, [
296
- getSessionToken,
443
+ canRefreshSession,
297
444
  refreshSession,
298
- sessionEndpoint,
299
445
  ]);
300
446
  const fetchJson = useCallback(async (method, path, body, allowSessionRefresh = true, sessionTokenOverride) => {
301
447
  let sessionHeaderToken = sessionTokenOverride ?? runtimeSessionTokenRef.current;
@@ -343,7 +489,7 @@ export function BeeperInboxProvider({ baseUrl = DEFAULT_BEEPER_WIDGET_API_BASE_U
343
489
  });
344
490
  if (allowSessionRefresh &&
345
491
  response.status === 401 &&
346
- (getSessionToken || sessionEndpoint)) {
492
+ canRefreshSession) {
347
493
  const nextToken = await refreshSession();
348
494
  return fetchJson(method, path, body, false, nextToken);
349
495
  }
@@ -352,17 +498,20 @@ export function BeeperInboxProvider({ baseUrl = DEFAULT_BEEPER_WIDGET_API_BASE_U
352
498
  return payload.data;
353
499
  }, [
354
500
  baseUrl,
501
+ canRefreshSession,
355
502
  emitEvent,
356
- getSessionToken,
357
503
  projectId,
358
504
  publishableKey,
359
505
  refreshSession,
360
506
  ensureSession,
361
- sessionEndpoint,
362
507
  subscriber.subscriberId,
363
508
  ]);
364
509
  /** Config is public (publishable key only); stable deps avoid refetch on every session token change. */
365
510
  const fetchWidgetConfigDocument = useCallback(async () => {
511
+ const stored = readStoredConfig(baseUrl, projectId);
512
+ if (stored) {
513
+ return stored;
514
+ }
366
515
  const url = `${baseUrl.replace(/\/$/, "")}/api/v1/projects/${projectId}/widget/config`;
367
516
  const response = await fetch(url, {
368
517
  method: "GET",
@@ -382,8 +531,31 @@ export function BeeperInboxProvider({ baseUrl = DEFAULT_BEEPER_WIDGET_API_BASE_U
382
531
  if (!response.ok) {
383
532
  return undefined;
384
533
  }
534
+ if (payload.data) {
535
+ writeStoredConfig(baseUrl, projectId, payload.data);
536
+ }
385
537
  return payload.data;
386
538
  }, [baseUrl, projectId, publishableKey]);
539
+ /** Applies a fresh newest page, from a fetch or a subscription. */
540
+ const applyHead = useCallback((inbox) => {
541
+ const head = (inbox.items ?? []).map(normalizeInboxItem);
542
+ if (hasOlderPagesRef.current) {
543
+ setItems((current) => mergeOlderItems(head, current));
544
+ }
545
+ else {
546
+ cursorRef.current = inbox.nextCursor ?? null;
547
+ setItems(head);
548
+ }
549
+ setHasMore(cursorRef.current !== null);
550
+ setUnreadCount(Number(inbox.unreadCount ?? 0));
551
+ setUnreadByKind(inbox.unreadByKind ?? {});
552
+ hasLoadedOnceRef.current = true;
553
+ }, []);
554
+ const applyUnread = useCallback((result) => {
555
+ setUnreadCount(Number(result.unreadCount ?? 0));
556
+ setUnreadByKind(result.byKind ?? {});
557
+ }, []);
558
+ const unreadQuery = useMemo(() => unreadKinds.map((kind) => `&kind=${encodeURIComponent(kind)}`).join(""), [unreadKinds]);
387
559
  const refresh = useCallback(async (options) => {
388
560
  const silent = options?.silent ?? false;
389
561
  if (silent) {
@@ -394,11 +566,12 @@ export function BeeperInboxProvider({ baseUrl = DEFAULT_BEEPER_WIDGET_API_BASE_U
394
566
  }
395
567
  try {
396
568
  await ensureSession();
397
- const inbox = await fetchJson("GET", `/widget/inbox?subscriberId=${encodeURIComponent(subscriber.subscriberId)}&limit=50${kindsQuery}`);
398
- setItems((inbox.items ?? []).map(normalizeInboxItem));
399
- setUnreadCount(inbox.unreadCount ?? 0);
400
- setUnreadByKind(inbox.unreadByKind ?? {});
401
- hasLoadedOnceRef.current = true;
569
+ const subscriberQuery = `subscriberId=${encodeURIComponent(subscriber.subscriberId)}`;
570
+ if (!wantsItems) {
571
+ applyUnread(await fetchJson("GET", `/widget/unread?${subscriberQuery}${unreadQuery}`));
572
+ return;
573
+ }
574
+ applyHead(await fetchJson("GET", `/widget/inbox?${subscriberQuery}&limit=${INBOX_PAGE_SIZE}${kindsQuery}`));
402
575
  }
403
576
  finally {
404
577
  if (silent) {
@@ -408,7 +581,47 @@ export function BeeperInboxProvider({ baseUrl = DEFAULT_BEEPER_WIDGET_API_BASE_U
408
581
  setLoading(false);
409
582
  }
410
583
  }
411
- }, [ensureSession, fetchJson, kindsQuery, subscriber.subscriberId]);
584
+ }, [
585
+ applyHead,
586
+ applyUnread,
587
+ ensureSession,
588
+ fetchJson,
589
+ kindsQuery,
590
+ subscriber.subscriberId,
591
+ unreadQuery,
592
+ wantsItems,
593
+ ]);
594
+ /** Appends the next older page. */
595
+ const loadMore = useCallback(async () => {
596
+ const cursor = cursorRef.current;
597
+ if (loadMoreRef.current || !cursor) {
598
+ return loadMoreRef.current ?? undefined;
599
+ }
600
+ setLoadingMore(true);
601
+ const request = (async () => {
602
+ const page = await fetchJson("GET", `/widget/inbox?subscriberId=${encodeURIComponent(subscriber.subscriberId)}&limit=${INBOX_PAGE_SIZE}&cursor=${encodeURIComponent(cursor)}${kindsQuery}`);
603
+ hasOlderPagesRef.current = true;
604
+ cursorRef.current = page.nextCursor ?? null;
605
+ const older = (page.items ?? []).map(normalizeInboxItem);
606
+ setItems((current) => {
607
+ const seen = new Set(current.map((item) => item._id));
608
+ return [...current, ...older.filter((item) => !seen.has(item._id))];
609
+ });
610
+ setHasMore(cursorRef.current !== null);
611
+ })().finally(() => {
612
+ loadMoreRef.current = null;
613
+ setLoadingMore(false);
614
+ });
615
+ loadMoreRef.current = request;
616
+ return request;
617
+ }, [fetchJson, kindsQuery, subscriber.subscriberId]);
618
+ // Older pages belong to one view of the list: drop them when it closes or
619
+ // the tab changes, so the next view starts from a fresh first page.
620
+ useEffect(() => {
621
+ hasOlderPagesRef.current = false;
622
+ cursorRef.current = null;
623
+ setHasMore(false);
624
+ }, [wantsItems, kindsQuery]);
412
625
  /** Unread counters after `item` becomes read, if it was unread. */
413
626
  const decrementUnread = useCallback((item) => {
414
627
  if (!item || item.readAt) {
@@ -433,7 +646,10 @@ export function BeeperInboxProvider({ baseUrl = DEFAULT_BEEPER_WIDGET_API_BASE_U
433
646
  subscriberId: subscriber.subscriberId,
434
647
  inboxItemIds: [inboxItemId],
435
648
  });
436
- await refresh({ silent: true });
649
+ // A live subscription pushes the write's result, so only a poller re-fetches.
650
+ if (!realtimeLiveRef.current) {
651
+ await refresh({ silent: true });
652
+ }
437
653
  }
438
654
  catch (error) {
439
655
  setItems(previousItems);
@@ -466,7 +682,9 @@ export function BeeperInboxProvider({ baseUrl = DEFAULT_BEEPER_WIDGET_API_BASE_U
466
682
  subscriberId: subscriber.subscriberId,
467
683
  inboxItemIds: [inboxItemId],
468
684
  });
469
- await refresh({ silent: true });
685
+ if (!realtimeLiveRef.current) {
686
+ await refresh({ silent: true });
687
+ }
470
688
  }
471
689
  catch (error) {
472
690
  setItems(previousItems);
@@ -509,7 +727,9 @@ export function BeeperInboxProvider({ baseUrl = DEFAULT_BEEPER_WIDGET_API_BASE_U
509
727
  await fetchJson("POST", "/widget/read-all", {
510
728
  subscriberId: subscriber.subscriberId,
511
729
  });
512
- await refresh({ silent: true });
730
+ if (!realtimeLiveRef.current) {
731
+ await refresh({ silent: true });
732
+ }
513
733
  }
514
734
  catch (error) {
515
735
  setItems(previousItems);
@@ -592,19 +812,18 @@ export function BeeperInboxProvider({ baseUrl = DEFAULT_BEEPER_WIDGET_API_BASE_U
592
812
  // Bump nonce to force the subscribe effect to re-run and re-establish
593
813
  // the Convex realtime subscription (a REST refresh alone isn't enough).
594
814
  setReconnectNonce((n) => n + 1);
595
- if (getSessionToken || sessionEndpoint) {
815
+ if (canRefreshSession) {
596
816
  await refreshSession();
597
817
  }
598
818
  else {
599
819
  await ensureSession();
600
820
  }
601
821
  }, [
822
+ canRefreshSession,
602
823
  emitEvent,
603
824
  ensureSession,
604
- getSessionToken,
605
825
  projectId,
606
826
  refreshSession,
607
- sessionEndpoint,
608
827
  subscriber.subscriberId,
609
828
  ]);
610
829
  useEffect(() => {
@@ -623,6 +842,11 @@ export function BeeperInboxProvider({ baseUrl = DEFAULT_BEEPER_WIDGET_API_BASE_U
623
842
  setServerConfig(DEFAULT_CONFIG);
624
843
  }
625
844
  }
845
+ finally {
846
+ if (!cancelled) {
847
+ setConfigResolved(true);
848
+ }
849
+ }
626
850
  }
627
851
  void loadConfig();
628
852
  return () => {
@@ -630,7 +854,7 @@ export function BeeperInboxProvider({ baseUrl = DEFAULT_BEEPER_WIDGET_API_BASE_U
630
854
  };
631
855
  }, [fetchWidgetConfigDocument]);
632
856
  useEffect(() => {
633
- if (!runtimeSessionToken || !runtimeSessionExpiresAt || !getSessionToken) {
857
+ if (!runtimeSessionToken || !runtimeSessionExpiresAt || !hasGetSessionToken) {
634
858
  return;
635
859
  }
636
860
  const refreshInMs = Math.max(runtimeSessionExpiresAt - Date.now() - 60_000, 1_000);
@@ -638,23 +862,40 @@ export function BeeperInboxProvider({ baseUrl = DEFAULT_BEEPER_WIDGET_API_BASE_U
638
862
  refreshSession().catch(() => undefined);
639
863
  }, refreshInMs);
640
864
  return () => clearTimeout(timer);
641
- }, [getSessionToken, refreshSession, runtimeSessionExpiresAt, runtimeSessionToken]);
865
+ }, [hasGetSessionToken, refreshSession, runtimeSessionExpiresAt, runtimeSessionToken]);
866
+ // Keyed by value so an inline `push={{ ... }}` doesn't re-register the device
867
+ // on every render.
868
+ const pushToken = push?.token;
869
+ const pushPlatform = push?.platform;
870
+ const pushDeviceLabel = push?.deviceLabel;
871
+ const pushMetadataKey = push?.metadata ? JSON.stringify(push.metadata) : "";
872
+ const pushAutoRegister = push?.autoRegister !== false;
873
+ const pushAutoUnregister = Boolean(push?.autoUnregister);
642
874
  useEffect(() => {
643
- if (!push?.token || push.autoRegister === false) {
875
+ if (!pushToken || !pushAutoRegister) {
644
876
  return;
645
877
  }
646
- registerPushToken(push.token, {
647
- platform: push.platform,
648
- deviceLabel: push.deviceLabel,
649
- metadata: push.metadata,
878
+ registerPushToken(pushToken, {
879
+ platform: pushPlatform,
880
+ deviceLabel: pushDeviceLabel,
881
+ metadata: pushMetadataKey ? JSON.parse(pushMetadataKey) : undefined,
650
882
  }).catch(() => undefined);
651
- if (!push.autoUnregister) {
883
+ if (!pushAutoUnregister) {
652
884
  return;
653
885
  }
654
886
  return () => {
655
- unregisterPushToken(push.token ?? "").catch(() => undefined);
887
+ unregisterPushToken(pushToken).catch(() => undefined);
656
888
  };
657
- }, [push, registerPushToken, unregisterPushToken]);
889
+ }, [
890
+ pushAutoRegister,
891
+ pushAutoUnregister,
892
+ pushDeviceLabel,
893
+ pushMetadataKey,
894
+ pushPlatform,
895
+ pushToken,
896
+ registerPushToken,
897
+ unregisterPushToken,
898
+ ]);
658
899
  useEffect(() => {
659
900
  if (!realtimeConvexUrl) {
660
901
  return;
@@ -676,6 +917,7 @@ export function BeeperInboxProvider({ baseUrl = DEFAULT_BEEPER_WIDGET_API_BASE_U
676
917
  }
677
918
  let disposed = false;
678
919
  let retryTimer = null;
920
+ let firstResultTimer = null;
679
921
  let retryAttempt = 0;
680
922
  let unsubscribe = null;
681
923
  const clearSubscription = () => {
@@ -687,8 +929,42 @@ export function BeeperInboxProvider({ baseUrl = DEFAULT_BEEPER_WIDGET_API_BASE_U
687
929
  }
688
930
  unsubscribe = null;
689
931
  };
932
+ // The subscription carries the session token in its args, so an expired
933
+ // token surfaces here rather than as a 401. Refresh it once and resubscribe;
934
+ // anything else hands updates to polling until a later retry delivers.
935
+ function handleSubscriptionError(error, afterSessionRefresh) {
936
+ clearSubscription();
937
+ realtimeLiveRef.current = false;
938
+ if (!afterSessionRefresh &&
939
+ canRefreshSession &&
940
+ /session|token|expired|invalid/i.test(error.message)) {
941
+ subscribe(true).catch(() => undefined);
942
+ return;
943
+ }
944
+ setLoading(false);
945
+ setRefreshing(false);
946
+ setConnectionState("polling");
947
+ setRealtimeFailed(true);
948
+ emitEvent({
949
+ type: "realtime.error",
950
+ projectId,
951
+ subscriberId: subscriber.subscriberId,
952
+ message: error.message,
953
+ });
954
+ retryAttempt += 1;
955
+ emitEvent({
956
+ type: "realtime.retry.scheduled",
957
+ projectId,
958
+ subscriberId: subscriber.subscriberId,
959
+ attempt: retryAttempt,
960
+ retryInMs: REALTIME_RETRY_MS,
961
+ });
962
+ retryTimer = setTimeout(() => {
963
+ subscribe().catch(() => undefined);
964
+ }, REALTIME_RETRY_MS);
965
+ }
690
966
  async function subscribe(forceRefreshSession = false) {
691
- if (!hasLoadedOnceRef.current) {
967
+ if (wantsItems && !hasLoadedOnceRef.current) {
692
968
  setLoading(true);
693
969
  }
694
970
  setConnectionState("connecting");
@@ -703,23 +979,39 @@ export function BeeperInboxProvider({ baseUrl = DEFAULT_BEEPER_WIDGET_API_BASE_U
703
979
  return;
704
980
  }
705
981
  clearSubscription();
706
- const subscription = convexClientRef.current.onUpdate("widgetInbox:list", {
707
- projectId,
708
- sessionToken: token,
709
- subscriberId: subscriber.subscriberId,
710
- limit: 50,
711
- ...(activeKinds.length ? { kinds: activeKinds } : {}),
712
- ...(unreadKinds.length ? { unreadKinds } : {}),
713
- }, (inbox) => {
982
+ // The list while something shows it, otherwise only the unread counts.
983
+ const subscription = convexClientRef.current.onUpdate((wantsItems ? "widgetInbox:list" : "widgetInbox:unreadCount"), (wantsItems
984
+ ? {
985
+ projectId,
986
+ sessionToken: token,
987
+ subscriberId: subscriber.subscriberId,
988
+ limit: INBOX_PAGE_SIZE,
989
+ ...(activeKinds.length ? { kinds: activeKinds } : {}),
990
+ ...(unreadKinds.length ? { unreadKinds } : {}),
991
+ }
992
+ : {
993
+ projectId,
994
+ sessionToken: token,
995
+ subscriberId: subscriber.subscriberId,
996
+ ...(unreadKinds.length ? { kinds: unreadKinds } : {}),
997
+ }), (result) => {
714
998
  if (disposed) {
715
999
  return;
716
1000
  }
717
- setItems((inbox?.items ?? []).map(normalizeInboxItem));
718
- setUnreadCount(Number(inbox?.unreadCount ?? 0));
719
- setUnreadByKind(inbox?.unreadByKind ?? {});
720
- setLoading(false);
1001
+ if (firstResultTimer) {
1002
+ clearTimeout(firstResultTimer);
1003
+ firstResultTimer = null;
1004
+ }
1005
+ realtimeLiveRef.current = true;
1006
+ setRealtimeFailed(false);
1007
+ if (wantsItems) {
1008
+ applyHead(result ?? {});
1009
+ setLoading(false);
1010
+ }
1011
+ else {
1012
+ applyUnread(result ?? {});
1013
+ }
721
1014
  setRefreshing(false);
722
- hasLoadedOnceRef.current = true;
723
1015
  setConnectionState("live");
724
1016
  setErrorMessage(null);
725
1017
  emitEvent({
@@ -727,9 +1019,23 @@ export function BeeperInboxProvider({ baseUrl = DEFAULT_BEEPER_WIDGET_API_BASE_U
727
1019
  projectId,
728
1020
  subscriberId: subscriber.subscriberId,
729
1021
  });
1022
+ }, (error) => {
1023
+ if (!disposed) {
1024
+ handleSubscriptionError(error, forceRefreshSession);
1025
+ }
730
1026
  });
731
1027
  unsubscribe = subscription;
732
1028
  retryAttempt = 0;
1029
+ // Nothing fetches over HTTP while a subscription is expected to deliver,
1030
+ // so if it stays silent (e.g. WebSockets blocked) let polling take over.
1031
+ if (!realtimeLiveRef.current && !firstResultTimer) {
1032
+ firstResultTimer = setTimeout(() => {
1033
+ firstResultTimer = null;
1034
+ if (!disposed && !realtimeLiveRef.current) {
1035
+ setRealtimeFailed(true);
1036
+ }
1037
+ }, Math.max(pollIntervalMs, 5_000));
1038
+ }
733
1039
  }
734
1040
  catch (error) {
735
1041
  if (disposed) {
@@ -737,7 +1043,7 @@ export function BeeperInboxProvider({ baseUrl = DEFAULT_BEEPER_WIDGET_API_BASE_U
737
1043
  }
738
1044
  const message = error instanceof Error ? error.message : "Realtime connection failed";
739
1045
  if (!forceRefreshSession &&
740
- (getSessionToken || sessionEndpoint) &&
1046
+ canRefreshSession &&
741
1047
  /session|token|expired|invalid/i.test(message)) {
742
1048
  await subscribe(true);
743
1049
  return;
@@ -782,9 +1088,13 @@ export function BeeperInboxProvider({ baseUrl = DEFAULT_BEEPER_WIDGET_API_BASE_U
782
1088
  });
783
1089
  return () => {
784
1090
  disposed = true;
1091
+ realtimeLiveRef.current = false;
785
1092
  if (retryTimer) {
786
1093
  clearTimeout(retryTimer);
787
1094
  }
1095
+ if (firstResultTimer) {
1096
+ clearTimeout(firstResultTimer);
1097
+ }
788
1098
  if (typeof unsubscribe === "function") {
789
1099
  unsubscribe();
790
1100
  }
@@ -794,25 +1104,25 @@ export function BeeperInboxProvider({ baseUrl = DEFAULT_BEEPER_WIDGET_API_BASE_U
794
1104
  };
795
1105
  }, [
796
1106
  activeKinds,
1107
+ applyHead,
1108
+ applyUnread,
1109
+ canRefreshSession,
797
1110
  convexClient,
798
1111
  emitEvent,
799
1112
  ensureSession,
800
- getSessionToken,
1113
+ pollIntervalMs,
801
1114
  projectId,
802
1115
  reconnectNonce,
803
1116
  unreadKinds,
804
1117
  refreshSession,
805
- sessionEndpoint,
806
1118
  subscriber.subscriberId,
1119
+ wantsItems,
807
1120
  ]);
808
1121
  useEffect(() => {
809
- if (convexClient) {
810
- // Live updates are already active via Convex subscription.
811
- // Keep a low-frequency fallback refresh for resilience.
812
- const id = setInterval(() => {
813
- refresh({ silent: true }).catch(() => undefined);
814
- }, Math.max(pollIntervalMs, 60000));
815
- return () => clearInterval(id);
1122
+ // Until config settles we don't know whether a subscription will deliver,
1123
+ // and while one does, polling would only re-fetch what it pushes.
1124
+ if (!configResolved || (realtimeConvexUrl && !realtimeFailed)) {
1125
+ return;
816
1126
  }
817
1127
  setConnectionState("polling");
818
1128
  emitEvent({
@@ -820,12 +1130,65 @@ export function BeeperInboxProvider({ baseUrl = DEFAULT_BEEPER_WIDGET_API_BASE_U
820
1130
  projectId,
821
1131
  subscriberId: subscriber.subscriberId,
822
1132
  });
823
- refresh().catch(() => undefined);
824
- const id = setInterval(() => {
825
- refresh({ silent: true }).catch(() => undefined);
826
- }, pollIntervalMs);
827
- return () => clearInterval(id);
828
- }, [convexClient, emitEvent, pollIntervalMs, projectId, refresh, realtimeConvexUrl, subscriber.subscriberId]);
1133
+ let disposed = false;
1134
+ let timer = null;
1135
+ let failures = 0;
1136
+ // Waits double per consecutive failure, and stop while the page is hidden.
1137
+ const schedule = () => {
1138
+ if (timer) {
1139
+ clearTimeout(timer);
1140
+ timer = null;
1141
+ }
1142
+ if (disposed || isPageHidden()) {
1143
+ return;
1144
+ }
1145
+ const delayMs = Math.max(pollIntervalMs, Math.min(pollIntervalMs * 2 ** failures, MAX_POLL_BACKOFF_MS));
1146
+ timer = setTimeout(() => {
1147
+ timer = null;
1148
+ poll({ silent: true });
1149
+ }, delayMs);
1150
+ };
1151
+ const poll = (options) => {
1152
+ refresh(options)
1153
+ .then(() => {
1154
+ failures = 0;
1155
+ }, () => {
1156
+ failures += 1;
1157
+ })
1158
+ .finally(schedule);
1159
+ };
1160
+ // Catch up once when the page is shown again.
1161
+ const onVisibilityChange = () => {
1162
+ if (isPageHidden()) {
1163
+ schedule();
1164
+ }
1165
+ else {
1166
+ poll({ silent: true });
1167
+ }
1168
+ };
1169
+ poll();
1170
+ if (typeof document !== "undefined") {
1171
+ document.addEventListener("visibilitychange", onVisibilityChange);
1172
+ }
1173
+ return () => {
1174
+ disposed = true;
1175
+ if (timer) {
1176
+ clearTimeout(timer);
1177
+ }
1178
+ if (typeof document !== "undefined") {
1179
+ document.removeEventListener("visibilitychange", onVisibilityChange);
1180
+ }
1181
+ };
1182
+ }, [
1183
+ configResolved,
1184
+ emitEvent,
1185
+ pollIntervalMs,
1186
+ projectId,
1187
+ realtimeConvexUrl,
1188
+ realtimeFailed,
1189
+ refresh,
1190
+ subscriber.subscriberId,
1191
+ ]);
829
1192
  const effectiveConfig = useMemo(() => {
830
1193
  const merged = {
831
1194
  ...serverConfig,
@@ -859,6 +1222,9 @@ export function BeeperInboxProvider({ baseUrl = DEFAULT_BEEPER_WIDGET_API_BASE_U
859
1222
  archive,
860
1223
  unarchive,
861
1224
  unreadByKind,
1225
+ hasMore,
1226
+ loadingMore,
1227
+ loadMore,
862
1228
  tabs: stableTabs,
863
1229
  activeTab,
864
1230
  setActiveTab,
@@ -872,6 +1238,9 @@ export function BeeperInboxProvider({ baseUrl = DEFAULT_BEEPER_WIDGET_API_BASE_U
872
1238
  archive,
873
1239
  unarchive,
874
1240
  unreadByKind,
1241
+ hasMore,
1242
+ loadingMore,
1243
+ loadMore,
875
1244
  stableTabs,
876
1245
  activeTab,
877
1246
  setActiveTab,
@@ -892,20 +1261,36 @@ export function BeeperInboxProvider({ baseUrl = DEFAULT_BEEPER_WIDGET_API_BASE_U
892
1261
  handleActionClick,
893
1262
  effectiveConfig,
894
1263
  ]);
895
- return _jsx(Ctx.Provider, { value: value, children: children });
1264
+ return (_jsx(ItemsDemandCtx.Provider, { value: registerItemsDemand, children: _jsx(Ctx.Provider, { value: value, children: children }) }));
896
1265
  }
897
- export function useBeeperInbox() {
1266
+ function useInboxContext(hookName) {
898
1267
  const ctx = useContext(Ctx);
899
1268
  if (!ctx) {
900
- throw new Error("useBeeperInbox must be used inside BeeperInboxProvider");
1269
+ throw new Error(`${hookName} must be used inside BeeperInboxProvider`);
901
1270
  }
902
1271
  return ctx;
903
1272
  }
1273
+ /**
1274
+ * The inbox state and actions. A component using it keeps the item list
1275
+ * loaded while mounted (a custom panel needs `items`); for a badge alone, use
1276
+ * `useBeeperInboxUnreadCount`, which doesn't.
1277
+ */
1278
+ export function useBeeperInbox() {
1279
+ const ctx = useInboxContext("useBeeperInbox");
1280
+ const registerItemsDemand = useContext(ItemsDemandCtx);
1281
+ useEffect(() => registerItemsDemand?.(), [registerItemsDemand]);
1282
+ return ctx;
1283
+ }
1284
+ /** Unread counts only: doesn't make the provider load the item list. */
1285
+ export function useBeeperInboxUnreadCount() {
1286
+ const { unreadCount, unreadByKind, tabUnreadCount } = useInboxContext("useBeeperInboxUnreadCount");
1287
+ return { unreadCount, unreadByKind, tabUnreadCount };
1288
+ }
904
1289
  function BellGlyph({ size = 20, color = "currentColor", }) {
905
1290
  return (_jsxs("svg", { width: size, height: size, viewBox: "0 0 24 24", fill: "none", xmlns: "http://www.w3.org/2000/svg", "aria-hidden": true, children: [_jsx("path", { d: "M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9", stroke: color, strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }), _jsx("path", { d: "M13.73 21a2 2 0 0 1-3.46 0", stroke: color, strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" })] }));
906
1291
  }
907
1292
  export function BeeperInboxBell({ variant = "bell", label = "Inbox", className, style, "aria-label": ariaLabel = "Open notifications", renderTrigger, }) {
908
- const { open, setOpen, unreadCount, effectiveConfig, triggerRef } = useBeeperInbox();
1293
+ const { open, setOpen, unreadCount, effectiveConfig, triggerRef } = useInboxContext("BeeperInboxBell");
909
1294
  const toggle = () => setOpen(!open);
910
1295
  const fs = effectiveConfig.fontScale;
911
1296
  const triggerAriaLabel = unreadCount > 0 ? `${ariaLabel}, ${unreadCount} unread` : ariaLabel;
@@ -1010,7 +1395,7 @@ function ShadowContainer({ children }) {
1010
1395
  const PANEL_WIDTH = 384;
1011
1396
  const PANEL_ESTIMATE_HEIGHT = 440;
1012
1397
  export function BeeperInboxPanel({ placement = "anchor", } = {}) {
1013
- const { open, setOpen, items, loading, refreshing, connectionState, errorMessage, refresh, reconnect, markRead, markAllRead, archive, tabs, activeTab, setActiveTab, tabUnreadCount, handleActionClick, effectiveConfig, triggerRef, } = useBeeperInbox();
1398
+ const { open, setOpen, items, loading, refreshing, connectionState, errorMessage, refresh, reconnect, markRead, markAllRead, archive, tabs, activeTab, setActiveTab, tabUnreadCount, handleActionClick, effectiveConfig, triggerRef, hasMore, loadingMore, loadMore, } = useInboxContext("BeeperInboxPanel");
1014
1399
  const [layout, setLayout] = useState({ top: 16, right: 16, maxListHeight: 320 });
1015
1400
  const panelRef = useRef(null);
1016
1401
  useEffect(() => {
@@ -1213,7 +1598,7 @@ export function BeeperInboxPanel({ placement = "anchor", } = {}) {
1213
1598
  lineHeight: 1,
1214
1599
  padding: "3px 6px",
1215
1600
  }, children: count > 99 ? "99+" : count })) : null] }, tab.key));
1216
- }) })) : null, connectionState !== "live" ? (_jsx("div", { role: connectionState === "error" ? "alert" : "status", children: connectionState === "error" ? (_jsxs(_Fragment, { children: [errorMessage ? _jsx("small", { children: errorMessage }) : null, _jsx("button", { type: "button", style: toolbarBtn, onClick: () => reconnect(), children: "Reconnect" })] })) : null })) : null, _jsx("div", { style: {
1601
+ }) })) : null, connectionState !== "live" ? (_jsx("div", { role: connectionState === "error" ? "alert" : "status", children: connectionState === "error" ? (_jsxs(_Fragment, { children: [errorMessage ? _jsx("small", { children: errorMessage }) : null, _jsx("button", { type: "button", style: toolbarBtn, onClick: () => reconnect(), children: "Reconnect" })] })) : null })) : null, _jsxs("div", { style: {
1217
1602
  marginTop: 12,
1218
1603
  display: "grid",
1219
1604
  gap: 8,
@@ -1221,71 +1606,73 @@ export function BeeperInboxPanel({ placement = "anchor", } = {}) {
1221
1606
  minHeight: items.length === 0 && !loading ? 140 : undefined,
1222
1607
  overflowY: "auto",
1223
1608
  paddingRight: 2,
1224
- }, children: loading && items.length === 0 ? (_jsx("div", { role: "status", style: {
1225
- alignSelf: "center",
1226
- padding: "18px 0",
1227
- color: dark ? "#d0d5dd" : light.muted,
1228
- fontSize: "0.92em",
1229
- }, children: "Loading notifications..." })) : items.length === 0 ? (_jsx("div", { style: {
1230
- alignSelf: "center",
1231
- textAlign: "center",
1232
- padding: "30px 18px",
1233
- lineHeight: 1.5,
1234
- color: dark ? "#c7b6a7" : light.muted,
1235
- border: dark ? "1px dashed #3a4250" : `1px dashed ${light.border}`,
1236
- borderRadius: effectiveConfig.radius - 2,
1237
- background: dark ? "#181411" : "#fffdf9",
1238
- }, children: "No notifications yet. New activity will appear here as soon as this subscriber receives it." })) : (items.map((item) => (_jsxs("div", { style: {
1239
- border: dark ? "1px solid #2b313b" : `1px solid ${light.border}`,
1240
- borderRadius: effectiveConfig.radius - 2,
1241
- padding: 14,
1242
- background: item.readAt
1243
- ? dark
1244
- ? "#181411"
1245
- : "#fffaf4"
1246
- : dark
1247
- ? "#1b1613"
1248
- : light.itemBg,
1249
- boxShadow: item.readAt
1250
- ? "none"
1251
- : dark
1252
- ? `inset 0 0 0 1px ${withAlpha(effectiveConfig.accentColor, 0.18)}`
1253
- : `inset 0 0 0 1px ${withAlpha(effectiveConfig.accentColor, 0.14)}`,
1254
- opacity: item.resolvedAt ? 0.65 : 1,
1255
- }, children: [_jsxs("div", { style: {
1256
- display: "flex",
1257
- alignItems: "center",
1258
- gap: 10,
1259
- fontWeight: 700,
1260
- marginBottom: 6,
1261
- letterSpacing: "-0.02em",
1262
- }, children: [item.avatarUrl ? (_jsx("img", { src: item.avatarUrl, alt: "", width: 32, height: 32, loading: "lazy", style: { borderRadius: "50%", objectFit: "cover", flexShrink: 0 } })) : null, _jsx("span", { children: item.title ?? "Notification" })] }), _jsx("div", { style: {
1263
- opacity: 0.92,
1264
- marginBottom: 10,
1265
- lineHeight: 1.5,
1266
- color: dark ? "#efe3d8" : "#4e3c34",
1267
- }, children: item.body }), item.imageUrl ? (_jsx("img", { src: item.imageUrl, alt: "", loading: "lazy", style: {
1268
- display: "block",
1269
- width: "100%",
1270
- aspectRatio: "16 / 9",
1271
- objectFit: "cover",
1272
- borderRadius: Math.max(effectiveConfig.radius - 6, 4),
1273
- marginBottom: 10,
1274
- } })) : null, _jsxs("div", { style: {
1275
- display: "flex",
1276
- justifyContent: "space-between",
1277
- alignItems: "center",
1278
- gap: 12,
1279
- }, children: [_jsxs("div", { style: {
1280
- display: "flex",
1281
- alignItems: "center",
1282
- gap: 10,
1283
- flexWrap: "wrap",
1284
- }, children: [_jsx("small", { style: { opacity: 0.65 }, children: timeAgo(item.createdAt) }), item.actionUrl ? (_jsx("button", { type: "button", onClick: () => {
1285
- void handleActionClick(item);
1286
- }, style: linkBtn, children: item.actionLabel ?? "Open" })) : null] }), _jsxs("div", { style: { display: "flex", gap: 12, alignItems: "center" }, children: [!item.readAt ? (_jsx("button", { type: "button", style: linkBtn, onClick: () => markRead(item._id), children: "Mark read" })) : (_jsx("small", { style: { opacity: 0.65 }, children: "Read" })), effectiveConfig.showDismiss ? (_jsx("button", { type: "button", style: { ...linkBtn, color: dark ? "#c7b6a7" : light.muted }, onClick: () => {
1287
- void archive(item._id).catch(() => undefined);
1288
- }, children: "Dismiss" })) : null] })] })] }, item._id)))) }), effectiveConfig.showMarkAll && items.length > 0 ? (_jsx("div", { style: {
1609
+ }, children: [loading && items.length === 0 ? (_jsx("div", { role: "status", style: {
1610
+ alignSelf: "center",
1611
+ padding: "18px 0",
1612
+ color: dark ? "#d0d5dd" : light.muted,
1613
+ fontSize: "0.92em",
1614
+ }, children: "Loading notifications..." })) : items.length === 0 ? (_jsx("div", { style: {
1615
+ alignSelf: "center",
1616
+ textAlign: "center",
1617
+ padding: "30px 18px",
1618
+ lineHeight: 1.5,
1619
+ color: dark ? "#c7b6a7" : light.muted,
1620
+ border: dark ? "1px dashed #3a4250" : `1px dashed ${light.border}`,
1621
+ borderRadius: effectiveConfig.radius - 2,
1622
+ background: dark ? "#181411" : "#fffdf9",
1623
+ }, children: "No notifications yet. New activity will appear here as soon as this subscriber receives it." })) : (items.map((item) => (_jsxs("div", { style: {
1624
+ border: dark ? "1px solid #2b313b" : `1px solid ${light.border}`,
1625
+ borderRadius: effectiveConfig.radius - 2,
1626
+ padding: 14,
1627
+ background: item.readAt
1628
+ ? dark
1629
+ ? "#181411"
1630
+ : "#fffaf4"
1631
+ : dark
1632
+ ? "#1b1613"
1633
+ : light.itemBg,
1634
+ boxShadow: item.readAt
1635
+ ? "none"
1636
+ : dark
1637
+ ? `inset 0 0 0 1px ${withAlpha(effectiveConfig.accentColor, 0.18)}`
1638
+ : `inset 0 0 0 1px ${withAlpha(effectiveConfig.accentColor, 0.14)}`,
1639
+ opacity: item.resolvedAt ? 0.65 : 1,
1640
+ }, children: [_jsxs("div", { style: {
1641
+ display: "flex",
1642
+ alignItems: "center",
1643
+ gap: 10,
1644
+ fontWeight: 700,
1645
+ marginBottom: 6,
1646
+ letterSpacing: "-0.02em",
1647
+ }, children: [item.avatarUrl ? (_jsx("img", { src: item.avatarUrl, alt: "", width: 32, height: 32, loading: "lazy", style: { borderRadius: "50%", objectFit: "cover", flexShrink: 0 } })) : null, _jsx("span", { children: item.title ?? "Notification" })] }), _jsx("div", { style: {
1648
+ opacity: 0.92,
1649
+ marginBottom: 10,
1650
+ lineHeight: 1.5,
1651
+ color: dark ? "#efe3d8" : "#4e3c34",
1652
+ }, children: item.body }), item.imageUrl ? (_jsx("img", { src: item.imageUrl, alt: "", loading: "lazy", style: {
1653
+ display: "block",
1654
+ width: "100%",
1655
+ aspectRatio: "16 / 9",
1656
+ objectFit: "cover",
1657
+ borderRadius: Math.max(effectiveConfig.radius - 6, 4),
1658
+ marginBottom: 10,
1659
+ } })) : null, _jsxs("div", { style: {
1660
+ display: "flex",
1661
+ justifyContent: "space-between",
1662
+ alignItems: "center",
1663
+ gap: 12,
1664
+ }, children: [_jsxs("div", { style: {
1665
+ display: "flex",
1666
+ alignItems: "center",
1667
+ gap: 10,
1668
+ flexWrap: "wrap",
1669
+ }, children: [_jsx("small", { style: { opacity: 0.65 }, children: timeAgo(item.createdAt) }), item.actionUrl ? (_jsx("button", { type: "button", onClick: () => {
1670
+ void handleActionClick(item);
1671
+ }, style: linkBtn, children: item.actionLabel ?? "Open" })) : null] }), _jsxs("div", { style: { display: "flex", gap: 12, alignItems: "center" }, children: [!item.readAt ? (_jsx("button", { type: "button", style: linkBtn, onClick: () => markRead(item._id), children: "Mark read" })) : (_jsx("small", { style: { opacity: 0.65 }, children: "Read" })), effectiveConfig.showDismiss ? (_jsx("button", { type: "button", style: { ...linkBtn, color: dark ? "#c7b6a7" : light.muted }, onClick: () => {
1672
+ void archive(item._id).catch(() => undefined);
1673
+ }, children: "Dismiss" })) : null] })] })] }, item._id)))), items.length > 0 && hasMore ? (_jsx("button", { type: "button", style: { ...toolbarBtn, justifySelf: "center" }, disabled: loadingMore, onClick: () => {
1674
+ void loadMore().catch(() => undefined);
1675
+ }, children: loadingMore ? "Loading..." : "Show older" })) : null] }), effectiveConfig.showMarkAll && items.length > 0 ? (_jsx("div", { style: {
1289
1676
  display: "flex",
1290
1677
  justifyContent: "flex-end",
1291
1678
  marginTop: 12,