beeper-inbox-react 0.4.0 → 0.5.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
@@ -1,1691 +1,2124 @@
1
- import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
- import { createContext, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, } from "react";
3
- import { createPortal } from "react-dom";
4
- import { ConvexClient } from "convex/browser";
5
- const DEFAULT_CONFIG = {
6
- modeDefault: "system",
7
- accentColor: "#f97316",
8
- radius: 14,
9
- fontScale: 1,
10
- compact: false,
11
- showTopicTabs: true,
12
- showMarkAll: true,
13
- headerTitle: "Notifications",
14
- showDismiss: false,
1
+ import { createContext, useState, useRef, useCallback, useMemo, useEffect, useContext, useLayoutEffect } from 'react';
2
+ import { createPortal } from 'react-dom';
3
+ import { ConvexClient } from 'convex/browser';
4
+ import { jsx, Fragment, jsxs } from 'react/jsx-runtime';
5
+
6
+ // src/index.tsx
7
+
8
+ // ../inbox-core/dist/websocket.js
9
+ var SESSION_EXPIRED_CLOSE = 4001;
10
+ var SOCKET_PING_MS = 25e3;
11
+ function createWebSocketRealtimeClient(url, options) {
12
+ const open = options.createSocket ?? ((socketUrl) => new WebSocket(socketUrl));
13
+ return {
14
+ onUpdate(_query, args, onResult, onError) {
15
+ const params = new URLSearchParams({
16
+ subscriberId: String(args.subscriberId ?? ""),
17
+ token: String(args.sessionToken ?? ""),
18
+ publishableKey: options.publishableKey
19
+ });
20
+ const socket = open(`${url}${url.includes("?") ? "&" : "?"}${params}`);
21
+ let stopped = false;
22
+ let page = null;
23
+ let loading = false;
24
+ let reloadQueued = false;
25
+ let pingTimer = null;
26
+ const stop = () => {
27
+ stopped = true;
28
+ if (pingTimer)
29
+ clearInterval(pingTimer);
30
+ pingTimer = null;
31
+ };
32
+ const reload = async () => {
33
+ if (loading) {
34
+ reloadQueued = true;
35
+ return;
36
+ }
37
+ loading = true;
38
+ try {
39
+ page = await options.loadFirstPage();
40
+ if (!stopped)
41
+ onResult(page);
42
+ } catch (error) {
43
+ if (!stopped) {
44
+ stop();
45
+ try {
46
+ socket.close(1e3);
47
+ } catch {
48
+ }
49
+ onError(error instanceof Error ? error : new Error("Inbox request failed"));
50
+ }
51
+ } finally {
52
+ loading = false;
53
+ if (reloadQueued && !stopped) {
54
+ reloadQueued = false;
55
+ void reload();
56
+ }
57
+ }
58
+ };
59
+ socket.addEventListener("open", () => {
60
+ if (stopped)
61
+ return;
62
+ pingTimer = setInterval(() => {
63
+ try {
64
+ socket.send("ping");
65
+ } catch {
66
+ }
67
+ }, SOCKET_PING_MS);
68
+ void reload();
69
+ });
70
+ socket.addEventListener("message", (event) => {
71
+ if (stopped || event.data === "pong")
72
+ return;
73
+ let message;
74
+ try {
75
+ message = JSON.parse(String(event.data));
76
+ } catch {
77
+ return;
78
+ }
79
+ if (message.type === "sync") {
80
+ void reload();
81
+ } else if (message.type === "item" && message.item) {
82
+ if (!page || loading || options.reloadOnItem) {
83
+ reloadQueued = loading;
84
+ if (!loading)
85
+ void reload();
86
+ return;
87
+ }
88
+ page = applyInboxItem(page, message.item, args);
89
+ onResult(page);
90
+ }
91
+ });
92
+ socket.addEventListener("close", (event) => {
93
+ if (stopped)
94
+ return;
95
+ stop();
96
+ onError(new Error(event.code === SESSION_EXPIRED_CLOSE ? "Widget session expired" : `Realtime connection closed (${event.code})`));
97
+ });
98
+ return () => {
99
+ stop();
100
+ try {
101
+ socket.close(1e3);
102
+ } catch {
103
+ }
104
+ };
105
+ },
106
+ close() {
107
+ }
108
+ };
109
+ }
110
+ function applyInboxItem(page, item, args) {
111
+ if (page.items.some((existing) => existing._id === item._id))
112
+ return page;
113
+ const kind = item.kind;
114
+ const kinds = Array.isArray(args.kinds) ? args.kinds : [];
115
+ const visible = args.archived !== true && (kinds.length === 0 || kind !== void 0 && kinds.includes(kind));
116
+ const unread = !item.readAt;
117
+ const unreadByKind = page.unreadByKind ? { ...page.unreadByKind } : void 0;
118
+ if (unread && kind && unreadByKind && kind in unreadByKind)
119
+ unreadByKind[kind] = Math.min(100, (unreadByKind[kind] ?? 0) + 1);
120
+ return {
121
+ ...page,
122
+ items: visible ? [item, ...page.items] : page.items,
123
+ unreadCount: unread ? Math.min(100, page.unreadCount + 1) : page.unreadCount,
124
+ ...unreadByKind ? { unreadByKind } : {}
125
+ };
126
+ }
127
+ var DEFAULT_CONFIG = {
128
+ modeDefault: "system",
129
+ accentColor: "#f97316",
130
+ radius: 14,
131
+ fontScale: 1,
132
+ compact: false,
133
+ showTopicTabs: true,
134
+ showMarkAll: true,
135
+ headerTitle: "Notifications",
136
+ showDismiss: false
15
137
  };
16
- /**
17
- * The hosted Beeper API origin.
18
- *
19
- * Kept as a local copy rather than imported from `beeper-sdk`, so that a browser
20
- * bundle never pulls in the server-side client (whose constructor takes a secret
21
- * key). `BEEPER_DEFAULT_BASE_URL` in `beeper-sdk` is the same value, and a test
22
- * asserts the two stay equal.
23
- *
24
- * This is the API origin, NOT the dashboard/marketing domain — that one serves
25
- * the web app and answers API paths with HTML, which surfaces here as the
26
- * "non-JSON response from Beeper API" error below.
27
- */
28
- const DEFAULT_BEEPER_WIDGET_API_BASE_URL = "https://exciting-guineapig-440.convex.site";
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;
138
+ function pickRealtimeSource(config) {
139
+ if (config.realtime?.kind === "ws" && config.realtime.url && typeof WebSocket !== "undefined") {
140
+ return { kind: "ws", url: config.realtime.url };
141
+ }
142
+ return config.convexUrl ? { kind: "convex", url: config.convexUrl } : null;
143
+ }
144
+ function createConvexClient(url) {
145
+ const client = new ConvexClient(url);
146
+ return {
147
+ onUpdate(query, args, onResult, onError) {
148
+ const unsubscribe = client.onUpdate(query, args, onResult, onError);
149
+ return () => unsubscribe();
150
+ },
151
+ close: () => client.close()
152
+ };
153
+ }
154
+ function createWidgetSocketClient(url, publishableKey, loaders) {
155
+ return {
156
+ onUpdate(query, args, onResult, onError) {
157
+ const list = query === "widgetInbox:list";
158
+ return createWebSocketRealtimeClient(url, {
159
+ publishableKey,
160
+ loadFirstPage: () => list ? loaders.current.head() : loaders.current.unread(),
161
+ reloadOnItem: !list
162
+ }).onUpdate(query, args, onResult, onError);
163
+ },
164
+ close() {
46
165
  }
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
- ];
166
+ };
52
167
  }
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. */
168
+ var DEFAULT_BEEPER_WIDGET_API_BASE_URL = "https://api.beeper.iconeht.com";
169
+ var Ctx = createContext(null);
170
+ var ItemsDemandCtx = createContext(null);
171
+ var INBOX_PAGE_SIZE = 20;
172
+ function mergeOlderItems(head, previous) {
173
+ const last = head[head.length - 1];
174
+ if (!last) {
175
+ return previous;
176
+ }
177
+ const headIds = new Set(head.map((item) => item._id));
178
+ return [
179
+ ...head,
180
+ ...previous.filter((item) => !headIds.has(item._id) && item.createdAt <= last.createdAt)
181
+ ];
182
+ }
183
+ var REALTIME_RETRY_MS = 6e4;
184
+ var MAX_POLL_BACKOFF_MS = 5 * 6e4;
58
185
  function isPageHidden() {
59
- return typeof document !== "undefined" && document.hidden === true;
186
+ return typeof document !== "undefined" && document.hidden === true;
60
187
  }
61
188
  function parseTokenExpiryMs(token) {
62
- const segments = token.split(".");
63
- const payload = segments.length >= 3 ? segments[1] : segments[0];
64
- if (!payload) {
65
- return null;
66
- }
67
- try {
68
- const normalized = payload.replace(/-/g, "+").replace(/_/g, "/");
69
- const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, "=");
70
- const decoded = typeof globalThis.Buffer !== "undefined"
71
- ? globalThis.Buffer.from(padded, "base64").toString("utf8")
72
- : typeof globalThis.atob === "function"
73
- ? globalThis.atob(padded)
74
- : null;
75
- if (!decoded) {
76
- return null;
77
- }
78
- const json = JSON.parse(decoded);
79
- if (typeof json.exp !== "number" || !Number.isFinite(json.exp)) {
80
- return null;
81
- }
82
- return json.exp;
189
+ const segments = token.split(".");
190
+ const payload = segments.length >= 3 ? segments[1] : segments[0];
191
+ if (!payload) {
192
+ return null;
193
+ }
194
+ try {
195
+ const normalized = payload.replace(/-/g, "+").replace(/_/g, "/");
196
+ const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, "=");
197
+ const decoded = typeof globalThis.Buffer !== "undefined" ? globalThis.Buffer.from(padded, "base64").toString("utf8") : typeof globalThis.atob === "function" ? globalThis.atob(padded) : null;
198
+ if (!decoded) {
199
+ return null;
83
200
  }
84
- catch {
85
- return null;
201
+ const json = JSON.parse(decoded);
202
+ if (typeof json.exp !== "number" || !Number.isFinite(json.exp)) {
203
+ return null;
86
204
  }
205
+ return json.exp;
206
+ } catch {
207
+ return null;
208
+ }
87
209
  }
88
210
  function isSessionExpiringSoon(expiresAt, now = Date.now()) {
89
- return Boolean(expiresAt && expiresAt - now <= 30_000);
211
+ return Boolean(expiresAt && expiresAt - now <= 3e4);
90
212
  }
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;
213
+ var CONFIG_CACHE_MS = 10 * 6e4;
97
214
  function storedConfigKey(baseUrl, projectId) {
98
- return `beeper:widget-config:${baseUrl}:${projectId}`;
215
+ return `beeper:widget-config:${baseUrl}:${projectId}`;
99
216
  }
100
217
  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;
218
+ try {
219
+ if (typeof window === "undefined" || !window.sessionStorage) {
220
+ return void 0;
111
221
  }
112
- catch {
113
- return undefined;
222
+ const raw = window.sessionStorage.getItem(storedConfigKey(baseUrl, projectId));
223
+ const stored = raw ? JSON.parse(raw) : null;
224
+ if (!stored?.config || !stored.savedAt || Date.now() - stored.savedAt > CONFIG_CACHE_MS) {
225
+ return void 0;
114
226
  }
227
+ return stored.config;
228
+ } catch {
229
+ return void 0;
230
+ }
115
231
  }
116
232
  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.
233
+ try {
234
+ if (typeof window !== "undefined" && window.sessionStorage) {
235
+ window.sessionStorage.setItem(
236
+ storedConfigKey(baseUrl, projectId),
237
+ JSON.stringify({ savedAt: Date.now(), config })
238
+ );
124
239
  }
240
+ } catch {
241
+ }
125
242
  }
126
243
  function storedSessionKey(projectId, subscriberId) {
127
- return `beeper:widget-session:${projectId}:${subscriberId}`;
244
+ return `beeper:widget-session:${projectId}:${subscriberId}`;
128
245
  }
129
- /** A session minted earlier in this tab, if it is still good for a while. */
130
246
  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;
247
+ try {
248
+ if (typeof window === "undefined" || !window.sessionStorage) {
249
+ return "";
143
250
  }
144
- catch {
145
- return "";
251
+ const key = storedSessionKey(projectId, subscriberId);
252
+ const token = window.sessionStorage.getItem(key) ?? "";
253
+ const expiresAt = parseTokenExpiryMs(token);
254
+ if (!token || !expiresAt || isSessionExpiringSoon(expiresAt)) {
255
+ window.sessionStorage.removeItem(key);
256
+ return "";
146
257
  }
258
+ return token;
259
+ } catch {
260
+ return "";
261
+ }
147
262
  }
148
263
  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.
264
+ try {
265
+ if (typeof window !== "undefined" && window.sessionStorage) {
266
+ window.sessionStorage.setItem(storedSessionKey(projectId, subscriberId), token);
156
267
  }
268
+ } catch {
269
+ }
157
270
  }
158
271
  function resolveTheme(theme) {
159
- if (theme === "system") {
160
- if (typeof window === "undefined") {
161
- return "light";
162
- }
163
- return window.matchMedia("(prefers-color-scheme: dark)").matches
164
- ? "dark"
165
- : "light";
272
+ if (theme === "system") {
273
+ if (typeof window === "undefined") {
274
+ return "light";
166
275
  }
167
- return theme;
276
+ return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
277
+ }
278
+ return theme;
168
279
  }
169
280
  function timeAgo(ts) {
170
- const diffSec = Math.max(1, Math.floor((Date.now() - ts) / 1000));
171
- if (diffSec < 60)
172
- return `${diffSec}s ago`;
173
- if (diffSec < 3600)
174
- return `${Math.floor(diffSec / 60)}m ago`;
175
- if (diffSec < 86400)
176
- return `${Math.floor(diffSec / 3600)}h ago`;
177
- return `${Math.floor(diffSec / 86400)}d ago`;
281
+ const diffSec = Math.max(1, Math.floor((Date.now() - ts) / 1e3));
282
+ if (diffSec < 60) return `${diffSec}s ago`;
283
+ if (diffSec < 3600) return `${Math.floor(diffSec / 60)}m ago`;
284
+ if (diffSec < 86400) return `${Math.floor(diffSec / 3600)}h ago`;
285
+ return `${Math.floor(diffSec / 86400)}d ago`;
178
286
  }
179
287
  function withAlpha(color, alpha) {
180
- const normalized = color.trim();
181
- const clamped = Math.max(0, Math.min(1, alpha));
182
- const shortHexMatch = /^#([\da-f]{3})$/i.exec(normalized);
183
- const shortHex = shortHexMatch?.[1];
184
- if (shortHex) {
185
- const channels = shortHex
186
- .split("")
187
- .map((channel) => parseInt(channel + channel, 16));
188
- const [r, g, b] = channels;
189
- return `rgba(${r}, ${g}, ${b}, ${clamped})`;
190
- }
191
- const longHexMatch = /^#([\da-f]{6})$/i.exec(normalized);
192
- const value = longHexMatch?.[1];
193
- if (value) {
194
- const r = parseInt(value.slice(0, 2), 16);
195
- const g = parseInt(value.slice(2, 4), 16);
196
- const b = parseInt(value.slice(4, 6), 16);
197
- return `rgba(${r}, ${g}, ${b}, ${clamped})`;
198
- }
199
- return `color-mix(in srgb, ${normalized} ${Math.round(clamped * 100)}%, transparent)`;
288
+ const normalized = color.trim();
289
+ const clamped = Math.max(0, Math.min(1, alpha));
290
+ const shortHexMatch = /^#([\da-f]{3})$/i.exec(normalized);
291
+ const shortHex = shortHexMatch?.[1];
292
+ if (shortHex) {
293
+ const channels = shortHex.split("").map((channel) => parseInt(channel + channel, 16));
294
+ const [r, g, b] = channels;
295
+ return `rgba(${r}, ${g}, ${b}, ${clamped})`;
296
+ }
297
+ const longHexMatch = /^#([\da-f]{6})$/i.exec(normalized);
298
+ const value = longHexMatch?.[1];
299
+ if (value) {
300
+ const r = parseInt(value.slice(0, 2), 16);
301
+ const g = parseInt(value.slice(2, 4), 16);
302
+ const b = parseInt(value.slice(4, 6), 16);
303
+ return `rgba(${r}, ${g}, ${b}, ${clamped})`;
304
+ }
305
+ return `color-mix(in srgb, ${normalized} ${Math.round(clamped * 100)}%, transparent)`;
200
306
  }
201
307
  function readStringRecordValue(record, keys) {
202
- if (!record) {
203
- return undefined;
204
- }
205
- for (const key of keys) {
206
- const value = record[key];
207
- if (typeof value === "string" && value.trim()) {
208
- return value.trim();
209
- }
308
+ if (!record) {
309
+ return void 0;
310
+ }
311
+ for (const key of keys) {
312
+ const value = record[key];
313
+ if (typeof value === "string" && value.trim()) {
314
+ return value.trim();
210
315
  }
211
- return undefined;
316
+ }
317
+ return void 0;
212
318
  }
213
319
  function normalizeInboxItem(item) {
214
- const actionLabel = item.actionLabel ??
215
- readStringRecordValue(item.metadata, [
216
- "_beeperActionLabel",
217
- "actionLabel",
218
- "action_label",
219
- "ctaLabel",
220
- "cta_label",
221
- ]);
222
- const actionUrl = item.actionUrl ??
223
- readStringRecordValue(item.metadata, [
224
- "_beeperActionUrl",
225
- "actionUrl",
226
- "action_url",
227
- "ctaUrl",
228
- "cta_url",
229
- ]);
230
- return {
231
- ...item,
232
- actionLabel,
233
- actionUrl,
234
- };
320
+ const actionLabel = item.actionLabel ?? readStringRecordValue(item.metadata, [
321
+ "_beeperActionLabel",
322
+ "actionLabel",
323
+ "action_label",
324
+ "ctaLabel",
325
+ "cta_label"
326
+ ]);
327
+ const actionUrl = item.actionUrl ?? readStringRecordValue(item.metadata, [
328
+ "_beeperActionUrl",
329
+ "actionUrl",
330
+ "action_url",
331
+ "ctaUrl",
332
+ "cta_url"
333
+ ]);
334
+ return {
335
+ ...item,
336
+ actionLabel,
337
+ actionUrl
338
+ };
235
339
  }
236
340
  function resolveActionNavigationTarget(actionUrl, configured) {
237
- if (configured !== "auto") {
238
- return configured;
239
- }
240
- if (typeof window === "undefined") {
241
- return "_self";
242
- }
243
- try {
244
- const resolved = new URL(actionUrl, window.location.origin);
245
- return resolved.origin === window.location.origin ? "_self" : "_blank";
246
- }
247
- catch {
248
- return "_self";
249
- }
341
+ if (configured !== "auto") {
342
+ return configured;
343
+ }
344
+ if (typeof window === "undefined") {
345
+ return "_self";
346
+ }
347
+ try {
348
+ const resolved = new URL(actionUrl, window.location.origin);
349
+ return resolved.origin === window.location.origin ? "_self" : "_blank";
350
+ } catch {
351
+ return "_self";
352
+ }
250
353
  }
251
354
  function tabKinds(tab) {
252
- return tab?.kind === undefined ? [] : [tab.kind].flat();
355
+ return tab?.kind === void 0 ? [] : [tab.kind].flat();
253
356
  }
254
- /** A tab's badge: its kinds' unread, or the whole inbox's for an "all" tab. */
255
357
  function countTabUnread(tab, unreadCount, unreadByKind) {
256
- const kinds = tabKinds(tab);
257
- return kinds.length === 0
258
- ? unreadCount
259
- : kinds.reduce((sum, kind) => sum + (unreadByKind[kind] ?? 0), 0);
358
+ const kinds = tabKinds(tab);
359
+ return kinds.length === 0 ? unreadCount : kinds.reduce((sum, kind) => sum + (unreadByKind[kind] ?? 0), 0);
260
360
  }
261
- /** `&kind=` for the active tab and `&unreadKind=` for every tab's badge. */
262
361
  function buildKindsQuery(activeKinds, unreadKinds) {
263
- return [
264
- ...activeKinds.map((kind) => `&kind=${encodeURIComponent(kind)}`),
265
- ...unreadKinds.map((kind) => `&unreadKind=${encodeURIComponent(kind)}`),
266
- ].join("");
362
+ return [
363
+ ...activeKinds.map((kind) => `&kind=${encodeURIComponent(kind)}`),
364
+ ...unreadKinds.map((kind) => `&unreadKind=${encodeURIComponent(kind)}`)
365
+ ].join("");
267
366
  }
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, }) {
269
- const [open, setOpen] = useState(false);
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;
285
- const [unreadCount, setUnreadCount] = useState(0);
286
- const [unreadByKind, setUnreadByKind] = useState({});
287
- // Keyed by value so an inline `tabs={[...]}` doesn't refetch on every render.
288
- const tabsKey = JSON.stringify(tabs ?? []);
289
- const stableTabs = useMemo(() => JSON.parse(tabsKey), [tabsKey]);
290
- const [activeTab, setActiveTabState] = useState(defaultTab ?? tabs?.[0]?.key ?? null);
291
- const activeKinds = useMemo(() => tabKinds(stableTabs.find((candidate) => candidate.key === activeTab)), [activeTab, stableTabs]);
292
- const unreadKinds = useMemo(() => Array.from(new Set(stableTabs.flatMap(tabKinds))), [stableTabs]);
293
- const kindsQuery = useMemo(() => buildKindsQuery(activeKinds, unreadKinds), [activeKinds, unreadKinds]);
294
- const [loading, setLoading] = useState(false);
295
- const [refreshing, setRefreshing] = useState(false);
296
- const [connectionState, setConnectionState] = useState("connecting");
297
- const [errorMessage, setErrorMessage] = useState(null);
298
- const [serverConfig, setServerConfig] = useState(DEFAULT_CONFIG);
299
- const [realtimeConvexUrl, setRealtimeConvexUrl] = useState(null);
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));
307
- const [convexClient, setConvexClient] = useState(null);
308
- const convexClientRef = useRef(null);
309
- const [reconnectNonce, setReconnectNonce] = useState(0);
310
- const sessionRefreshRef = useRef(null);
311
- const eventRef = useRef(onEvent);
312
- const triggerRef = useRef(null);
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);
320
- useEffect(() => {
321
- eventRef.current = onEvent;
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);
336
- const emitEvent = useCallback((event) => {
337
- eventRef.current?.(event);
338
- }, []);
339
- useEffect(() => {
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]);
347
- const resolveSessionToken = useCallback(async () => {
348
- const subscriber = subscriberRef.current;
349
- const getSessionToken = getSessionTokenRef.current;
350
- if (getSessionToken) {
351
- return getSessionToken(subscriber);
352
- }
353
- const sessionUrl = /^https?:\/\//i.test(sessionEndpoint)
354
- ? sessionEndpoint
355
- : typeof window !== "undefined"
356
- ? new URL(sessionEndpoint, window.location.origin).toString()
357
- : sessionEndpoint;
358
- const response = await fetch(sessionUrl, {
359
- method: "POST",
360
- headers: {
361
- "content-type": "application/json",
362
- ...(sessionRequestHeadersRef.current ?? {}),
363
- },
364
- body: JSON.stringify({
365
- projectId,
366
- subscriberId: subscriber.subscriberId,
367
- profile: {
368
- displayName: subscriber.displayName,
369
- email: subscriber.email,
370
- avatarUrl: subscriber.avatarUrl,
371
- metadata: subscriber.metadata,
372
- },
373
- }),
374
- });
375
- const payload = (await response.json());
376
- const token = payload.widgetSessionToken ?? payload.data?.widgetSessionToken;
377
- if (!response.ok || !token) {
378
- throw new Error(payload?.error ?? "Failed to mint Beeper widget session token");
379
- }
380
- return token;
381
- }, [projectId, sessionEndpoint]);
382
- const refreshSession = useCallback(async () => {
383
- if (sessionRefreshRef.current) {
384
- return sessionRefreshRef.current;
385
- }
386
- emitEvent({
387
- type: "session.refresh.start",
388
- projectId,
389
- subscriberId: subscriber.subscriberId,
390
- });
391
- const request = resolveSessionToken()
392
- .then((next) => {
393
- setRuntimeSessionToken(next);
394
- runtimeSessionTokenRef.current = next;
395
- if (persistSession && !sessionToken) {
396
- writeStoredSession(projectId, subscriber.subscriberId, next);
397
- }
398
- const nextExpiresAt = parseTokenExpiryMs(next);
399
- setRuntimeSessionExpiresAt(nextExpiresAt);
400
- runtimeSessionExpiresAtRef.current = nextExpiresAt;
401
- emitEvent({
402
- type: "session.refresh.success",
403
- projectId,
404
- subscriberId: subscriber.subscriberId,
405
- });
406
- return next;
407
- })
408
- .catch((error) => {
409
- const message = error instanceof Error ? error.message : "Session refresh failed";
410
- emitEvent({
411
- type: "session.refresh.error",
412
- projectId,
413
- subscriberId: subscriber.subscriberId,
414
- message,
415
- });
416
- throw error;
417
- })
418
- .finally(() => {
419
- sessionRefreshRef.current = null;
420
- });
421
- sessionRefreshRef.current = request;
422
- return request;
423
- }, [
424
- emitEvent,
425
- persistSession,
367
+ function BeeperInboxProvider({
368
+ baseUrl = DEFAULT_BEEPER_WIDGET_API_BASE_URL,
369
+ projectId,
370
+ publishableKey,
371
+ sessionToken,
372
+ getSessionToken,
373
+ sessionEndpoint = "/api/beeper/widget-session",
374
+ sessionRequestHeaders,
375
+ persistSession = true,
376
+ subscriber,
377
+ theme = "system",
378
+ customization,
379
+ push,
380
+ actionLinkTarget = "auto",
381
+ onActionClick,
382
+ pollIntervalMs = 15e3,
383
+ onEvent,
384
+ tabs,
385
+ defaultTab,
386
+ children
387
+ }) {
388
+ const [open, setOpen] = useState(false);
389
+ const [items, setItems] = useState([]);
390
+ const [hasMore, setHasMore] = useState(false);
391
+ const [loadingMore, setLoadingMore] = useState(false);
392
+ const cursorRef = useRef(null);
393
+ const hasOlderPagesRef = useRef(false);
394
+ const loadMoreRef = useRef(null);
395
+ const [itemsDemand, setItemsDemand] = useState(0);
396
+ const registerItemsDemand = useCallback(() => {
397
+ setItemsDemand((count) => count + 1);
398
+ return () => setItemsDemand((count) => count - 1);
399
+ }, []);
400
+ const wantsItems = open || itemsDemand > 0;
401
+ const [unreadCount, setUnreadCount] = useState(0);
402
+ const [unreadByKind, setUnreadByKind] = useState({});
403
+ const tabsKey = JSON.stringify(tabs ?? []);
404
+ const stableTabs = useMemo(() => JSON.parse(tabsKey), [tabsKey]);
405
+ const [activeTab, setActiveTabState] = useState(
406
+ defaultTab ?? tabs?.[0]?.key ?? null
407
+ );
408
+ const activeKinds = useMemo(
409
+ () => tabKinds(stableTabs.find((candidate) => candidate.key === activeTab)),
410
+ [activeTab, stableTabs]
411
+ );
412
+ const unreadKinds = useMemo(
413
+ () => Array.from(new Set(stableTabs.flatMap(tabKinds))),
414
+ [stableTabs]
415
+ );
416
+ const kindsQuery = useMemo(
417
+ () => buildKindsQuery(activeKinds, unreadKinds),
418
+ [activeKinds, unreadKinds]
419
+ );
420
+ const [loading, setLoading] = useState(false);
421
+ const [refreshing, setRefreshing] = useState(false);
422
+ const [connectionState, setConnectionState] = useState("connecting");
423
+ const [errorMessage, setErrorMessage] = useState(null);
424
+ const [serverConfig, setServerConfig] = useState(DEFAULT_CONFIG);
425
+ const [realtimeSource, setRealtimeSource] = useState(null);
426
+ const [initialSessionToken] = useState(
427
+ () => sessionToken ?? (persistSession ? readStoredSession(projectId, subscriber.subscriberId) : "")
428
+ );
429
+ const [runtimeSessionToken, setRuntimeSessionToken] = useState(initialSessionToken);
430
+ const [runtimeSessionExpiresAt, setRuntimeSessionExpiresAt] = useState(
431
+ parseTokenExpiryMs(initialSessionToken)
432
+ );
433
+ const runtimeSessionTokenRef = useRef(initialSessionToken);
434
+ const runtimeSessionExpiresAtRef = useRef(
435
+ parseTokenExpiryMs(initialSessionToken)
436
+ );
437
+ const [realtimeClient, setRealtimeClient] = useState(null);
438
+ const realtimeClientRef = useRef(null);
439
+ const realtimeLoadersRef = useRef({
440
+ head: async () => ({}),
441
+ unread: async () => ({})
442
+ });
443
+ const [reconnectNonce, setReconnectNonce] = useState(0);
444
+ const sessionRefreshRef = useRef(null);
445
+ const eventRef = useRef(onEvent);
446
+ const triggerRef = useRef(null);
447
+ const hasLoadedOnceRef = useRef(false);
448
+ const [configResolved, setConfigResolved] = useState(false);
449
+ const [realtimeFailed, setRealtimeFailed] = useState(false);
450
+ const realtimeLiveRef = useRef(false);
451
+ useEffect(() => {
452
+ eventRef.current = onEvent;
453
+ }, [onEvent]);
454
+ const subscriberRef = useRef(subscriber);
455
+ const getSessionTokenRef = useRef(getSessionToken);
456
+ const sessionRequestHeadersRef = useRef(sessionRequestHeaders);
457
+ useEffect(() => {
458
+ subscriberRef.current = subscriber;
459
+ getSessionTokenRef.current = getSessionToken;
460
+ sessionRequestHeadersRef.current = sessionRequestHeaders;
461
+ }, [getSessionToken, sessionRequestHeaders, subscriber]);
462
+ const hasGetSessionToken = Boolean(getSessionToken);
463
+ const canRefreshSession = hasGetSessionToken || Boolean(sessionEndpoint);
464
+ const emitEvent = useCallback(
465
+ (event) => {
466
+ eventRef.current?.(event);
467
+ },
468
+ []
469
+ );
470
+ useEffect(() => {
471
+ const next = sessionToken ?? (persistSession ? readStoredSession(projectId, subscriber.subscriberId) : "");
472
+ setRuntimeSessionToken(next);
473
+ setRuntimeSessionExpiresAt(parseTokenExpiryMs(next));
474
+ runtimeSessionTokenRef.current = next;
475
+ runtimeSessionExpiresAtRef.current = parseTokenExpiryMs(next);
476
+ }, [persistSession, projectId, sessionToken, subscriber.subscriberId]);
477
+ const resolveSessionToken = useCallback(async () => {
478
+ const subscriber2 = subscriberRef.current;
479
+ const getSessionToken2 = getSessionTokenRef.current;
480
+ if (getSessionToken2) {
481
+ return getSessionToken2(subscriber2);
482
+ }
483
+ const sessionUrl = /^https?:\/\//i.test(sessionEndpoint) ? sessionEndpoint : typeof window !== "undefined" ? new URL(sessionEndpoint, window.location.origin).toString() : sessionEndpoint;
484
+ const response = await fetch(sessionUrl, {
485
+ method: "POST",
486
+ headers: {
487
+ "content-type": "application/json",
488
+ ...sessionRequestHeadersRef.current ?? {}
489
+ },
490
+ body: JSON.stringify({
426
491
  projectId,
427
- resolveSessionToken,
428
- sessionToken,
429
- subscriber.subscriberId,
430
- ]);
431
- const ensureSession = useCallback(async () => {
432
- const now = Date.now();
433
- const currentToken = runtimeSessionTokenRef.current;
434
- const currentExpiresAt = runtimeSessionExpiresAtRef.current;
435
- if (currentToken) {
436
- if (isSessionExpiringSoon(currentExpiresAt, now) && canRefreshSession) {
437
- return refreshSession();
438
- }
439
- return currentToken;
440
- }
492
+ subscriberId: subscriber2.subscriberId,
493
+ profile: {
494
+ displayName: subscriber2.displayName,
495
+ email: subscriber2.email,
496
+ avatarUrl: subscriber2.avatarUrl,
497
+ metadata: subscriber2.metadata
498
+ }
499
+ })
500
+ });
501
+ const payload = await response.json();
502
+ const token = payload.widgetSessionToken ?? payload.data?.widgetSessionToken;
503
+ if (!response.ok || !token) {
504
+ throw new Error(
505
+ payload?.error ?? "Failed to mint Beeper widget session token"
506
+ );
507
+ }
508
+ return token;
509
+ }, [projectId, sessionEndpoint]);
510
+ const refreshSession = useCallback(async () => {
511
+ if (sessionRefreshRef.current) {
512
+ return sessionRefreshRef.current;
513
+ }
514
+ emitEvent({
515
+ type: "session.refresh.start",
516
+ projectId,
517
+ subscriberId: subscriber.subscriberId
518
+ });
519
+ const request = resolveSessionToken().then((next) => {
520
+ setRuntimeSessionToken(next);
521
+ runtimeSessionTokenRef.current = next;
522
+ if (persistSession && !sessionToken) {
523
+ writeStoredSession(projectId, subscriber.subscriberId, next);
524
+ }
525
+ const nextExpiresAt = parseTokenExpiryMs(next);
526
+ setRuntimeSessionExpiresAt(nextExpiresAt);
527
+ runtimeSessionExpiresAtRef.current = nextExpiresAt;
528
+ emitEvent({
529
+ type: "session.refresh.success",
530
+ projectId,
531
+ subscriberId: subscriber.subscriberId
532
+ });
533
+ return next;
534
+ }).catch((error) => {
535
+ const message = error instanceof Error ? error.message : "Session refresh failed";
536
+ emitEvent({
537
+ type: "session.refresh.error",
538
+ projectId,
539
+ subscriberId: subscriber.subscriberId,
540
+ message
541
+ });
542
+ throw error;
543
+ }).finally(() => {
544
+ sessionRefreshRef.current = null;
545
+ });
546
+ sessionRefreshRef.current = request;
547
+ return request;
548
+ }, [
549
+ emitEvent,
550
+ persistSession,
551
+ projectId,
552
+ resolveSessionToken,
553
+ sessionToken,
554
+ subscriber.subscriberId
555
+ ]);
556
+ const ensureSession = useCallback(async () => {
557
+ const now = Date.now();
558
+ const currentToken = runtimeSessionTokenRef.current;
559
+ const currentExpiresAt = runtimeSessionExpiresAtRef.current;
560
+ if (currentToken) {
561
+ if (isSessionExpiringSoon(currentExpiresAt, now) && canRefreshSession) {
441
562
  return refreshSession();
442
- }, [
443
- canRefreshSession,
444
- refreshSession,
445
- ]);
446
- const fetchJson = useCallback(async (method, path, body, allowSessionRefresh = true, sessionTokenOverride) => {
447
- let sessionHeaderToken = sessionTokenOverride ?? runtimeSessionTokenRef.current;
448
- if (!sessionHeaderToken && allowSessionRefresh) {
449
- sessionHeaderToken = await ensureSession();
450
- }
451
- const url = `${baseUrl.replace(/\/$/, "")}/api/v1/projects/${projectId}${path}`;
452
- const response = await fetch(url, {
453
- method,
454
- headers: {
455
- "content-type": "application/json",
456
- "x-beeper-publishable-key": publishableKey,
457
- ...(sessionHeaderToken
458
- ? {
459
- "x-beeper-session-token": sessionHeaderToken,
460
- }
461
- : {}),
462
- },
463
- body: method === "POST" ? JSON.stringify(body ?? {}) : undefined,
563
+ }
564
+ return currentToken;
565
+ }
566
+ return refreshSession();
567
+ }, [
568
+ canRefreshSession,
569
+ refreshSession
570
+ ]);
571
+ const fetchJson = useCallback(
572
+ async (method, path, body, allowSessionRefresh = true, sessionTokenOverride) => {
573
+ let sessionHeaderToken = sessionTokenOverride ?? runtimeSessionTokenRef.current;
574
+ if (!sessionHeaderToken && allowSessionRefresh) {
575
+ sessionHeaderToken = await ensureSession();
576
+ }
577
+ const url = `${baseUrl.replace(/\/$/, "")}/api/v1/projects/${projectId}${path}`;
578
+ const response = await fetch(url, {
579
+ method,
580
+ headers: {
581
+ "content-type": "application/json",
582
+ "x-beeper-publishable-key": publishableKey,
583
+ ...sessionHeaderToken ? {
584
+ "x-beeper-session-token": sessionHeaderToken
585
+ } : {}
586
+ },
587
+ body: method === "POST" ? JSON.stringify(body ?? {}) : void 0
588
+ });
589
+ const rawText = await response.text();
590
+ let payload = {};
591
+ try {
592
+ payload = rawText ? JSON.parse(rawText) : {};
593
+ } catch {
594
+ emitEvent({
595
+ type: "api.error",
596
+ projectId,
597
+ subscriberId: subscriber.subscriberId,
598
+ path,
599
+ status: response.status,
600
+ message: `Non-JSON response from Beeper API. Check baseUrl if you are overriding it. ${rawText.slice(0, 120)}`
464
601
  });
465
- const rawText = await response.text();
466
- let payload = {};
467
- try {
468
- payload = rawText ? JSON.parse(rawText) : {};
469
- }
470
- catch {
471
- emitEvent({
472
- type: "api.error",
473
- projectId,
474
- subscriberId: subscriber.subscriberId,
475
- path,
476
- status: response.status,
477
- message: `Non-JSON response from Beeper API. Check baseUrl if you are overriding it. ${rawText.slice(0, 120)}`,
478
- });
479
- throw new Error(`Beeper API returned non-JSON (${response.status}). Check the configured baseUrl override.`);
480
- }
481
- if (!response.ok) {
482
- emitEvent({
483
- type: "api.error",
484
- projectId,
485
- subscriberId: subscriber.subscriberId,
486
- path,
487
- status: response.status,
488
- message: payload.error ?? "Beeper widget request failed",
489
- });
490
- if (allowSessionRefresh &&
491
- response.status === 401 &&
492
- canRefreshSession) {
493
- const nextToken = await refreshSession();
494
- return fetchJson(method, path, body, false, nextToken);
495
- }
496
- throw new Error(payload.error ?? "Beeper widget request failed");
497
- }
498
- return payload.data;
499
- }, [
500
- baseUrl,
501
- canRefreshSession,
502
- emitEvent,
503
- projectId,
504
- publishableKey,
505
- refreshSession,
506
- ensureSession,
507
- subscriber.subscriberId,
508
- ]);
509
- /** Config is public (publishable key only); stable deps avoid refetch on every session token change. */
510
- const fetchWidgetConfigDocument = useCallback(async () => {
511
- const stored = readStoredConfig(baseUrl, projectId);
512
- if (stored) {
513
- return stored;
514
- }
515
- const url = `${baseUrl.replace(/\/$/, "")}/api/v1/projects/${projectId}/widget/config`;
516
- const response = await fetch(url, {
517
- method: "GET",
518
- headers: {
519
- "content-type": "application/json",
520
- "x-beeper-publishable-key": publishableKey,
521
- },
602
+ throw new Error(
603
+ `Beeper API returned non-JSON (${response.status}). Check the configured baseUrl override.`
604
+ );
605
+ }
606
+ if (!response.ok) {
607
+ emitEvent({
608
+ type: "api.error",
609
+ projectId,
610
+ subscriberId: subscriber.subscriberId,
611
+ path,
612
+ status: response.status,
613
+ message: payload.error ?? "Beeper widget request failed"
522
614
  });
523
- const rawText = await response.text();
524
- let payload = {};
525
- try {
526
- payload = rawText ? JSON.parse(rawText) : {};
527
- }
528
- catch {
529
- return undefined;
530
- }
531
- if (!response.ok) {
532
- return undefined;
533
- }
534
- if (payload.data) {
535
- writeStoredConfig(baseUrl, projectId, payload.data);
536
- }
537
- return payload.data;
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]);
559
- const refresh = useCallback(async (options) => {
560
- const silent = options?.silent ?? false;
561
- if (silent) {
562
- setRefreshing(true);
563
- }
564
- else {
565
- setLoading(true);
566
- }
567
- try {
568
- await ensureSession();
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}`));
575
- }
576
- finally {
577
- if (silent) {
578
- setRefreshing(false);
579
- }
580
- else {
581
- setLoading(false);
582
- }
583
- }
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);
615
+ if (allowSessionRefresh && response.status === 401 && canRefreshSession) {
616
+ const nextToken = await refreshSession();
617
+ return fetchJson(method, path, body, false, nextToken);
618
+ }
619
+ throw new Error(payload.error ?? "Beeper widget request failed");
620
+ }
621
+ return payload.data;
622
+ },
623
+ [
624
+ baseUrl,
625
+ canRefreshSession,
626
+ emitEvent,
627
+ projectId,
628
+ publishableKey,
629
+ refreshSession,
630
+ ensureSession,
631
+ subscriber.subscriberId
632
+ ]
633
+ );
634
+ const fetchWidgetConfigDocument = useCallback(async () => {
635
+ const stored = readStoredConfig(baseUrl, projectId);
636
+ if (stored) {
637
+ return stored;
638
+ }
639
+ const url = `${baseUrl.replace(/\/$/, "")}/api/v1/projects/${projectId}/widget/config`;
640
+ const response = await fetch(url, {
641
+ method: "GET",
642
+ headers: {
643
+ "content-type": "application/json",
644
+ "x-beeper-publishable-key": publishableKey
645
+ }
646
+ });
647
+ const rawText = await response.text();
648
+ let payload = {};
649
+ try {
650
+ payload = rawText ? JSON.parse(rawText) : {};
651
+ } catch {
652
+ return void 0;
653
+ }
654
+ if (!response.ok) {
655
+ return void 0;
656
+ }
657
+ if (payload.data) {
658
+ writeStoredConfig(baseUrl, projectId, payload.data);
659
+ }
660
+ return payload.data;
661
+ }, [baseUrl, projectId, publishableKey]);
662
+ const applyHead = useCallback(
663
+ (inbox) => {
664
+ const head = (inbox.items ?? []).map(normalizeInboxItem);
665
+ if (hasOlderPagesRef.current) {
666
+ setItems((current) => mergeOlderItems(head, current));
667
+ } else {
668
+ cursorRef.current = inbox.nextCursor ?? null;
669
+ setItems(head);
670
+ }
671
+ setHasMore(cursorRef.current !== null);
672
+ setUnreadCount(Number(inbox.unreadCount ?? 0));
673
+ setUnreadByKind(inbox.unreadByKind ?? {});
674
+ hasLoadedOnceRef.current = true;
675
+ },
676
+ []
677
+ );
678
+ const applyUnread = useCallback(
679
+ (result) => {
680
+ setUnreadCount(Number(result.unreadCount ?? 0));
681
+ setUnreadByKind(result.byKind ?? {});
682
+ },
683
+ []
684
+ );
685
+ const unreadQuery = useMemo(
686
+ () => unreadKinds.map((kind) => `&kind=${encodeURIComponent(kind)}`).join(""),
687
+ [unreadKinds]
688
+ );
689
+ const headPath = useMemo(
690
+ () => `/widget/inbox?subscriberId=${encodeURIComponent(subscriber.subscriberId)}&limit=${INBOX_PAGE_SIZE}${kindsQuery}`,
691
+ [kindsQuery, subscriber.subscriberId]
692
+ );
693
+ const unreadPath = useMemo(
694
+ () => `/widget/unread?subscriberId=${encodeURIComponent(subscriber.subscriberId)}${unreadQuery}`,
695
+ [subscriber.subscriberId, unreadQuery]
696
+ );
697
+ realtimeLoadersRef.current = {
698
+ head: () => fetchJson("GET", headPath),
699
+ unread: () => fetchJson("GET", unreadPath)
700
+ };
701
+ const refresh = useCallback(async (options) => {
702
+ const silent = options?.silent ?? false;
703
+ if (silent) {
704
+ setRefreshing(true);
705
+ } else {
706
+ setLoading(true);
707
+ }
708
+ try {
709
+ await ensureSession();
710
+ if (!wantsItems) {
711
+ applyUnread(
712
+ await fetchJson("GET", unreadPath)
713
+ );
714
+ return;
715
+ }
716
+ applyHead(
717
+ await fetchJson("GET", headPath)
718
+ );
719
+ } finally {
720
+ if (silent) {
721
+ setRefreshing(false);
722
+ } else {
723
+ setLoading(false);
724
+ }
725
+ }
726
+ }, [
727
+ applyHead,
728
+ applyUnread,
729
+ ensureSession,
730
+ fetchJson,
731
+ headPath,
732
+ unreadPath,
733
+ wantsItems
734
+ ]);
735
+ const loadMore = useCallback(async () => {
736
+ const cursor = cursorRef.current;
737
+ if (loadMoreRef.current || !cursor) {
738
+ return loadMoreRef.current ?? void 0;
739
+ }
740
+ setLoadingMore(true);
741
+ const request = (async () => {
742
+ const page = await fetchJson(
743
+ "GET",
744
+ `/widget/inbox?subscriberId=${encodeURIComponent(subscriber.subscriberId)}&limit=${INBOX_PAGE_SIZE}&cursor=${encodeURIComponent(cursor)}${kindsQuery}`
745
+ );
746
+ hasOlderPagesRef.current = true;
747
+ cursorRef.current = page.nextCursor ?? null;
748
+ const older = (page.items ?? []).map(normalizeInboxItem);
749
+ setItems((current) => {
750
+ const seen = new Set(current.map((item) => item._id));
751
+ return [...current, ...older.filter((item) => !seen.has(item._id))];
752
+ });
753
+ setHasMore(cursorRef.current !== null);
754
+ })().finally(() => {
755
+ loadMoreRef.current = null;
756
+ setLoadingMore(false);
757
+ });
758
+ loadMoreRef.current = request;
759
+ return request;
760
+ }, [fetchJson, kindsQuery, subscriber.subscriberId]);
761
+ useEffect(() => {
762
+ hasOlderPagesRef.current = false;
763
+ cursorRef.current = null;
764
+ setHasMore(false);
765
+ }, [wantsItems, kindsQuery]);
766
+ const decrementUnread = useCallback((item) => {
767
+ if (!item || item.readAt) {
768
+ return;
769
+ }
770
+ setUnreadCount((current) => Math.max(0, current - 1));
771
+ if (item.kind) {
772
+ const kind = item.kind;
773
+ setUnreadByKind(
774
+ (current) => kind in current ? { ...current, [kind]: Math.max(0, (current[kind] ?? 0) - 1) } : current
775
+ );
776
+ }
777
+ }, []);
778
+ const markRead = useCallback(
779
+ async (inboxItemId) => {
780
+ const previousItems = items;
781
+ const previousUnreadCount = unreadCount;
782
+ const previousUnreadByKind = unreadByKind;
783
+ const now = Date.now();
784
+ setItems(
785
+ (current) => current.map((item) => item._id === inboxItemId ? { ...item, readAt: now } : item)
786
+ );
787
+ decrementUnread(previousItems.find((item) => item._id === inboxItemId));
788
+ await ensureSession();
789
+ try {
790
+ await fetchJson("POST", "/widget/read", {
791
+ subscriberId: subscriber.subscriberId,
792
+ inboxItemIds: [inboxItemId]
614
793
  });
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]);
625
- /** Unread counters after `item` becomes read, if it was unread. */
626
- const decrementUnread = useCallback((item) => {
627
- if (!item || item.readAt) {
628
- return;
629
- }
630
- setUnreadCount((current) => Math.max(0, current - 1));
631
- if (item.kind) {
632
- const kind = item.kind;
633
- setUnreadByKind((current) => kind in current ? { ...current, [kind]: Math.max(0, (current[kind] ?? 0) - 1) } : current);
634
- }
635
- }, []);
636
- const markRead = useCallback(async (inboxItemId) => {
637
- const previousItems = items;
638
- const previousUnreadCount = unreadCount;
639
- const previousUnreadByKind = unreadByKind;
640
- const now = Date.now();
641
- setItems((current) => current.map((item) => (item._id === inboxItemId ? { ...item, readAt: now } : item)));
794
+ if (!realtimeLiveRef.current) {
795
+ await refresh({ silent: true });
796
+ }
797
+ } catch (error) {
798
+ setItems(previousItems);
799
+ setUnreadCount(previousUnreadCount);
800
+ setUnreadByKind(previousUnreadByKind);
801
+ throw error;
802
+ }
803
+ },
804
+ [
805
+ decrementUnread,
806
+ ensureSession,
807
+ fetchJson,
808
+ items,
809
+ refresh,
810
+ subscriber.subscriberId,
811
+ unreadByKind,
812
+ unreadCount
813
+ ]
814
+ );
815
+ const setArchived = useCallback(
816
+ async (inboxItemId, archived) => {
817
+ const previousItems = items;
818
+ const previousUnreadCount = unreadCount;
819
+ const previousUnreadByKind = unreadByKind;
820
+ if (archived) {
821
+ setItems((current) => current.filter((item) => item._id !== inboxItemId));
642
822
  decrementUnread(previousItems.find((item) => item._id === inboxItemId));
643
- await ensureSession();
644
- try {
645
- await fetchJson("POST", "/widget/read", {
646
- subscriberId: subscriber.subscriberId,
647
- inboxItemIds: [inboxItemId],
648
- });
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
- }
653
- }
654
- catch (error) {
655
- setItems(previousItems);
656
- setUnreadCount(previousUnreadCount);
657
- setUnreadByKind(previousUnreadByKind);
658
- throw error;
659
- }
660
- }, [
661
- decrementUnread,
662
- ensureSession,
663
- fetchJson,
664
- items,
665
- refresh,
666
- subscriber.subscriberId,
667
- unreadByKind,
668
- unreadCount,
669
- ]);
670
- const setArchived = useCallback(async (inboxItemId, archived) => {
671
- const previousItems = items;
672
- const previousUnreadCount = unreadCount;
673
- const previousUnreadByKind = unreadByKind;
674
- // The panel lists active items, so only archiving changes what it shows.
675
- if (archived) {
676
- setItems((current) => current.filter((item) => item._id !== inboxItemId));
677
- decrementUnread(previousItems.find((item) => item._id === inboxItemId));
678
- }
679
- await ensureSession();
680
- try {
681
- await fetchJson("POST", archived ? "/widget/archive" : "/widget/unarchive", {
682
- subscriberId: subscriber.subscriberId,
683
- inboxItemIds: [inboxItemId],
684
- });
685
- if (!realtimeLiveRef.current) {
686
- await refresh({ silent: true });
687
- }
688
- }
689
- catch (error) {
690
- setItems(previousItems);
691
- setUnreadCount(previousUnreadCount);
692
- setUnreadByKind(previousUnreadByKind);
693
- throw error;
694
- }
695
- }, [
696
- decrementUnread,
697
- ensureSession,
698
- fetchJson,
699
- items,
700
- refresh,
701
- subscriber.subscriberId,
702
- unreadByKind,
703
- unreadCount,
704
- ]);
705
- const archive = useCallback((id) => setArchived(id, true), [setArchived]);
706
- const unarchive = useCallback((id) => setArchived(id, false), [setArchived]);
707
- const setActiveTab = useCallback((key) => {
708
- if (key === activeTab) {
709
- return;
710
- }
711
- // Clear the old tab's rows rather than showing them under the new one.
712
- setItems([]);
713
- setLoading(true);
714
- setActiveTabState(key);
715
- }, [activeTab]);
716
- const tabUnreadCount = useCallback((tab) => countTabUnread(tab, unreadCount, unreadByKind), [unreadByKind, unreadCount]);
717
- const markAllRead = useCallback(async () => {
718
- const previousItems = items;
719
- const previousUnreadCount = unreadCount;
720
- const now = Date.now();
721
- const previousUnreadByKind = unreadByKind;
722
- setItems((current) => current.map((item) => (item.readAt ? item : { ...item, readAt: now })));
723
- setUnreadCount(0);
724
- setUnreadByKind((current) => Object.fromEntries(Object.keys(current).map((kind) => [kind, 0])));
725
- await ensureSession();
726
- try {
727
- await fetchJson("POST", "/widget/read-all", {
728
- subscriberId: subscriber.subscriberId,
729
- });
730
- if (!realtimeLiveRef.current) {
731
- await refresh({ silent: true });
732
- }
733
- }
734
- catch (error) {
735
- setItems(previousItems);
736
- setUnreadCount(previousUnreadCount);
737
- setUnreadByKind(previousUnreadByKind);
738
- throw error;
739
- }
740
- }, [ensureSession, fetchJson, items, refresh, subscriber.subscriberId, unreadByKind, unreadCount]);
741
- const registerPushToken = useCallback(async (token, options) => {
742
- const normalizedToken = token.trim();
743
- if (!normalizedToken) {
744
- return;
745
- }
746
- await ensureSession();
747
- await fetchJson("POST", "/widget/push/register", {
748
- subscriberId: subscriber.subscriberId,
749
- pushToken: normalizedToken,
750
- platform: options?.platform ?? "web",
751
- deviceLabel: options?.deviceLabel,
752
- metadata: options?.metadata,
823
+ }
824
+ await ensureSession();
825
+ try {
826
+ await fetchJson("POST", archived ? "/widget/archive" : "/widget/unarchive", {
827
+ subscriberId: subscriber.subscriberId,
828
+ inboxItemIds: [inboxItemId]
753
829
  });
754
- }, [ensureSession, fetchJson, subscriber.subscriberId]);
755
- const unregisterPushToken = useCallback(async (token) => {
756
- const normalizedToken = token.trim();
757
- if (!normalizedToken) {
758
- return;
759
- }
830
+ if (!realtimeLiveRef.current) {
831
+ await refresh({ silent: true });
832
+ }
833
+ } catch (error) {
834
+ setItems(previousItems);
835
+ setUnreadCount(previousUnreadCount);
836
+ setUnreadByKind(previousUnreadByKind);
837
+ throw error;
838
+ }
839
+ },
840
+ [
841
+ decrementUnread,
842
+ ensureSession,
843
+ fetchJson,
844
+ items,
845
+ refresh,
846
+ subscriber.subscriberId,
847
+ unreadByKind,
848
+ unreadCount
849
+ ]
850
+ );
851
+ const archive = useCallback((id) => setArchived(id, true), [setArchived]);
852
+ const unarchive = useCallback((id) => setArchived(id, false), [setArchived]);
853
+ const setActiveTab = useCallback(
854
+ (key) => {
855
+ if (key === activeTab) {
856
+ return;
857
+ }
858
+ setItems([]);
859
+ setLoading(true);
860
+ setActiveTabState(key);
861
+ },
862
+ [activeTab]
863
+ );
864
+ const tabUnreadCount = useCallback(
865
+ (tab) => countTabUnread(tab, unreadCount, unreadByKind),
866
+ [unreadByKind, unreadCount]
867
+ );
868
+ const markAllRead = useCallback(async () => {
869
+ const previousItems = items;
870
+ const previousUnreadCount = unreadCount;
871
+ const now = Date.now();
872
+ const previousUnreadByKind = unreadByKind;
873
+ setItems((current) => current.map((item) => item.readAt ? item : { ...item, readAt: now }));
874
+ setUnreadCount(0);
875
+ setUnreadByKind(
876
+ (current) => Object.fromEntries(Object.keys(current).map((kind) => [kind, 0]))
877
+ );
878
+ await ensureSession();
879
+ try {
880
+ await fetchJson("POST", "/widget/read-all", {
881
+ subscriberId: subscriber.subscriberId
882
+ });
883
+ if (!realtimeLiveRef.current) {
884
+ await refresh({ silent: true });
885
+ }
886
+ } catch (error) {
887
+ setItems(previousItems);
888
+ setUnreadCount(previousUnreadCount);
889
+ setUnreadByKind(previousUnreadByKind);
890
+ throw error;
891
+ }
892
+ }, [ensureSession, fetchJson, items, refresh, subscriber.subscriberId, unreadByKind, unreadCount]);
893
+ const registerPushToken = useCallback(
894
+ async (token, options) => {
895
+ const normalizedToken = token.trim();
896
+ if (!normalizedToken) {
897
+ return;
898
+ }
899
+ await ensureSession();
900
+ await fetchJson("POST", "/widget/push/register", {
901
+ subscriberId: subscriber.subscriberId,
902
+ pushToken: normalizedToken,
903
+ platform: options?.platform ?? "web",
904
+ deviceLabel: options?.deviceLabel,
905
+ metadata: options?.metadata
906
+ });
907
+ },
908
+ [ensureSession, fetchJson, subscriber.subscriberId]
909
+ );
910
+ const unregisterPushToken = useCallback(
911
+ async (token) => {
912
+ const normalizedToken = token.trim();
913
+ if (!normalizedToken) {
914
+ return;
915
+ }
916
+ await ensureSession();
917
+ await fetchJson("POST", "/widget/push/unregister", {
918
+ subscriberId: subscriber.subscriberId,
919
+ pushToken: normalizedToken
920
+ });
921
+ },
922
+ [ensureSession, fetchJson, subscriber.subscriberId]
923
+ );
924
+ const handleActionClick = useCallback(
925
+ async (item) => {
926
+ const actionUrl = item.actionUrl?.trim();
927
+ if (!actionUrl) {
928
+ return;
929
+ }
930
+ const shouldNavigate = await onActionClick?.({
931
+ item,
932
+ actionLabel: item.actionLabel,
933
+ actionUrl
934
+ }) !== false;
935
+ try {
760
936
  await ensureSession();
761
- await fetchJson("POST", "/widget/push/unregister", {
762
- subscriberId: subscriber.subscriberId,
763
- pushToken: normalizedToken,
937
+ await fetchJson("POST", "/widget/action-click", {
938
+ subscriberId: subscriber.subscriberId,
939
+ inboxItemId: item._id,
940
+ actionLabel: item.actionLabel,
941
+ actionUrl
764
942
  });
765
- }, [ensureSession, fetchJson, subscriber.subscriberId]);
766
- const handleActionClick = useCallback(async (item) => {
767
- const actionUrl = item.actionUrl?.trim();
768
- if (!actionUrl) {
769
- return;
770
- }
771
- const shouldNavigate = (await onActionClick?.({
772
- item,
773
- actionLabel: item.actionLabel,
774
- actionUrl,
775
- })) !== false;
776
- try {
777
- await ensureSession();
778
- await fetchJson("POST", "/widget/action-click", {
779
- subscriberId: subscriber.subscriberId,
780
- inboxItemId: item._id,
781
- actionLabel: item.actionLabel,
782
- actionUrl,
783
- });
784
- }
785
- catch {
786
- // Best-effort analytics only.
787
- }
788
- if (!shouldNavigate || typeof window === "undefined") {
789
- return;
790
- }
791
- const target = resolveActionNavigationTarget(actionUrl, actionLinkTarget);
792
- if (target === "_blank") {
793
- window.open(actionUrl, "_blank", "noopener,noreferrer");
794
- return;
795
- }
796
- window.location.assign(actionUrl);
797
- }, [
798
- actionLinkTarget,
799
- ensureSession,
800
- fetchJson,
801
- onActionClick,
802
- subscriber.subscriberId,
803
- ]);
804
- const reconnect = useCallback(async () => {
805
- emitEvent({
806
- type: "realtime.reconnect.manual",
943
+ } catch {
944
+ }
945
+ if (!shouldNavigate || typeof window === "undefined") {
946
+ return;
947
+ }
948
+ const target = resolveActionNavigationTarget(actionUrl, actionLinkTarget);
949
+ if (target === "_blank") {
950
+ window.open(actionUrl, "_blank", "noopener,noreferrer");
951
+ return;
952
+ }
953
+ window.location.assign(actionUrl);
954
+ },
955
+ [
956
+ actionLinkTarget,
957
+ ensureSession,
958
+ fetchJson,
959
+ onActionClick,
960
+ subscriber.subscriberId
961
+ ]
962
+ );
963
+ const reconnect = useCallback(async () => {
964
+ emitEvent({
965
+ type: "realtime.reconnect.manual",
966
+ projectId,
967
+ subscriberId: subscriber.subscriberId
968
+ });
969
+ setConnectionState("connecting");
970
+ setErrorMessage(null);
971
+ setReconnectNonce((n) => n + 1);
972
+ if (canRefreshSession) {
973
+ await refreshSession();
974
+ } else {
975
+ await ensureSession();
976
+ }
977
+ }, [
978
+ canRefreshSession,
979
+ emitEvent,
980
+ ensureSession,
981
+ projectId,
982
+ refreshSession,
983
+ subscriber.subscriberId
984
+ ]);
985
+ useEffect(() => {
986
+ let cancelled = false;
987
+ async function loadConfig() {
988
+ try {
989
+ const config = await fetchWidgetConfigDocument();
990
+ if (!cancelled && config) {
991
+ const next = pickRealtimeSource(config);
992
+ setRealtimeSource(
993
+ (current) => current?.kind === next?.kind && current?.url === next?.url ? current : next
994
+ );
995
+ setServerConfig({ ...DEFAULT_CONFIG, ...config });
996
+ }
997
+ } catch {
998
+ if (!cancelled) {
999
+ setRealtimeSource(null);
1000
+ setServerConfig(DEFAULT_CONFIG);
1001
+ }
1002
+ } finally {
1003
+ if (!cancelled) {
1004
+ setConfigResolved(true);
1005
+ }
1006
+ }
1007
+ }
1008
+ void loadConfig();
1009
+ return () => {
1010
+ cancelled = true;
1011
+ };
1012
+ }, [fetchWidgetConfigDocument]);
1013
+ useEffect(() => {
1014
+ if (!runtimeSessionToken || !runtimeSessionExpiresAt || !hasGetSessionToken) {
1015
+ return;
1016
+ }
1017
+ const refreshInMs = Math.max(runtimeSessionExpiresAt - Date.now() - 6e4, 1e3);
1018
+ const timer = setTimeout(() => {
1019
+ refreshSession().catch(() => void 0);
1020
+ }, refreshInMs);
1021
+ return () => clearTimeout(timer);
1022
+ }, [hasGetSessionToken, refreshSession, runtimeSessionExpiresAt, runtimeSessionToken]);
1023
+ const pushToken = push?.token;
1024
+ const pushPlatform = push?.platform;
1025
+ const pushDeviceLabel = push?.deviceLabel;
1026
+ const pushMetadataKey = push?.metadata ? JSON.stringify(push.metadata) : "";
1027
+ const pushAutoRegister = push?.autoRegister !== false;
1028
+ const pushAutoUnregister = Boolean(push?.autoUnregister);
1029
+ useEffect(() => {
1030
+ if (!pushToken || !pushAutoRegister) {
1031
+ return;
1032
+ }
1033
+ registerPushToken(pushToken, {
1034
+ platform: pushPlatform,
1035
+ deviceLabel: pushDeviceLabel,
1036
+ metadata: pushMetadataKey ? JSON.parse(pushMetadataKey) : void 0
1037
+ }).catch(() => void 0);
1038
+ if (!pushAutoUnregister) {
1039
+ return;
1040
+ }
1041
+ return () => {
1042
+ unregisterPushToken(pushToken).catch(() => void 0);
1043
+ };
1044
+ }, [
1045
+ pushAutoRegister,
1046
+ pushAutoUnregister,
1047
+ pushDeviceLabel,
1048
+ pushMetadataKey,
1049
+ pushPlatform,
1050
+ pushToken,
1051
+ registerPushToken,
1052
+ unregisterPushToken
1053
+ ]);
1054
+ useEffect(() => {
1055
+ if (!realtimeSource) {
1056
+ return;
1057
+ }
1058
+ const client = realtimeSource.kind === "ws" ? createWidgetSocketClient(realtimeSource.url, publishableKey, realtimeLoadersRef) : createConvexClient(realtimeSource.url);
1059
+ realtimeClientRef.current = client;
1060
+ setRealtimeClient(client);
1061
+ return () => {
1062
+ realtimeClientRef.current = null;
1063
+ setRealtimeClient(null);
1064
+ void client.close();
1065
+ };
1066
+ }, [publishableKey, realtimeSource]);
1067
+ useEffect(() => {
1068
+ if (!realtimeClient) {
1069
+ return;
1070
+ }
1071
+ let disposed = false;
1072
+ let retryTimer = null;
1073
+ let firstResultTimer = null;
1074
+ let retryAttempt = 0;
1075
+ let unsubscribe = null;
1076
+ const clearSubscription = () => {
1077
+ if (typeof unsubscribe === "function") {
1078
+ unsubscribe();
1079
+ } else {
1080
+ unsubscribe?.unsubscribe?.();
1081
+ }
1082
+ unsubscribe = null;
1083
+ };
1084
+ function handleSubscriptionError(error, afterSessionRefresh) {
1085
+ clearSubscription();
1086
+ realtimeLiveRef.current = false;
1087
+ if (!afterSessionRefresh && canRefreshSession && /session|token|expired|invalid/i.test(error.message)) {
1088
+ subscribe(true).catch(() => void 0);
1089
+ return;
1090
+ }
1091
+ setLoading(false);
1092
+ setRefreshing(false);
1093
+ setConnectionState("polling");
1094
+ setRealtimeFailed(true);
1095
+ emitEvent({
1096
+ type: "realtime.error",
1097
+ projectId,
1098
+ subscriberId: subscriber.subscriberId,
1099
+ message: error.message
1100
+ });
1101
+ retryAttempt += 1;
1102
+ emitEvent({
1103
+ type: "realtime.retry.scheduled",
1104
+ projectId,
1105
+ subscriberId: subscriber.subscriberId,
1106
+ attempt: retryAttempt,
1107
+ retryInMs: REALTIME_RETRY_MS
1108
+ });
1109
+ retryTimer = setTimeout(() => {
1110
+ subscribe().catch(() => void 0);
1111
+ }, REALTIME_RETRY_MS);
1112
+ }
1113
+ async function subscribe(forceRefreshSession = false) {
1114
+ if (wantsItems && !hasLoadedOnceRef.current) {
1115
+ setLoading(true);
1116
+ }
1117
+ setConnectionState("connecting");
1118
+ emitEvent({
1119
+ type: "realtime.connecting",
1120
+ projectId,
1121
+ subscriberId: subscriber.subscriberId
1122
+ });
1123
+ try {
1124
+ const token = forceRefreshSession ? await refreshSession() : await ensureSession();
1125
+ if (disposed || !realtimeClientRef.current) {
1126
+ return;
1127
+ }
1128
+ clearSubscription();
1129
+ const subscription = realtimeClientRef.current.onUpdate(
1130
+ wantsItems ? "widgetInbox:list" : "widgetInbox:unreadCount",
1131
+ wantsItems ? {
807
1132
  projectId,
1133
+ sessionToken: token,
808
1134
  subscriberId: subscriber.subscriberId,
809
- });
810
- setConnectionState("connecting");
811
- setErrorMessage(null);
812
- // Bump nonce to force the subscribe effect to re-run and re-establish
813
- // the Convex realtime subscription (a REST refresh alone isn't enough).
814
- setReconnectNonce((n) => n + 1);
815
- if (canRefreshSession) {
816
- await refreshSession();
817
- }
818
- else {
819
- await ensureSession();
820
- }
821
- }, [
822
- canRefreshSession,
823
- emitEvent,
824
- ensureSession,
825
- projectId,
826
- refreshSession,
827
- subscriber.subscriberId,
828
- ]);
829
- useEffect(() => {
830
- let cancelled = false;
831
- async function loadConfig() {
832
- try {
833
- const config = await fetchWidgetConfigDocument();
834
- if (!cancelled && config) {
835
- setRealtimeConvexUrl(config.convexUrl ?? null);
836
- setServerConfig({ ...DEFAULT_CONFIG, ...config });
837
- }
838
- }
839
- catch {
840
- if (!cancelled) {
841
- setRealtimeConvexUrl(null);
842
- setServerConfig(DEFAULT_CONFIG);
843
- }
844
- }
845
- finally {
846
- if (!cancelled) {
847
- setConfigResolved(true);
848
- }
849
- }
850
- }
851
- void loadConfig();
852
- return () => {
853
- cancelled = true;
854
- };
855
- }, [fetchWidgetConfigDocument]);
856
- useEffect(() => {
857
- if (!runtimeSessionToken || !runtimeSessionExpiresAt || !hasGetSessionToken) {
858
- return;
859
- }
860
- const refreshInMs = Math.max(runtimeSessionExpiresAt - Date.now() - 60_000, 1_000);
861
- const timer = setTimeout(() => {
862
- refreshSession().catch(() => undefined);
863
- }, refreshInMs);
864
- return () => clearTimeout(timer);
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);
874
- useEffect(() => {
875
- if (!pushToken || !pushAutoRegister) {
876
- return;
877
- }
878
- registerPushToken(pushToken, {
879
- platform: pushPlatform,
880
- deviceLabel: pushDeviceLabel,
881
- metadata: pushMetadataKey ? JSON.parse(pushMetadataKey) : undefined,
882
- }).catch(() => undefined);
883
- if (!pushAutoUnregister) {
884
- return;
885
- }
886
- return () => {
887
- unregisterPushToken(pushToken).catch(() => undefined);
888
- };
889
- }, [
890
- pushAutoRegister,
891
- pushAutoUnregister,
892
- pushDeviceLabel,
893
- pushMetadataKey,
894
- pushPlatform,
895
- pushToken,
896
- registerPushToken,
897
- unregisterPushToken,
898
- ]);
899
- useEffect(() => {
900
- if (!realtimeConvexUrl) {
901
- return;
902
- }
903
- const client = new ConvexClient(realtimeConvexUrl);
904
- convexClientRef.current = client;
905
- setConvexClient(client);
906
- return () => {
907
- convexClientRef.current = null;
908
- setConvexClient(null);
909
- if (typeof client.close === "function") {
910
- client.close();
911
- }
912
- };
913
- }, [realtimeConvexUrl]);
914
- useEffect(() => {
915
- if (!convexClient) {
916
- return;
917
- }
918
- let disposed = false;
919
- let retryTimer = null;
920
- let firstResultTimer = null;
921
- let retryAttempt = 0;
922
- let unsubscribe = null;
923
- const clearSubscription = () => {
924
- if (typeof unsubscribe === "function") {
925
- unsubscribe();
1135
+ limit: INBOX_PAGE_SIZE,
1136
+ ...activeKinds.length ? { kinds: activeKinds } : {},
1137
+ ...unreadKinds.length ? { unreadKinds } : {}
1138
+ } : {
1139
+ projectId,
1140
+ sessionToken: token,
1141
+ subscriberId: subscriber.subscriberId,
1142
+ ...unreadKinds.length ? { kinds: unreadKinds } : {}
1143
+ },
1144
+ (result) => {
1145
+ if (disposed) {
1146
+ return;
926
1147
  }
927
- else {
928
- unsubscribe?.unsubscribe?.();
1148
+ if (firstResultTimer) {
1149
+ clearTimeout(firstResultTimer);
1150
+ firstResultTimer = null;
929
1151
  }
930
- unsubscribe = null;
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;
1152
+ realtimeLiveRef.current = true;
1153
+ setRealtimeFailed(false);
1154
+ if (wantsItems) {
1155
+ applyHead(result ?? {});
1156
+ setLoading(false);
1157
+ } else {
1158
+ applyUnread(result ?? {});
943
1159
  }
944
- setLoading(false);
945
1160
  setRefreshing(false);
946
- setConnectionState("polling");
947
- setRealtimeFailed(true);
1161
+ setConnectionState("live");
1162
+ setErrorMessage(null);
948
1163
  emitEvent({
949
- type: "realtime.error",
950
- projectId,
951
- subscriberId: subscriber.subscriberId,
952
- message: error.message,
1164
+ type: "realtime.live",
1165
+ projectId,
1166
+ subscriberId: subscriber.subscriberId
953
1167
  });
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
- }
966
- async function subscribe(forceRefreshSession = false) {
967
- if (wantsItems && !hasLoadedOnceRef.current) {
968
- setLoading(true);
969
- }
970
- setConnectionState("connecting");
971
- emitEvent({
972
- type: "realtime.connecting",
973
- projectId,
974
- subscriberId: subscriber.subscriberId,
975
- });
976
- try {
977
- const token = forceRefreshSession ? await refreshSession() : await ensureSession();
978
- if (disposed || !convexClientRef.current) {
979
- return;
980
- }
981
- clearSubscription();
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) => {
998
- if (disposed) {
999
- return;
1000
- }
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
- }
1014
- setRefreshing(false);
1015
- setConnectionState("live");
1016
- setErrorMessage(null);
1017
- emitEvent({
1018
- type: "realtime.live",
1019
- projectId,
1020
- subscriberId: subscriber.subscriberId,
1021
- });
1022
- }, (error) => {
1023
- if (!disposed) {
1024
- handleSubscriptionError(error, forceRefreshSession);
1025
- }
1026
- });
1027
- unsubscribe = subscription;
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
- }
1039
- }
1040
- catch (error) {
1041
- if (disposed) {
1042
- return;
1043
- }
1044
- const message = error instanceof Error ? error.message : "Realtime connection failed";
1045
- if (!forceRefreshSession &&
1046
- canRefreshSession &&
1047
- /session|token|expired|invalid/i.test(message)) {
1048
- await subscribe(true);
1049
- return;
1050
- }
1051
- setLoading(false);
1052
- setRefreshing(false);
1053
- setConnectionState("error");
1054
- setErrorMessage(message);
1055
- emitEvent({
1056
- type: "realtime.error",
1057
- projectId,
1058
- subscriberId: subscriber.subscriberId,
1059
- message,
1060
- });
1061
- const backoffMs = Math.min(30_000, 1_000 * 2 ** retryAttempt);
1062
- retryAttempt += 1;
1063
- emitEvent({
1064
- type: "realtime.retry.scheduled",
1065
- projectId,
1066
- subscriberId: subscriber.subscriberId,
1067
- attempt: retryAttempt,
1068
- retryInMs: backoffMs,
1069
- });
1070
- retryTimer = setTimeout(() => {
1071
- subscribe().catch(() => undefined);
1072
- }, backoffMs);
1073
- }
1074
- }
1075
- subscribe().catch(() => {
1168
+ },
1169
+ (error) => {
1076
1170
  if (!disposed) {
1077
- setLoading(false);
1078
- setRefreshing(false);
1079
- setConnectionState("error");
1080
- setErrorMessage("Failed to start realtime updates");
1081
- emitEvent({
1082
- type: "realtime.error",
1083
- projectId,
1084
- subscriberId: subscriber.subscriberId,
1085
- message: "Failed to start realtime updates",
1086
- });
1171
+ handleSubscriptionError(error, forceRefreshSession);
1087
1172
  }
1088
- });
1089
- return () => {
1090
- disposed = true;
1091
- realtimeLiveRef.current = false;
1092
- if (retryTimer) {
1093
- clearTimeout(retryTimer);
1094
- }
1095
- if (firstResultTimer) {
1096
- clearTimeout(firstResultTimer);
1173
+ }
1174
+ );
1175
+ unsubscribe = subscription;
1176
+ retryAttempt = 0;
1177
+ if (!realtimeLiveRef.current && !firstResultTimer) {
1178
+ firstResultTimer = setTimeout(() => {
1179
+ firstResultTimer = null;
1180
+ if (!disposed && !realtimeLiveRef.current) {
1181
+ setRealtimeFailed(true);
1097
1182
  }
1098
- if (typeof unsubscribe === "function") {
1099
- unsubscribe();
1100
- }
1101
- else {
1102
- unsubscribe?.unsubscribe?.();
1103
- }
1104
- };
1105
- }, [
1106
- activeKinds,
1107
- applyHead,
1108
- applyUnread,
1109
- canRefreshSession,
1110
- convexClient,
1111
- emitEvent,
1112
- ensureSession,
1113
- pollIntervalMs,
1114
- projectId,
1115
- reconnectNonce,
1116
- unreadKinds,
1117
- refreshSession,
1118
- subscriber.subscriberId,
1119
- wantsItems,
1120
- ]);
1121
- useEffect(() => {
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;
1183
+ }, Math.max(pollIntervalMs, 5e3));
1126
1184
  }
1127
- setConnectionState("polling");
1185
+ } catch (error) {
1186
+ if (disposed) {
1187
+ return;
1188
+ }
1189
+ const message = error instanceof Error ? error.message : "Realtime connection failed";
1190
+ if (!forceRefreshSession && canRefreshSession && /session|token|expired|invalid/i.test(message)) {
1191
+ await subscribe(true);
1192
+ return;
1193
+ }
1194
+ setLoading(false);
1195
+ setRefreshing(false);
1196
+ setConnectionState("error");
1197
+ setErrorMessage(message);
1128
1198
  emitEvent({
1129
- type: "transport.polling",
1130
- projectId,
1131
- subscriberId: subscriber.subscriberId,
1199
+ type: "realtime.error",
1200
+ projectId,
1201
+ subscriberId: subscriber.subscriberId,
1202
+ message
1132
1203
  });
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,
1204
+ const backoffMs = Math.min(3e4, 1e3 * 2 ** retryAttempt);
1205
+ retryAttempt += 1;
1206
+ emitEvent({
1207
+ type: "realtime.retry.scheduled",
1208
+ projectId,
1209
+ subscriberId: subscriber.subscriberId,
1210
+ attempt: retryAttempt,
1211
+ retryInMs: backoffMs
1212
+ });
1213
+ retryTimer = setTimeout(() => {
1214
+ subscribe().catch(() => void 0);
1215
+ }, backoffMs);
1216
+ }
1217
+ }
1218
+ subscribe().catch(() => {
1219
+ if (!disposed) {
1220
+ setLoading(false);
1221
+ setRefreshing(false);
1222
+ setConnectionState("error");
1223
+ setErrorMessage("Failed to start realtime updates");
1224
+ emitEvent({
1225
+ type: "realtime.error",
1226
+ projectId,
1227
+ subscriberId: subscriber.subscriberId,
1228
+ message: "Failed to start realtime updates"
1229
+ });
1230
+ }
1231
+ });
1232
+ return () => {
1233
+ disposed = true;
1234
+ realtimeLiveRef.current = false;
1235
+ if (retryTimer) {
1236
+ clearTimeout(retryTimer);
1237
+ }
1238
+ if (firstResultTimer) {
1239
+ clearTimeout(firstResultTimer);
1240
+ }
1241
+ if (typeof unsubscribe === "function") {
1242
+ unsubscribe();
1243
+ } else {
1244
+ unsubscribe?.unsubscribe?.();
1245
+ }
1246
+ };
1247
+ }, [
1248
+ activeKinds,
1249
+ applyHead,
1250
+ applyUnread,
1251
+ canRefreshSession,
1252
+ realtimeClient,
1253
+ emitEvent,
1254
+ ensureSession,
1255
+ pollIntervalMs,
1256
+ projectId,
1257
+ reconnectNonce,
1258
+ unreadKinds,
1259
+ refreshSession,
1260
+ subscriber.subscriberId,
1261
+ wantsItems
1262
+ ]);
1263
+ useEffect(() => {
1264
+ if (!configResolved || realtimeSource && !realtimeFailed) {
1265
+ return;
1266
+ }
1267
+ setConnectionState("polling");
1268
+ emitEvent({
1269
+ type: "transport.polling",
1270
+ projectId,
1271
+ subscriberId: subscriber.subscriberId
1272
+ });
1273
+ let disposed = false;
1274
+ let timer = null;
1275
+ let failures = 0;
1276
+ const schedule = () => {
1277
+ if (timer) {
1278
+ clearTimeout(timer);
1279
+ timer = null;
1280
+ }
1281
+ if (disposed || isPageHidden()) {
1282
+ return;
1283
+ }
1284
+ const delayMs = Math.max(
1185
1285
  pollIntervalMs,
1186
- projectId,
1187
- realtimeConvexUrl,
1188
- realtimeFailed,
1189
- refresh,
1190
- subscriber.subscriberId,
1191
- ]);
1192
- const effectiveConfig = useMemo(() => {
1193
- const merged = {
1194
- ...serverConfig,
1195
- ...customization,
1196
- };
1197
- return {
1198
- modeDefault: theme,
1199
- accentColor: merged.accentColor ?? DEFAULT_CONFIG.accentColor,
1200
- radius: merged.radius ?? DEFAULT_CONFIG.radius,
1201
- fontScale: merged.fontScale ?? DEFAULT_CONFIG.fontScale,
1202
- compact: merged.compact ?? DEFAULT_CONFIG.compact,
1203
- showTopicTabs: merged.showTopicTabs ?? DEFAULT_CONFIG.showTopicTabs,
1204
- showMarkAll: merged.showMarkAll ?? DEFAULT_CONFIG.showMarkAll,
1205
- headerTitle: merged.headerTitle ?? DEFAULT_CONFIG.headerTitle,
1206
- showDismiss: merged.showDismiss ?? DEFAULT_CONFIG.showDismiss,
1207
- };
1208
- }, [customization, serverConfig, theme]);
1209
- const value = useMemo(() => ({
1210
- open,
1211
- setOpen,
1212
- unreadCount,
1213
- items,
1214
- loading,
1215
- refreshing,
1216
- connectionState,
1217
- errorMessage,
1218
- refresh,
1219
- reconnect,
1220
- markRead,
1221
- markAllRead,
1222
- archive,
1223
- unarchive,
1224
- unreadByKind,
1225
- hasMore,
1226
- loadingMore,
1227
- loadMore,
1228
- tabs: stableTabs,
1229
- activeTab,
1230
- setActiveTab,
1231
- tabUnreadCount,
1232
- registerPushToken,
1233
- unregisterPushToken,
1234
- handleActionClick,
1235
- effectiveConfig,
1236
- triggerRef,
1237
- }), [
1238
- archive,
1239
- unarchive,
1240
- unreadByKind,
1241
- hasMore,
1242
- loadingMore,
1243
- loadMore,
1244
- stableTabs,
1245
- activeTab,
1246
- setActiveTab,
1247
- tabUnreadCount,
1248
- open,
1249
- unreadCount,
1250
- items,
1251
- loading,
1252
- refreshing,
1253
- connectionState,
1254
- errorMessage,
1255
- refresh,
1256
- reconnect,
1257
- markRead,
1258
- markAllRead,
1259
- registerPushToken,
1260
- unregisterPushToken,
1261
- handleActionClick,
1262
- effectiveConfig,
1263
- ]);
1264
- return (_jsx(ItemsDemandCtx.Provider, { value: registerItemsDemand, children: _jsx(Ctx.Provider, { value: value, children: children }) }));
1265
- }
1266
- function useInboxContext(hookName) {
1267
- const ctx = useContext(Ctx);
1268
- if (!ctx) {
1269
- throw new Error(`${hookName} must be used inside BeeperInboxProvider`);
1286
+ Math.min(pollIntervalMs * 2 ** failures, MAX_POLL_BACKOFF_MS)
1287
+ );
1288
+ timer = setTimeout(() => {
1289
+ timer = null;
1290
+ poll({ silent: true });
1291
+ }, delayMs);
1292
+ };
1293
+ const poll = (options) => {
1294
+ refresh(options).then(
1295
+ () => {
1296
+ failures = 0;
1297
+ },
1298
+ () => {
1299
+ failures += 1;
1300
+ }
1301
+ ).finally(schedule);
1302
+ };
1303
+ const onVisibilityChange = () => {
1304
+ if (isPageHidden()) {
1305
+ schedule();
1306
+ } else {
1307
+ poll({ silent: true });
1308
+ }
1309
+ };
1310
+ poll();
1311
+ if (typeof document !== "undefined") {
1312
+ document.addEventListener("visibilitychange", onVisibilityChange);
1270
1313
  }
1271
- return ctx;
1314
+ return () => {
1315
+ disposed = true;
1316
+ if (timer) {
1317
+ clearTimeout(timer);
1318
+ }
1319
+ if (typeof document !== "undefined") {
1320
+ document.removeEventListener("visibilitychange", onVisibilityChange);
1321
+ }
1322
+ };
1323
+ }, [
1324
+ configResolved,
1325
+ emitEvent,
1326
+ pollIntervalMs,
1327
+ projectId,
1328
+ realtimeSource,
1329
+ realtimeFailed,
1330
+ refresh,
1331
+ subscriber.subscriberId
1332
+ ]);
1333
+ const effectiveConfig = useMemo(() => {
1334
+ const merged = {
1335
+ ...serverConfig,
1336
+ ...customization
1337
+ };
1338
+ return {
1339
+ modeDefault: theme,
1340
+ accentColor: merged.accentColor ?? DEFAULT_CONFIG.accentColor,
1341
+ radius: merged.radius ?? DEFAULT_CONFIG.radius,
1342
+ fontScale: merged.fontScale ?? DEFAULT_CONFIG.fontScale,
1343
+ compact: merged.compact ?? DEFAULT_CONFIG.compact,
1344
+ showTopicTabs: merged.showTopicTabs ?? DEFAULT_CONFIG.showTopicTabs,
1345
+ showMarkAll: merged.showMarkAll ?? DEFAULT_CONFIG.showMarkAll,
1346
+ headerTitle: merged.headerTitle ?? DEFAULT_CONFIG.headerTitle,
1347
+ showDismiss: merged.showDismiss ?? DEFAULT_CONFIG.showDismiss
1348
+ };
1349
+ }, [customization, serverConfig, theme]);
1350
+ const value = useMemo(
1351
+ () => ({
1352
+ open,
1353
+ setOpen,
1354
+ unreadCount,
1355
+ items,
1356
+ loading,
1357
+ refreshing,
1358
+ connectionState,
1359
+ errorMessage,
1360
+ refresh,
1361
+ reconnect,
1362
+ markRead,
1363
+ markAllRead,
1364
+ archive,
1365
+ unarchive,
1366
+ unreadByKind,
1367
+ hasMore,
1368
+ loadingMore,
1369
+ loadMore,
1370
+ tabs: stableTabs,
1371
+ activeTab,
1372
+ setActiveTab,
1373
+ tabUnreadCount,
1374
+ registerPushToken,
1375
+ unregisterPushToken,
1376
+ handleActionClick,
1377
+ effectiveConfig,
1378
+ triggerRef
1379
+ }),
1380
+ [
1381
+ archive,
1382
+ unarchive,
1383
+ unreadByKind,
1384
+ hasMore,
1385
+ loadingMore,
1386
+ loadMore,
1387
+ stableTabs,
1388
+ activeTab,
1389
+ setActiveTab,
1390
+ tabUnreadCount,
1391
+ open,
1392
+ unreadCount,
1393
+ items,
1394
+ loading,
1395
+ refreshing,
1396
+ connectionState,
1397
+ errorMessage,
1398
+ refresh,
1399
+ reconnect,
1400
+ markRead,
1401
+ markAllRead,
1402
+ registerPushToken,
1403
+ unregisterPushToken,
1404
+ handleActionClick,
1405
+ effectiveConfig
1406
+ ]
1407
+ );
1408
+ return /* @__PURE__ */ jsx(ItemsDemandCtx.Provider, { value: registerItemsDemand, children: /* @__PURE__ */ jsx(Ctx.Provider, { value, children }) });
1272
1409
  }
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;
1410
+ function useInboxContext(hookName) {
1411
+ const ctx = useContext(Ctx);
1412
+ if (!ctx) {
1413
+ throw new Error(`${hookName} must be used inside BeeperInboxProvider`);
1414
+ }
1415
+ return ctx;
1283
1416
  }
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 };
1417
+ function useBeeperInbox() {
1418
+ const ctx = useInboxContext("useBeeperInbox");
1419
+ const registerItemsDemand = useContext(ItemsDemandCtx);
1420
+ useEffect(() => registerItemsDemand?.(), [registerItemsDemand]);
1421
+ return ctx;
1288
1422
  }
1289
- function BellGlyph({ size = 20, color = "currentColor", }) {
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" })] }));
1423
+ function useBeeperInboxUnreadCount() {
1424
+ const { unreadCount, unreadByKind, tabUnreadCount } = useInboxContext("useBeeperInboxUnreadCount");
1425
+ return { unreadCount, unreadByKind, tabUnreadCount };
1291
1426
  }
1292
- export function BeeperInboxBell({ variant = "bell", label = "Inbox", className, style, "aria-label": ariaLabel = "Open notifications", renderTrigger, }) {
1293
- const { open, setOpen, unreadCount, effectiveConfig, triggerRef } = useInboxContext("BeeperInboxBell");
1294
- const toggle = () => setOpen(!open);
1295
- const fs = effectiveConfig.fontScale;
1296
- const triggerAriaLabel = unreadCount > 0 ? `${ariaLabel}, ${unreadCount} unread` : ariaLabel;
1297
- if (renderTrigger) {
1298
- return (_jsx(_Fragment, { children: renderTrigger({
1299
- unreadCount,
1300
- open,
1301
- toggle,
1302
- accentColor: effectiveConfig.accentColor,
1303
- fontScale: fs,
1304
- triggerRef,
1305
- }) }));
1427
+ function BellGlyph({
1428
+ size = 20,
1429
+ color = "currentColor"
1430
+ }) {
1431
+ return /* @__PURE__ */ jsxs(
1432
+ "svg",
1433
+ {
1434
+ width: size,
1435
+ height: size,
1436
+ viewBox: "0 0 24 24",
1437
+ fill: "none",
1438
+ xmlns: "http://www.w3.org/2000/svg",
1439
+ "aria-hidden": true,
1440
+ children: [
1441
+ /* @__PURE__ */ jsx(
1442
+ "path",
1443
+ {
1444
+ d: "M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9",
1445
+ stroke: color,
1446
+ strokeWidth: "2",
1447
+ strokeLinecap: "round",
1448
+ strokeLinejoin: "round"
1449
+ }
1450
+ ),
1451
+ /* @__PURE__ */ jsx(
1452
+ "path",
1453
+ {
1454
+ d: "M13.73 21a2 2 0 0 1-3.46 0",
1455
+ stroke: color,
1456
+ strokeWidth: "2",
1457
+ strokeLinecap: "round",
1458
+ strokeLinejoin: "round"
1459
+ }
1460
+ )
1461
+ ]
1306
1462
  }
1307
- if (variant === "minimal") {
1308
- return (_jsxs("button", { type: "button", ref: (el) => {
1309
- triggerRef.current = el;
1310
- }, className: className, "aria-label": triggerAriaLabel, "aria-expanded": open, "aria-controls": "beeper-inbox-panel", onClick: toggle, style: {
1463
+ );
1464
+ }
1465
+ function BeeperInboxBell({
1466
+ variant = "bell",
1467
+ label = "Inbox",
1468
+ className,
1469
+ style,
1470
+ "aria-label": ariaLabel = "Open notifications",
1471
+ renderTrigger
1472
+ }) {
1473
+ const { open, setOpen, unreadCount, effectiveConfig, triggerRef } = useInboxContext("BeeperInboxBell");
1474
+ const toggle = () => setOpen(!open);
1475
+ const fs = effectiveConfig.fontScale;
1476
+ const triggerAriaLabel = unreadCount > 0 ? `${ariaLabel}, ${unreadCount} unread` : ariaLabel;
1477
+ if (renderTrigger) {
1478
+ return /* @__PURE__ */ jsx(Fragment, { children: renderTrigger({
1479
+ unreadCount,
1480
+ open,
1481
+ toggle,
1482
+ accentColor: effectiveConfig.accentColor,
1483
+ fontScale: fs,
1484
+ triggerRef
1485
+ }) });
1486
+ }
1487
+ if (variant === "minimal") {
1488
+ return /* @__PURE__ */ jsxs(
1489
+ "button",
1490
+ {
1491
+ type: "button",
1492
+ ref: (el) => {
1493
+ triggerRef.current = el;
1494
+ },
1495
+ className,
1496
+ "aria-label": triggerAriaLabel,
1497
+ "aria-expanded": open,
1498
+ "aria-controls": "beeper-inbox-panel",
1499
+ onClick: toggle,
1500
+ style: {
1501
+ borderRadius: 999,
1502
+ border: "1px solid #d1d5db",
1503
+ padding: "8px 12px",
1504
+ background: "white",
1505
+ display: "inline-flex",
1506
+ alignItems: "center",
1507
+ gap: 8,
1508
+ fontSize: `${14 * fs}px`,
1509
+ cursor: "pointer",
1510
+ ...style
1511
+ },
1512
+ children: [
1513
+ /* @__PURE__ */ jsx("span", { children: label }),
1514
+ /* @__PURE__ */ jsx(
1515
+ "span",
1516
+ {
1517
+ style: {
1518
+ background: effectiveConfig.accentColor,
1519
+ color: "white",
1311
1520
  borderRadius: 999,
1312
- border: "1px solid #d1d5db",
1313
- padding: "8px 12px",
1314
- background: "white",
1315
- display: "inline-flex",
1316
- alignItems: "center",
1317
- gap: 8,
1318
- fontSize: `${14 * fs}px`,
1319
- cursor: "pointer",
1320
- ...style,
1321
- }, children: [_jsx("span", { children: label }), _jsx("span", { style: {
1322
- background: effectiveConfig.accentColor,
1323
- color: "white",
1324
- borderRadius: 999,
1325
- padding: "2px 8px",
1326
- fontSize: 12,
1327
- minWidth: "1.25rem",
1328
- minHeight: "1.25rem",
1329
- textAlign: "center",
1330
- }, children: unreadCount })] }));
1521
+ padding: "2px 8px",
1522
+ fontSize: 12,
1523
+ minWidth: "1.25rem",
1524
+ minHeight: "1.25rem",
1525
+ textAlign: "center"
1526
+ },
1527
+ children: unreadCount
1528
+ }
1529
+ )
1530
+ ]
1531
+ }
1532
+ );
1533
+ }
1534
+ const useHostStyles = !className;
1535
+ return /* @__PURE__ */ jsxs(
1536
+ "button",
1537
+ {
1538
+ type: "button",
1539
+ ref: (el) => {
1540
+ triggerRef.current = el;
1541
+ },
1542
+ className,
1543
+ "aria-label": triggerAriaLabel,
1544
+ "aria-expanded": open,
1545
+ "aria-controls": "beeper-inbox-panel",
1546
+ onClick: toggle,
1547
+ style: {
1548
+ position: "relative",
1549
+ display: "inline-flex",
1550
+ alignItems: "center",
1551
+ justifyContent: "center",
1552
+ ...useHostStyles ? {
1553
+ width: `${44 * fs}px`,
1554
+ height: `${44 * fs}px`,
1555
+ borderRadius: 999,
1556
+ border: "1px solid #d1d5db",
1557
+ background: "white",
1558
+ color: "#374151"
1559
+ } : {},
1560
+ cursor: "pointer",
1561
+ padding: 0,
1562
+ ...style
1563
+ },
1564
+ children: [
1565
+ /* @__PURE__ */ jsx(BellGlyph, { size: Math.round(20 * fs) }),
1566
+ unreadCount > 0 ? /* @__PURE__ */ jsx(
1567
+ "span",
1568
+ {
1569
+ style: {
1570
+ position: "absolute",
1571
+ top: 2,
1572
+ right: 2,
1573
+ minWidth: "1rem",
1574
+ height: "1rem",
1575
+ padding: unreadCount > 9 ? "0 4px" : 0,
1576
+ borderRadius: 999,
1577
+ background: effectiveConfig.accentColor,
1578
+ color: "white",
1579
+ fontSize: 10,
1580
+ fontWeight: 600,
1581
+ display: "flex",
1582
+ alignItems: "center",
1583
+ justifyContent: "center",
1584
+ lineHeight: 1
1585
+ },
1586
+ children: unreadCount > 99 ? "99+" : unreadCount
1587
+ }
1588
+ ) : null
1589
+ ]
1331
1590
  }
1332
- const useHostStyles = !className;
1333
- return (_jsxs("button", { type: "button", ref: (el) => {
1334
- triggerRef.current = el;
1335
- }, className: className, "aria-label": triggerAriaLabel, "aria-expanded": open, "aria-controls": "beeper-inbox-panel", onClick: toggle, style: {
1336
- position: "relative",
1337
- display: "inline-flex",
1338
- alignItems: "center",
1339
- justifyContent: "center",
1340
- ...(useHostStyles
1341
- ? {
1342
- width: `${44 * fs}px`,
1343
- height: `${44 * fs}px`,
1344
- borderRadius: 999,
1345
- border: "1px solid #d1d5db",
1346
- background: "white",
1347
- color: "#374151",
1348
- }
1349
- : {}),
1350
- cursor: "pointer",
1351
- padding: 0,
1352
- ...style,
1353
- }, children: [_jsx(BellGlyph, { size: Math.round(20 * fs) }), unreadCount > 0 ? (_jsx("span", { style: {
1354
- position: "absolute",
1355
- top: 2,
1356
- right: 2,
1357
- minWidth: "1rem",
1358
- height: "1rem",
1359
- padding: unreadCount > 9 ? "0 4px" : 0,
1360
- borderRadius: 999,
1361
- background: effectiveConfig.accentColor,
1362
- color: "white",
1363
- fontSize: 10,
1364
- fontWeight: 600,
1365
- display: "flex",
1366
- alignItems: "center",
1367
- justifyContent: "center",
1368
- lineHeight: 1,
1369
- }, children: unreadCount > 99 ? "99+" : unreadCount })) : null] }));
1591
+ );
1370
1592
  }
1371
1593
  function ShadowContainer({ children }) {
1372
- const hostRef = useRef(null);
1373
- const [portalTarget, setPortalTarget] = useState(null);
1374
- useLayoutEffect(() => {
1375
- const el = hostRef.current;
1376
- if (!el) {
1377
- return;
1378
- }
1379
- let root = el.shadowRoot;
1380
- if (!root) {
1381
- root = el.attachShadow({ mode: "open" });
1382
- }
1383
- setPortalTarget(root);
1384
- return () => {
1385
- setPortalTarget(null);
1386
- };
1387
- }, []);
1388
- return (_jsx("div", { ref: hostRef, children: portalTarget
1389
- ? createPortal(_jsxs(_Fragment, { children: [_jsx("style", { children: `
1594
+ const hostRef = useRef(null);
1595
+ const [portalTarget, setPortalTarget] = useState(null);
1596
+ useLayoutEffect(() => {
1597
+ const el = hostRef.current;
1598
+ if (!el) {
1599
+ return;
1600
+ }
1601
+ let root = el.shadowRoot;
1602
+ if (!root) {
1603
+ root = el.attachShadow({ mode: "open" });
1604
+ }
1605
+ setPortalTarget(root);
1606
+ return () => {
1607
+ setPortalTarget(null);
1608
+ };
1609
+ }, []);
1610
+ return /* @__PURE__ */ jsx("div", { ref: hostRef, children: portalTarget ? createPortal(
1611
+ /* @__PURE__ */ jsxs(Fragment, { children: [
1612
+ /* @__PURE__ */ jsx("style", { children: `
1390
1613
  :host { all: initial; display: block; }
1391
1614
  .bw-root { font-family: Manrope, ui-sans-serif, system-ui, sans-serif; width: 100%; max-width: 100%; box-sizing: border-box; }
1392
- ` }), children] }), portalTarget)
1393
- : null }));
1615
+ ` }),
1616
+ children
1617
+ ] }),
1618
+ portalTarget
1619
+ ) : null });
1394
1620
  }
1395
- const PANEL_WIDTH = 384;
1396
- const PANEL_ESTIMATE_HEIGHT = 440;
1397
- export function BeeperInboxPanel({ placement = "anchor", } = {}) {
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");
1399
- const [layout, setLayout] = useState({ top: 16, right: 16, maxListHeight: 320 });
1400
- const panelRef = useRef(null);
1401
- useEffect(() => {
1402
- if (!open) {
1403
- return;
1404
- }
1405
- const isInsideNode = (event, node) => {
1406
- if (!node) {
1407
- return false;
1408
- }
1409
- const path = typeof event.composedPath === "function" ? event.composedPath() : undefined;
1410
- if (path && path.includes(node)) {
1411
- return true;
1412
- }
1413
- const target = event.target;
1414
- return target instanceof Node ? node.contains(target) : false;
1415
- };
1416
- const handleInteractOutside = (event) => {
1417
- if (isInsideNode(event, panelRef.current)) {
1418
- return;
1419
- }
1420
- if (isInsideNode(event, triggerRef.current)) {
1421
- return;
1422
- }
1423
- setOpen(false);
1424
- };
1425
- document.addEventListener("pointerdown", handleInteractOutside, true);
1426
- document.addEventListener("focusin", handleInteractOutside, true);
1427
- return () => {
1428
- document.removeEventListener("pointerdown", handleInteractOutside, true);
1429
- document.removeEventListener("focusin", handleInteractOutside, true);
1430
- };
1431
- }, [open, setOpen, triggerRef]);
1432
- useEffect(() => {
1433
- if (!open) {
1434
- return;
1435
- }
1436
- const trigger = triggerRef.current;
1437
- const frame = requestAnimationFrame(() => panelRef.current?.focus());
1438
- const handleKeyDown = (event) => {
1439
- if (event.key === "Escape") {
1440
- event.preventDefault();
1441
- setOpen(false);
1442
- }
1443
- };
1444
- document.addEventListener("keydown", handleKeyDown);
1445
- return () => {
1446
- cancelAnimationFrame(frame);
1447
- document.removeEventListener("keydown", handleKeyDown);
1448
- const active = document.activeElement;
1449
- if (trigger && (active === panelRef.current || panelRef.current?.contains(active))) {
1450
- trigger.focus();
1451
- }
1452
- };
1453
- }, [open, setOpen, triggerRef]);
1454
- useLayoutEffect(() => {
1455
- if (!open) {
1456
- return;
1457
- }
1458
- const gap = 10;
1459
- const chrome = 168;
1460
- const compute = () => {
1461
- const w = window.innerWidth;
1462
- const h = window.innerHeight;
1463
- if (placement === "fixed-bottom-end") {
1464
- const top = Math.max(8, h - PANEL_ESTIMATE_HEIGHT - 16);
1465
- setLayout({
1466
- top,
1467
- right: 16,
1468
- maxListHeight: Math.max(180, Math.min(400, h - top - chrome)),
1469
- });
1470
- return;
1471
- }
1472
- const el = triggerRef.current;
1473
- if (!el) {
1474
- setLayout({
1475
- top: gap,
1476
- right: gap,
1477
- maxListHeight: Math.max(180, Math.min(400, h - gap - chrome)),
1478
- });
1479
- return;
1480
- }
1481
- const r = el.getBoundingClientRect();
1482
- let top = r.bottom + gap;
1483
- let right = w - r.right;
1484
- right = Math.max(8, Math.min(right, w - PANEL_WIDTH - 8));
1485
- if (top + PANEL_ESTIMATE_HEIGHT > h - 8) {
1486
- const above = r.top - PANEL_ESTIMATE_HEIGHT - gap;
1487
- top = above >= 8 ? above : Math.max(8, h - PANEL_ESTIMATE_HEIGHT - 8);
1488
- }
1489
- const maxList = Math.max(180, Math.min(440, h - top - chrome));
1490
- setLayout({ top, right, maxListHeight: maxList });
1491
- };
1492
- compute();
1493
- const ro = new ResizeObserver(compute);
1494
- if (triggerRef.current) {
1495
- ro.observe(triggerRef.current);
1496
- }
1497
- window.addEventListener("resize", compute);
1498
- window.addEventListener("scroll", compute, true);
1499
- return () => {
1500
- ro.disconnect();
1501
- window.removeEventListener("resize", compute);
1502
- window.removeEventListener("scroll", compute, true);
1503
- };
1504
- }, [open, placement, triggerRef]);
1621
+ var PANEL_WIDTH = 384;
1622
+ var PANEL_ESTIMATE_HEIGHT = 440;
1623
+ function BeeperInboxPanel({
1624
+ placement = "anchor"
1625
+ } = {}) {
1626
+ const {
1627
+ open,
1628
+ setOpen,
1629
+ items,
1630
+ loading,
1631
+ refreshing,
1632
+ connectionState,
1633
+ errorMessage,
1634
+ refresh,
1635
+ reconnect,
1636
+ markRead,
1637
+ markAllRead,
1638
+ archive,
1639
+ tabs,
1640
+ activeTab,
1641
+ setActiveTab,
1642
+ tabUnreadCount,
1643
+ handleActionClick,
1644
+ effectiveConfig,
1645
+ triggerRef,
1646
+ hasMore,
1647
+ loadingMore,
1648
+ loadMore
1649
+ } = useInboxContext("BeeperInboxPanel");
1650
+ const [layout, setLayout] = useState({ top: 16, right: 16, maxListHeight: 320 });
1651
+ const panelRef = useRef(null);
1652
+ useEffect(() => {
1505
1653
  if (!open) {
1506
- return null;
1654
+ return;
1507
1655
  }
1508
- const mode = resolveTheme(effectiveConfig.modeDefault);
1509
- const dark = mode === "dark";
1510
- const light = {
1511
- bg: "#fffaf5",
1512
- fg: "#2b221d",
1513
- muted: "#7d685d",
1514
- border: "#eadbcc",
1515
- surface: "#fffdf9",
1516
- itemBg: "#fffcf8",
1517
- shadow: "0 24px 54px rgba(38, 24, 12, 0.14)",
1656
+ const isInsideNode = (event, node) => {
1657
+ if (!node) {
1658
+ return false;
1659
+ }
1660
+ const path = typeof event.composedPath === "function" ? event.composedPath() : void 0;
1661
+ if (path && path.includes(node)) {
1662
+ return true;
1663
+ }
1664
+ const target = event.target;
1665
+ return target instanceof Node ? node.contains(target) : false;
1518
1666
  };
1519
- const toolbarBtn = dark
1520
- ? {
1521
- border: "1px solid #3a4250",
1522
- background: "rgba(255,255,255,0.02)",
1523
- color: "#e5e7eb",
1524
- borderRadius: effectiveConfig.radius - 4,
1525
- padding: "6px 10px",
1526
- fontSize: "0.85em",
1527
- cursor: "pointer",
1528
- }
1529
- : {
1530
- border: `1px solid ${light.border}`,
1531
- background: light.surface,
1532
- color: light.fg,
1533
- borderRadius: effectiveConfig.radius - 4,
1534
- padding: "6px 10px",
1535
- fontSize: "0.85em",
1536
- cursor: "pointer",
1537
- };
1538
- const linkBtn = {
1539
- border: "none",
1540
- background: "transparent",
1541
- color: effectiveConfig.accentColor,
1542
- cursor: "pointer",
1543
- fontSize: "0.88em",
1544
- fontWeight: 600,
1545
- padding: "4px 0",
1667
+ const handleInteractOutside = (event) => {
1668
+ if (isInsideNode(event, panelRef.current)) {
1669
+ return;
1670
+ }
1671
+ if (isInsideNode(event, triggerRef.current)) {
1672
+ return;
1673
+ }
1674
+ setOpen(false);
1675
+ };
1676
+ document.addEventListener("pointerdown", handleInteractOutside, true);
1677
+ document.addEventListener("focusin", handleInteractOutside, true);
1678
+ return () => {
1679
+ document.removeEventListener("pointerdown", handleInteractOutside, true);
1680
+ document.removeEventListener("focusin", handleInteractOutside, true);
1681
+ };
1682
+ }, [open, setOpen, triggerRef]);
1683
+ useEffect(() => {
1684
+ if (!open) {
1685
+ return;
1686
+ }
1687
+ const trigger = triggerRef.current;
1688
+ const frame = requestAnimationFrame(() => panelRef.current?.focus());
1689
+ const handleKeyDown = (event) => {
1690
+ if (event.key === "Escape") {
1691
+ event.preventDefault();
1692
+ setOpen(false);
1693
+ }
1694
+ };
1695
+ document.addEventListener("keydown", handleKeyDown);
1696
+ return () => {
1697
+ cancelAnimationFrame(frame);
1698
+ document.removeEventListener("keydown", handleKeyDown);
1699
+ const active = document.activeElement;
1700
+ if (trigger && (active === panelRef.current || panelRef.current?.contains(active))) {
1701
+ trigger.focus();
1702
+ }
1703
+ };
1704
+ }, [open, setOpen, triggerRef]);
1705
+ useLayoutEffect(() => {
1706
+ if (!open) {
1707
+ return;
1708
+ }
1709
+ const gap = 10;
1710
+ const chrome = 168;
1711
+ const compute = () => {
1712
+ const w = window.innerWidth;
1713
+ const h = window.innerHeight;
1714
+ if (placement === "fixed-bottom-end") {
1715
+ const top2 = Math.max(8, h - PANEL_ESTIMATE_HEIGHT - 16);
1716
+ setLayout({
1717
+ top: top2,
1718
+ right: 16,
1719
+ maxListHeight: Math.max(180, Math.min(400, h - top2 - chrome))
1720
+ });
1721
+ return;
1722
+ }
1723
+ const el = triggerRef.current;
1724
+ if (!el) {
1725
+ setLayout({
1726
+ top: gap,
1727
+ right: gap,
1728
+ maxListHeight: Math.max(180, Math.min(400, h - gap - chrome))
1729
+ });
1730
+ return;
1731
+ }
1732
+ const r = el.getBoundingClientRect();
1733
+ let top = r.bottom + gap;
1734
+ let right = w - r.right;
1735
+ right = Math.max(8, Math.min(right, w - PANEL_WIDTH - 8));
1736
+ if (top + PANEL_ESTIMATE_HEIGHT > h - 8) {
1737
+ const above = r.top - PANEL_ESTIMATE_HEIGHT - gap;
1738
+ top = above >= 8 ? above : Math.max(8, h - PANEL_ESTIMATE_HEIGHT - 8);
1739
+ }
1740
+ const maxList = Math.max(180, Math.min(440, h - top - chrome));
1741
+ setLayout({ top, right, maxListHeight: maxList });
1546
1742
  };
1547
- return (_jsx("div", { style: {
1548
- position: "fixed",
1549
- zIndex: 9999,
1550
- top: layout.top,
1551
- right: layout.right,
1552
- width: PANEL_WIDTH,
1553
- maxWidth: `calc(100vw - 16px)`,
1554
- pointerEvents: "none",
1555
- }, children: _jsx("div", { style: { pointerEvents: "auto" }, children: _jsx(ShadowContainer, { children: _jsxs("div", { ref: panelRef, id: "beeper-inbox-panel", role: "dialog", "aria-modal": "false", "aria-labelledby": "beeper-inbox-title", tabIndex: -1, className: "bw-root", style: {
1556
- width: "100%",
1557
- boxSizing: "border-box",
1558
- background: dark ? "#121418" : light.bg,
1559
- color: dark ? "#f9fafb" : light.fg,
1743
+ compute();
1744
+ const ro = new ResizeObserver(compute);
1745
+ if (triggerRef.current) {
1746
+ ro.observe(triggerRef.current);
1747
+ }
1748
+ window.addEventListener("resize", compute);
1749
+ window.addEventListener("scroll", compute, true);
1750
+ return () => {
1751
+ ro.disconnect();
1752
+ window.removeEventListener("resize", compute);
1753
+ window.removeEventListener("scroll", compute, true);
1754
+ };
1755
+ }, [open, placement, triggerRef]);
1756
+ if (!open) {
1757
+ return null;
1758
+ }
1759
+ const mode = resolveTheme(effectiveConfig.modeDefault);
1760
+ const dark = mode === "dark";
1761
+ const light = {
1762
+ bg: "#fffaf5",
1763
+ fg: "#2b221d",
1764
+ muted: "#7d685d",
1765
+ border: "#eadbcc",
1766
+ surface: "#fffdf9",
1767
+ itemBg: "#fffcf8",
1768
+ shadow: "0 24px 54px rgba(38, 24, 12, 0.14)"
1769
+ };
1770
+ const toolbarBtn = dark ? {
1771
+ border: "1px solid #3a4250",
1772
+ background: "rgba(255,255,255,0.02)",
1773
+ color: "#e5e7eb",
1774
+ borderRadius: effectiveConfig.radius - 4,
1775
+ padding: "6px 10px",
1776
+ fontSize: "0.85em",
1777
+ cursor: "pointer"
1778
+ } : {
1779
+ border: `1px solid ${light.border}`,
1780
+ background: light.surface,
1781
+ color: light.fg,
1782
+ borderRadius: effectiveConfig.radius - 4,
1783
+ padding: "6px 10px",
1784
+ fontSize: "0.85em",
1785
+ cursor: "pointer"
1786
+ };
1787
+ const linkBtn = {
1788
+ border: "none",
1789
+ background: "transparent",
1790
+ color: effectiveConfig.accentColor,
1791
+ cursor: "pointer",
1792
+ fontSize: "0.88em",
1793
+ fontWeight: 600,
1794
+ padding: "4px 0"
1795
+ };
1796
+ return /* @__PURE__ */ jsx(
1797
+ "div",
1798
+ {
1799
+ style: {
1800
+ position: "fixed",
1801
+ zIndex: 9999,
1802
+ top: layout.top,
1803
+ right: layout.right,
1804
+ width: PANEL_WIDTH,
1805
+ maxWidth: `calc(100vw - 16px)`,
1806
+ pointerEvents: "none"
1807
+ },
1808
+ children: /* @__PURE__ */ jsx("div", { style: { pointerEvents: "auto" }, children: /* @__PURE__ */ jsx(ShadowContainer, { children: /* @__PURE__ */ jsxs(
1809
+ "div",
1810
+ {
1811
+ ref: panelRef,
1812
+ id: "beeper-inbox-panel",
1813
+ role: "dialog",
1814
+ "aria-modal": "false",
1815
+ "aria-labelledby": "beeper-inbox-title",
1816
+ tabIndex: -1,
1817
+ className: "bw-root",
1818
+ style: {
1819
+ width: "100%",
1820
+ boxSizing: "border-box",
1821
+ background: dark ? "#121418" : light.bg,
1822
+ color: dark ? "#f9fafb" : light.fg,
1823
+ border: dark ? "1px solid #2b313b" : `1px solid ${light.border}`,
1824
+ borderRadius: effectiveConfig.radius,
1825
+ boxShadow: dark ? "0 16px 30px rgba(0,0,0,.45)" : light.shadow,
1826
+ padding: effectiveConfig.compact ? 10 : 14,
1827
+ fontSize: `${14 * effectiveConfig.fontScale}px`
1828
+ },
1829
+ children: [
1830
+ /* @__PURE__ */ jsxs(
1831
+ "div",
1832
+ {
1833
+ style: {
1834
+ display: "flex",
1835
+ justifyContent: "space-between",
1836
+ alignItems: "center",
1837
+ gap: 8
1838
+ },
1839
+ children: [
1840
+ /* @__PURE__ */ jsx("strong", { id: "beeper-inbox-title", style: { fontSize: "1.04em", letterSpacing: "-0.03em", fontWeight: 700 }, children: effectiveConfig.headerTitle }),
1841
+ /* @__PURE__ */ jsxs("div", { style: { display: "flex", gap: 6, flexShrink: 0, alignItems: "center" }, children: [
1842
+ refreshing ? /* @__PURE__ */ jsx("small", { role: "status", style: { opacity: 0.65, whiteSpace: "nowrap" }, children: "Refreshing..." }) : null,
1843
+ /* @__PURE__ */ jsx("button", { type: "button", style: toolbarBtn, onClick: () => refresh({ silent: true }), children: "Refresh" }),
1844
+ /* @__PURE__ */ jsx("button", { type: "button", style: toolbarBtn, onClick: () => setOpen(false), children: "Close" })
1845
+ ] })
1846
+ ]
1847
+ }
1848
+ ),
1849
+ effectiveConfig.showTopicTabs && tabs.length > 0 ? /* @__PURE__ */ jsx(
1850
+ "div",
1851
+ {
1852
+ role: "tablist",
1853
+ "aria-label": "Notification categories",
1854
+ style: {
1855
+ display: "flex",
1856
+ gap: 4,
1857
+ marginTop: 10,
1858
+ overflowX: "auto",
1859
+ borderBottom: dark ? "1px solid #2b313b" : `1px solid ${light.border}`
1860
+ },
1861
+ children: tabs.map((tab) => {
1862
+ const selected = tab.key === activeTab;
1863
+ const count = tabUnreadCount(tab);
1864
+ return /* @__PURE__ */ jsxs(
1865
+ "button",
1866
+ {
1867
+ type: "button",
1868
+ role: "tab",
1869
+ "aria-selected": selected,
1870
+ onClick: () => setActiveTab(tab.key),
1871
+ style: {
1872
+ display: "flex",
1873
+ alignItems: "center",
1874
+ gap: 6,
1875
+ border: "none",
1876
+ borderBottom: `2px solid ${selected ? effectiveConfig.accentColor : "transparent"}`,
1877
+ background: "transparent",
1878
+ color: selected ? dark ? "#f9fafb" : light.fg : dark ? "#c7b6a7" : light.muted,
1879
+ cursor: "pointer",
1880
+ fontSize: "0.9em",
1881
+ fontWeight: selected ? 700 : 500,
1882
+ padding: "6px 8px",
1883
+ whiteSpace: "nowrap"
1884
+ },
1885
+ children: [
1886
+ tab.label,
1887
+ count > 0 ? /* @__PURE__ */ jsx(
1888
+ "span",
1889
+ {
1890
+ "aria-label": `${count} unread`,
1891
+ style: {
1892
+ background: effectiveConfig.accentColor,
1893
+ color: "#fff",
1894
+ borderRadius: 999,
1895
+ fontSize: "0.78em",
1896
+ fontWeight: 700,
1897
+ lineHeight: 1,
1898
+ padding: "3px 6px"
1899
+ },
1900
+ children: count > 99 ? "99+" : count
1901
+ }
1902
+ ) : null
1903
+ ]
1904
+ },
1905
+ tab.key
1906
+ );
1907
+ })
1908
+ }
1909
+ ) : null,
1910
+ connectionState !== "live" ? /* @__PURE__ */ jsx("div", { role: connectionState === "error" ? "alert" : "status", children: connectionState === "error" ? /* @__PURE__ */ jsxs(Fragment, { children: [
1911
+ errorMessage ? /* @__PURE__ */ jsx("small", { children: errorMessage }) : null,
1912
+ /* @__PURE__ */ jsx("button", { type: "button", style: toolbarBtn, onClick: () => reconnect(), children: "Reconnect" })
1913
+ ] }) : null }) : null,
1914
+ /* @__PURE__ */ jsxs(
1915
+ "div",
1916
+ {
1917
+ style: {
1918
+ marginTop: 12,
1919
+ display: "grid",
1920
+ gap: 8,
1921
+ maxHeight: layout.maxListHeight,
1922
+ minHeight: items.length === 0 && !loading ? 140 : void 0,
1923
+ overflowY: "auto",
1924
+ paddingRight: 2
1925
+ },
1926
+ children: [
1927
+ loading && items.length === 0 ? /* @__PURE__ */ jsx(
1928
+ "div",
1929
+ {
1930
+ role: "status",
1931
+ style: {
1932
+ alignSelf: "center",
1933
+ padding: "18px 0",
1934
+ color: dark ? "#d0d5dd" : light.muted,
1935
+ fontSize: "0.92em"
1936
+ },
1937
+ children: "Loading notifications..."
1938
+ }
1939
+ ) : items.length === 0 ? /* @__PURE__ */ jsx(
1940
+ "div",
1941
+ {
1942
+ style: {
1943
+ alignSelf: "center",
1944
+ textAlign: "center",
1945
+ padding: "30px 18px",
1946
+ lineHeight: 1.5,
1947
+ color: dark ? "#c7b6a7" : light.muted,
1948
+ border: dark ? "1px dashed #3a4250" : `1px dashed ${light.border}`,
1949
+ borderRadius: effectiveConfig.radius - 2,
1950
+ background: dark ? "#181411" : "#fffdf9"
1951
+ },
1952
+ children: "No notifications yet. New activity will appear here as soon as this subscriber receives it."
1953
+ }
1954
+ ) : items.map((item) => /* @__PURE__ */ jsxs(
1955
+ "div",
1956
+ {
1957
+ style: {
1560
1958
  border: dark ? "1px solid #2b313b" : `1px solid ${light.border}`,
1561
- borderRadius: effectiveConfig.radius,
1562
- boxShadow: dark ? "0 16px 30px rgba(0,0,0,.45)" : light.shadow,
1563
- padding: effectiveConfig.compact ? 10 : 14,
1564
- fontSize: `${14 * effectiveConfig.fontScale}px`,
1565
- }, children: [_jsxs("div", { style: {
1566
- display: "flex",
1567
- justifyContent: "space-between",
1568
- alignItems: "center",
1569
- gap: 8,
1570
- }, children: [_jsx("strong", { id: "beeper-inbox-title", style: { fontSize: "1.04em", letterSpacing: "-0.03em", fontWeight: 700 }, children: effectiveConfig.headerTitle }), _jsxs("div", { style: { display: "flex", gap: 6, flexShrink: 0, alignItems: "center" }, children: [refreshing ? (_jsx("small", { role: "status", style: { opacity: 0.65, whiteSpace: "nowrap" }, children: "Refreshing..." })) : null, _jsx("button", { type: "button", style: toolbarBtn, onClick: () => refresh({ silent: true }), children: "Refresh" }), _jsx("button", { type: "button", style: toolbarBtn, onClick: () => setOpen(false), children: "Close" })] })] }), effectiveConfig.showTopicTabs && tabs.length > 0 ? (_jsx("div", { role: "tablist", "aria-label": "Notification categories", style: {
1571
- display: "flex",
1572
- gap: 4,
1573
- marginTop: 10,
1574
- overflowX: "auto",
1575
- borderBottom: dark ? "1px solid #2b313b" : `1px solid ${light.border}`,
1576
- }, children: tabs.map((tab) => {
1577
- const selected = tab.key === activeTab;
1578
- const count = tabUnreadCount(tab);
1579
- return (_jsxs("button", { type: "button", role: "tab", "aria-selected": selected, onClick: () => setActiveTab(tab.key), style: {
1580
- display: "flex",
1581
- alignItems: "center",
1582
- gap: 6,
1583
- border: "none",
1584
- borderBottom: `2px solid ${selected ? effectiveConfig.accentColor : "transparent"}`,
1585
- background: "transparent",
1586
- color: selected ? (dark ? "#f9fafb" : light.fg) : dark ? "#c7b6a7" : light.muted,
1587
- cursor: "pointer",
1588
- fontSize: "0.9em",
1589
- fontWeight: selected ? 700 : 500,
1590
- padding: "6px 8px",
1591
- whiteSpace: "nowrap",
1592
- }, children: [tab.label, count > 0 ? (_jsx("span", { "aria-label": `${count} unread`, style: {
1593
- background: effectiveConfig.accentColor,
1594
- color: "#fff",
1595
- borderRadius: 999,
1596
- fontSize: "0.78em",
1597
- fontWeight: 700,
1598
- lineHeight: 1,
1599
- padding: "3px 6px",
1600
- }, children: count > 99 ? "99+" : count })) : null] }, tab.key));
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: {
1602
- marginTop: 12,
1603
- display: "grid",
1604
- gap: 8,
1605
- maxHeight: layout.maxListHeight,
1606
- minHeight: items.length === 0 && !loading ? 140 : undefined,
1607
- overflowY: "auto",
1608
- paddingRight: 2,
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: {
1676
- display: "flex",
1677
- justifyContent: "flex-end",
1678
- marginTop: 12,
1679
- paddingTop: 10,
1680
- borderTop: dark ? "1px solid #2b313b" : `1px solid ${light.border}`,
1681
- }, children: _jsx("button", { type: "button", style: linkBtn, onClick: () => markAllRead(), children: "Mark all as read" }) })) : null] }) }) }) }));
1959
+ borderRadius: effectiveConfig.radius - 2,
1960
+ padding: 14,
1961
+ background: item.readAt ? dark ? "#181411" : "#fffaf4" : dark ? "#1b1613" : light.itemBg,
1962
+ boxShadow: item.readAt ? "none" : dark ? `inset 0 0 0 1px ${withAlpha(effectiveConfig.accentColor, 0.18)}` : `inset 0 0 0 1px ${withAlpha(effectiveConfig.accentColor, 0.14)}`,
1963
+ opacity: item.resolvedAt ? 0.65 : 1
1964
+ },
1965
+ children: [
1966
+ /* @__PURE__ */ jsxs(
1967
+ "div",
1968
+ {
1969
+ style: {
1970
+ display: "flex",
1971
+ alignItems: "center",
1972
+ gap: 10,
1973
+ fontWeight: 700,
1974
+ marginBottom: 6,
1975
+ letterSpacing: "-0.02em"
1976
+ },
1977
+ children: [
1978
+ item.avatarUrl ? /* @__PURE__ */ jsx(
1979
+ "img",
1980
+ {
1981
+ src: item.avatarUrl,
1982
+ alt: "",
1983
+ width: 32,
1984
+ height: 32,
1985
+ loading: "lazy",
1986
+ style: { borderRadius: "50%", objectFit: "cover", flexShrink: 0 }
1987
+ }
1988
+ ) : null,
1989
+ /* @__PURE__ */ jsx("span", { children: item.title ?? "Notification" })
1990
+ ]
1991
+ }
1992
+ ),
1993
+ /* @__PURE__ */ jsx(
1994
+ "div",
1995
+ {
1996
+ style: {
1997
+ opacity: 0.92,
1998
+ marginBottom: 10,
1999
+ lineHeight: 1.5,
2000
+ color: dark ? "#efe3d8" : "#4e3c34"
2001
+ },
2002
+ children: item.body
2003
+ }
2004
+ ),
2005
+ item.imageUrl ? /* @__PURE__ */ jsx(
2006
+ "img",
2007
+ {
2008
+ src: item.imageUrl,
2009
+ alt: "",
2010
+ loading: "lazy",
2011
+ style: {
2012
+ display: "block",
2013
+ width: "100%",
2014
+ aspectRatio: "16 / 9",
2015
+ objectFit: "cover",
2016
+ borderRadius: Math.max(effectiveConfig.radius - 6, 4),
2017
+ marginBottom: 10
2018
+ }
2019
+ }
2020
+ ) : null,
2021
+ /* @__PURE__ */ jsxs(
2022
+ "div",
2023
+ {
2024
+ style: {
2025
+ display: "flex",
2026
+ justifyContent: "space-between",
2027
+ alignItems: "center",
2028
+ gap: 12
2029
+ },
2030
+ children: [
2031
+ /* @__PURE__ */ jsxs(
2032
+ "div",
2033
+ {
2034
+ style: {
2035
+ display: "flex",
2036
+ alignItems: "center",
2037
+ gap: 10,
2038
+ flexWrap: "wrap"
2039
+ },
2040
+ children: [
2041
+ /* @__PURE__ */ jsx("small", { style: { opacity: 0.65 }, children: timeAgo(item.createdAt) }),
2042
+ item.actionUrl ? /* @__PURE__ */ jsx(
2043
+ "button",
2044
+ {
2045
+ type: "button",
2046
+ onClick: () => {
2047
+ void handleActionClick(item);
2048
+ },
2049
+ style: linkBtn,
2050
+ children: item.actionLabel ?? "Open"
2051
+ }
2052
+ ) : null
2053
+ ]
2054
+ }
2055
+ ),
2056
+ /* @__PURE__ */ jsxs("div", { style: { display: "flex", gap: 12, alignItems: "center" }, children: [
2057
+ !item.readAt ? /* @__PURE__ */ jsx("button", { type: "button", style: linkBtn, onClick: () => markRead(item._id), children: "Mark read" }) : /* @__PURE__ */ jsx("small", { style: { opacity: 0.65 }, children: "Read" }),
2058
+ effectiveConfig.showDismiss ? /* @__PURE__ */ jsx(
2059
+ "button",
2060
+ {
2061
+ type: "button",
2062
+ style: { ...linkBtn, color: dark ? "#c7b6a7" : light.muted },
2063
+ onClick: () => {
2064
+ void archive(item._id).catch(() => void 0);
2065
+ },
2066
+ children: "Dismiss"
2067
+ }
2068
+ ) : null
2069
+ ] })
2070
+ ]
2071
+ }
2072
+ )
2073
+ ]
2074
+ },
2075
+ item._id
2076
+ )),
2077
+ items.length > 0 && hasMore ? /* @__PURE__ */ jsx(
2078
+ "button",
2079
+ {
2080
+ type: "button",
2081
+ style: { ...toolbarBtn, justifySelf: "center" },
2082
+ disabled: loadingMore,
2083
+ onClick: () => {
2084
+ void loadMore().catch(() => void 0);
2085
+ },
2086
+ children: loadingMore ? "Loading..." : "Show older"
2087
+ }
2088
+ ) : null
2089
+ ]
2090
+ }
2091
+ ),
2092
+ effectiveConfig.showMarkAll && items.length > 0 ? /* @__PURE__ */ jsx(
2093
+ "div",
2094
+ {
2095
+ style: {
2096
+ display: "flex",
2097
+ justifyContent: "flex-end",
2098
+ marginTop: 12,
2099
+ paddingTop: 10,
2100
+ borderTop: dark ? "1px solid #2b313b" : `1px solid ${light.border}`
2101
+ },
2102
+ children: /* @__PURE__ */ jsx("button", { type: "button", style: linkBtn, onClick: () => markAllRead(), children: "Mark all as read" })
2103
+ }
2104
+ ) : null
2105
+ ]
2106
+ }
2107
+ ) }) })
2108
+ }
2109
+ );
1682
2110
  }
1683
- export const __internal = {
1684
- DEFAULT_BEEPER_WIDGET_API_BASE_URL,
1685
- tabKinds,
1686
- countTabUnread,
1687
- buildKindsQuery,
1688
- parseTokenExpiryMs,
1689
- isSessionExpiringSoon,
2111
+ var __internal = {
2112
+ DEFAULT_BEEPER_WIDGET_API_BASE_URL,
2113
+ tabKinds,
2114
+ countTabUnread,
2115
+ buildKindsQuery,
2116
+ parseTokenExpiryMs,
2117
+ isSessionExpiringSoon,
2118
+ pickRealtimeSource,
2119
+ createWidgetSocketClient
1690
2120
  };
2121
+
2122
+ export { BeeperInboxBell, BeeperInboxPanel, BeeperInboxProvider, __internal, useBeeperInbox, useBeeperInboxUnreadCount };
2123
+ //# sourceMappingURL=index.js.map
1691
2124
  //# sourceMappingURL=index.js.map