beeper-inbox-react 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +170 -0
- package/dist/index.d.ts +186 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1090 -0
- package/dist/index.js.map +1 -0
- package/dist/index.test.d.ts +2 -0
- package/dist/index.test.d.ts.map +1 -0
- package/dist/index.test.js +37 -0
- package/dist/index.test.js.map +1 -0
- package/package.json +44 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1090 @@
|
|
|
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
|
+
};
|
|
15
|
+
const Ctx = createContext(null);
|
|
16
|
+
function parseTokenExpiryMs(token) {
|
|
17
|
+
const segments = token.split(".");
|
|
18
|
+
const payload = segments.length >= 3 ? segments[1] : segments[0];
|
|
19
|
+
if (!payload) {
|
|
20
|
+
return null;
|
|
21
|
+
}
|
|
22
|
+
try {
|
|
23
|
+
const normalized = payload.replace(/-/g, "+").replace(/_/g, "/");
|
|
24
|
+
const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, "=");
|
|
25
|
+
const decoded = typeof globalThis.Buffer !== "undefined"
|
|
26
|
+
? globalThis.Buffer.from(padded, "base64").toString("utf8")
|
|
27
|
+
: typeof globalThis.atob === "function"
|
|
28
|
+
? globalThis.atob(padded)
|
|
29
|
+
: null;
|
|
30
|
+
if (!decoded) {
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
const json = JSON.parse(decoded);
|
|
34
|
+
if (typeof json.exp !== "number" || !Number.isFinite(json.exp)) {
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
return json.exp;
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
function isSessionExpiringSoon(expiresAt, now = Date.now()) {
|
|
44
|
+
return Boolean(expiresAt && expiresAt - now <= 30_000);
|
|
45
|
+
}
|
|
46
|
+
function resolveTheme(theme) {
|
|
47
|
+
if (theme === "system") {
|
|
48
|
+
if (typeof window === "undefined") {
|
|
49
|
+
return "light";
|
|
50
|
+
}
|
|
51
|
+
return window.matchMedia("(prefers-color-scheme: dark)").matches
|
|
52
|
+
? "dark"
|
|
53
|
+
: "light";
|
|
54
|
+
}
|
|
55
|
+
return theme;
|
|
56
|
+
}
|
|
57
|
+
function timeAgo(ts) {
|
|
58
|
+
const diffSec = Math.max(1, Math.floor((Date.now() - ts) / 1000));
|
|
59
|
+
if (diffSec < 60)
|
|
60
|
+
return `${diffSec}s ago`;
|
|
61
|
+
if (diffSec < 3600)
|
|
62
|
+
return `${Math.floor(diffSec / 60)}m ago`;
|
|
63
|
+
if (diffSec < 86400)
|
|
64
|
+
return `${Math.floor(diffSec / 3600)}h ago`;
|
|
65
|
+
return `${Math.floor(diffSec / 86400)}d ago`;
|
|
66
|
+
}
|
|
67
|
+
function withAlpha(color, alpha) {
|
|
68
|
+
const normalized = color.trim();
|
|
69
|
+
const clamped = Math.max(0, Math.min(1, alpha));
|
|
70
|
+
const shortHexMatch = /^#([\da-f]{3})$/i.exec(normalized);
|
|
71
|
+
const shortHex = shortHexMatch?.[1];
|
|
72
|
+
if (shortHex) {
|
|
73
|
+
const channels = shortHex
|
|
74
|
+
.split("")
|
|
75
|
+
.map((channel) => parseInt(channel + channel, 16));
|
|
76
|
+
const [r, g, b] = channels;
|
|
77
|
+
return `rgba(${r}, ${g}, ${b}, ${clamped})`;
|
|
78
|
+
}
|
|
79
|
+
const longHexMatch = /^#([\da-f]{6})$/i.exec(normalized);
|
|
80
|
+
const value = longHexMatch?.[1];
|
|
81
|
+
if (value) {
|
|
82
|
+
const r = parseInt(value.slice(0, 2), 16);
|
|
83
|
+
const g = parseInt(value.slice(2, 4), 16);
|
|
84
|
+
const b = parseInt(value.slice(4, 6), 16);
|
|
85
|
+
return `rgba(${r}, ${g}, ${b}, ${clamped})`;
|
|
86
|
+
}
|
|
87
|
+
return `color-mix(in srgb, ${normalized} ${Math.round(clamped * 100)}%, transparent)`;
|
|
88
|
+
}
|
|
89
|
+
function readStringRecordValue(record, keys) {
|
|
90
|
+
if (!record) {
|
|
91
|
+
return undefined;
|
|
92
|
+
}
|
|
93
|
+
for (const key of keys) {
|
|
94
|
+
const value = record[key];
|
|
95
|
+
if (typeof value === "string" && value.trim()) {
|
|
96
|
+
return value.trim();
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return undefined;
|
|
100
|
+
}
|
|
101
|
+
function normalizeInboxItem(item) {
|
|
102
|
+
const actionLabel = item.actionLabel ??
|
|
103
|
+
readStringRecordValue(item.metadata, [
|
|
104
|
+
"_beeperActionLabel",
|
|
105
|
+
"actionLabel",
|
|
106
|
+
"action_label",
|
|
107
|
+
"ctaLabel",
|
|
108
|
+
"cta_label",
|
|
109
|
+
]);
|
|
110
|
+
const actionUrl = item.actionUrl ??
|
|
111
|
+
readStringRecordValue(item.metadata, [
|
|
112
|
+
"_beeperActionUrl",
|
|
113
|
+
"actionUrl",
|
|
114
|
+
"action_url",
|
|
115
|
+
"ctaUrl",
|
|
116
|
+
"cta_url",
|
|
117
|
+
]);
|
|
118
|
+
return {
|
|
119
|
+
...item,
|
|
120
|
+
actionLabel,
|
|
121
|
+
actionUrl,
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
function resolveActionNavigationTarget(actionUrl, configured) {
|
|
125
|
+
if (configured !== "auto") {
|
|
126
|
+
return configured;
|
|
127
|
+
}
|
|
128
|
+
if (typeof window === "undefined") {
|
|
129
|
+
return "_self";
|
|
130
|
+
}
|
|
131
|
+
try {
|
|
132
|
+
const resolved = new URL(actionUrl, window.location.origin);
|
|
133
|
+
return resolved.origin === window.location.origin ? "_self" : "_blank";
|
|
134
|
+
}
|
|
135
|
+
catch {
|
|
136
|
+
return "_self";
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
export function BeeperInboxProvider({ baseUrl, projectId, publishableKey, sessionToken, getSessionToken, sessionEndpoint = "/api/beeper/widget-session", sessionRequestHeaders, subscriber, theme = "system", customization, push, actionLinkTarget = "auto", onActionClick, pollIntervalMs = 15000, onEvent, children, }) {
|
|
140
|
+
const [open, setOpen] = useState(false);
|
|
141
|
+
const [items, setItems] = useState([]);
|
|
142
|
+
const [unreadCount, setUnreadCount] = useState(0);
|
|
143
|
+
const [loading, setLoading] = useState(false);
|
|
144
|
+
const [refreshing, setRefreshing] = useState(false);
|
|
145
|
+
const [connectionState, setConnectionState] = useState("connecting");
|
|
146
|
+
const [errorMessage, setErrorMessage] = useState(null);
|
|
147
|
+
const [serverConfig, setServerConfig] = useState(DEFAULT_CONFIG);
|
|
148
|
+
const [realtimeConvexUrl, setRealtimeConvexUrl] = useState(null);
|
|
149
|
+
const [runtimeSessionToken, setRuntimeSessionToken] = useState(sessionToken ?? "");
|
|
150
|
+
const [runtimeSessionExpiresAt, setRuntimeSessionExpiresAt] = useState(parseTokenExpiryMs(sessionToken ?? ""));
|
|
151
|
+
const runtimeSessionTokenRef = useRef(sessionToken ?? "");
|
|
152
|
+
const runtimeSessionExpiresAtRef = useRef(parseTokenExpiryMs(sessionToken ?? ""));
|
|
153
|
+
const convexClientRef = useRef(null);
|
|
154
|
+
const sessionRefreshRef = useRef(null);
|
|
155
|
+
const eventRef = useRef(onEvent);
|
|
156
|
+
const triggerRef = useRef(null);
|
|
157
|
+
const hasLoadedOnceRef = useRef(false);
|
|
158
|
+
useEffect(() => {
|
|
159
|
+
eventRef.current = onEvent;
|
|
160
|
+
}, [onEvent]);
|
|
161
|
+
const emitEvent = useCallback((event) => {
|
|
162
|
+
eventRef.current?.(event);
|
|
163
|
+
}, []);
|
|
164
|
+
useEffect(() => {
|
|
165
|
+
setRuntimeSessionToken(sessionToken ?? "");
|
|
166
|
+
setRuntimeSessionExpiresAt(parseTokenExpiryMs(sessionToken ?? ""));
|
|
167
|
+
runtimeSessionTokenRef.current = sessionToken ?? "";
|
|
168
|
+
runtimeSessionExpiresAtRef.current = parseTokenExpiryMs(sessionToken ?? "");
|
|
169
|
+
}, [sessionToken]);
|
|
170
|
+
const resolveSessionToken = useCallback(async () => {
|
|
171
|
+
if (getSessionToken) {
|
|
172
|
+
return getSessionToken(subscriber);
|
|
173
|
+
}
|
|
174
|
+
const sessionUrl = /^https?:\/\//i.test(sessionEndpoint)
|
|
175
|
+
? sessionEndpoint
|
|
176
|
+
: typeof window !== "undefined"
|
|
177
|
+
? new URL(sessionEndpoint, window.location.origin).toString()
|
|
178
|
+
: sessionEndpoint;
|
|
179
|
+
const response = await fetch(sessionUrl, {
|
|
180
|
+
method: "POST",
|
|
181
|
+
headers: {
|
|
182
|
+
"content-type": "application/json",
|
|
183
|
+
...(sessionRequestHeaders ?? {}),
|
|
184
|
+
},
|
|
185
|
+
body: JSON.stringify({
|
|
186
|
+
projectId,
|
|
187
|
+
subscriberId: subscriber.subscriberId,
|
|
188
|
+
profile: {
|
|
189
|
+
displayName: subscriber.displayName,
|
|
190
|
+
email: subscriber.email,
|
|
191
|
+
avatarUrl: subscriber.avatarUrl,
|
|
192
|
+
metadata: subscriber.metadata,
|
|
193
|
+
},
|
|
194
|
+
}),
|
|
195
|
+
});
|
|
196
|
+
const payload = (await response.json());
|
|
197
|
+
const token = payload.widgetSessionToken ?? payload.data?.widgetSessionToken;
|
|
198
|
+
if (!response.ok || !token) {
|
|
199
|
+
throw new Error(payload?.error ?? "Failed to mint Beeper widget session token");
|
|
200
|
+
}
|
|
201
|
+
return token;
|
|
202
|
+
}, [getSessionToken, projectId, sessionEndpoint, sessionRequestHeaders, subscriber]);
|
|
203
|
+
const refreshSession = useCallback(async () => {
|
|
204
|
+
if (sessionRefreshRef.current) {
|
|
205
|
+
return sessionRefreshRef.current;
|
|
206
|
+
}
|
|
207
|
+
emitEvent({
|
|
208
|
+
type: "session.refresh.start",
|
|
209
|
+
projectId,
|
|
210
|
+
subscriberId: subscriber.subscriberId,
|
|
211
|
+
});
|
|
212
|
+
const request = resolveSessionToken()
|
|
213
|
+
.then((next) => {
|
|
214
|
+
setRuntimeSessionToken(next);
|
|
215
|
+
runtimeSessionTokenRef.current = next;
|
|
216
|
+
const nextExpiresAt = parseTokenExpiryMs(next);
|
|
217
|
+
setRuntimeSessionExpiresAt(nextExpiresAt);
|
|
218
|
+
runtimeSessionExpiresAtRef.current = nextExpiresAt;
|
|
219
|
+
emitEvent({
|
|
220
|
+
type: "session.refresh.success",
|
|
221
|
+
projectId,
|
|
222
|
+
subscriberId: subscriber.subscriberId,
|
|
223
|
+
});
|
|
224
|
+
return next;
|
|
225
|
+
})
|
|
226
|
+
.catch((error) => {
|
|
227
|
+
const message = error instanceof Error ? error.message : "Session refresh failed";
|
|
228
|
+
emitEvent({
|
|
229
|
+
type: "session.refresh.error",
|
|
230
|
+
projectId,
|
|
231
|
+
subscriberId: subscriber.subscriberId,
|
|
232
|
+
message,
|
|
233
|
+
});
|
|
234
|
+
throw error;
|
|
235
|
+
})
|
|
236
|
+
.finally(() => {
|
|
237
|
+
sessionRefreshRef.current = null;
|
|
238
|
+
});
|
|
239
|
+
sessionRefreshRef.current = request;
|
|
240
|
+
return request;
|
|
241
|
+
}, [emitEvent, projectId, resolveSessionToken, subscriber.subscriberId]);
|
|
242
|
+
const ensureSession = useCallback(async () => {
|
|
243
|
+
const now = Date.now();
|
|
244
|
+
const currentToken = runtimeSessionTokenRef.current;
|
|
245
|
+
const currentExpiresAt = runtimeSessionExpiresAtRef.current;
|
|
246
|
+
if (currentToken) {
|
|
247
|
+
const canRefresh = Boolean(getSessionToken) || Boolean(sessionEndpoint);
|
|
248
|
+
if (isSessionExpiringSoon(currentExpiresAt, now) && canRefresh) {
|
|
249
|
+
return refreshSession();
|
|
250
|
+
}
|
|
251
|
+
return currentToken;
|
|
252
|
+
}
|
|
253
|
+
return refreshSession();
|
|
254
|
+
}, [
|
|
255
|
+
getSessionToken,
|
|
256
|
+
refreshSession,
|
|
257
|
+
sessionEndpoint,
|
|
258
|
+
]);
|
|
259
|
+
const fetchJson = useCallback(async (method, path, body, allowSessionRefresh = true, sessionTokenOverride) => {
|
|
260
|
+
let sessionHeaderToken = sessionTokenOverride ?? runtimeSessionTokenRef.current;
|
|
261
|
+
if (!sessionHeaderToken && allowSessionRefresh) {
|
|
262
|
+
sessionHeaderToken = await ensureSession();
|
|
263
|
+
}
|
|
264
|
+
const url = `${baseUrl.replace(/\/$/, "")}/api/v1/projects/${projectId}${path}`;
|
|
265
|
+
const response = await fetch(url, {
|
|
266
|
+
method,
|
|
267
|
+
headers: {
|
|
268
|
+
"content-type": "application/json",
|
|
269
|
+
"x-beeper-publishable-key": publishableKey,
|
|
270
|
+
...(sessionHeaderToken
|
|
271
|
+
? {
|
|
272
|
+
"x-beeper-session-token": sessionHeaderToken,
|
|
273
|
+
}
|
|
274
|
+
: {}),
|
|
275
|
+
},
|
|
276
|
+
body: method === "POST" ? JSON.stringify(body ?? {}) : undefined,
|
|
277
|
+
});
|
|
278
|
+
const rawText = await response.text();
|
|
279
|
+
let payload = {};
|
|
280
|
+
try {
|
|
281
|
+
payload = rawText ? JSON.parse(rawText) : {};
|
|
282
|
+
}
|
|
283
|
+
catch {
|
|
284
|
+
emitEvent({
|
|
285
|
+
type: "api.error",
|
|
286
|
+
projectId,
|
|
287
|
+
subscriberId: subscriber.subscriberId,
|
|
288
|
+
path,
|
|
289
|
+
status: response.status,
|
|
290
|
+
message: `Non-JSON response from Beeper API (check baseUrl is your Convex site URL, e.g. …convex.site). ${rawText.slice(0, 120)}`,
|
|
291
|
+
});
|
|
292
|
+
throw new Error(`Beeper API returned non-JSON (${response.status}). Is baseUrl the Convex HTTP URL (…convex.site)?`);
|
|
293
|
+
}
|
|
294
|
+
if (!response.ok) {
|
|
295
|
+
emitEvent({
|
|
296
|
+
type: "api.error",
|
|
297
|
+
projectId,
|
|
298
|
+
subscriberId: subscriber.subscriberId,
|
|
299
|
+
path,
|
|
300
|
+
status: response.status,
|
|
301
|
+
message: payload.error ?? "Beeper widget request failed",
|
|
302
|
+
});
|
|
303
|
+
if (allowSessionRefresh &&
|
|
304
|
+
response.status === 401 &&
|
|
305
|
+
(getSessionToken || sessionEndpoint)) {
|
|
306
|
+
const nextToken = await refreshSession();
|
|
307
|
+
return fetchJson(method, path, body, false, nextToken);
|
|
308
|
+
}
|
|
309
|
+
throw new Error(payload.error ?? "Beeper widget request failed");
|
|
310
|
+
}
|
|
311
|
+
return payload.data;
|
|
312
|
+
}, [
|
|
313
|
+
baseUrl,
|
|
314
|
+
emitEvent,
|
|
315
|
+
getSessionToken,
|
|
316
|
+
projectId,
|
|
317
|
+
publishableKey,
|
|
318
|
+
refreshSession,
|
|
319
|
+
ensureSession,
|
|
320
|
+
sessionEndpoint,
|
|
321
|
+
subscriber.subscriberId,
|
|
322
|
+
]);
|
|
323
|
+
/** Config is public (publishable key only); stable deps avoid refetch on every session token change. */
|
|
324
|
+
const fetchWidgetConfigDocument = useCallback(async () => {
|
|
325
|
+
const url = `${baseUrl.replace(/\/$/, "")}/api/v1/projects/${projectId}/widget/config`;
|
|
326
|
+
const response = await fetch(url, {
|
|
327
|
+
method: "GET",
|
|
328
|
+
headers: {
|
|
329
|
+
"content-type": "application/json",
|
|
330
|
+
"x-beeper-publishable-key": publishableKey,
|
|
331
|
+
},
|
|
332
|
+
});
|
|
333
|
+
const rawText = await response.text();
|
|
334
|
+
let payload = {};
|
|
335
|
+
try {
|
|
336
|
+
payload = rawText ? JSON.parse(rawText) : {};
|
|
337
|
+
}
|
|
338
|
+
catch {
|
|
339
|
+
return undefined;
|
|
340
|
+
}
|
|
341
|
+
if (!response.ok) {
|
|
342
|
+
return undefined;
|
|
343
|
+
}
|
|
344
|
+
return payload.data;
|
|
345
|
+
}, [baseUrl, projectId, publishableKey]);
|
|
346
|
+
const refresh = useCallback(async (options) => {
|
|
347
|
+
const silent = options?.silent ?? false;
|
|
348
|
+
if (silent) {
|
|
349
|
+
setRefreshing(true);
|
|
350
|
+
}
|
|
351
|
+
else {
|
|
352
|
+
setLoading(true);
|
|
353
|
+
}
|
|
354
|
+
try {
|
|
355
|
+
await ensureSession();
|
|
356
|
+
const inbox = await fetchJson("GET", `/widget/inbox?subscriberId=${encodeURIComponent(subscriber.subscriberId)}&limit=50`);
|
|
357
|
+
setItems((inbox.items ?? []).map(normalizeInboxItem));
|
|
358
|
+
setUnreadCount(inbox.unreadCount ?? 0);
|
|
359
|
+
hasLoadedOnceRef.current = true;
|
|
360
|
+
}
|
|
361
|
+
finally {
|
|
362
|
+
if (silent) {
|
|
363
|
+
setRefreshing(false);
|
|
364
|
+
}
|
|
365
|
+
else {
|
|
366
|
+
setLoading(false);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
}, [ensureSession, fetchJson, subscriber.subscriberId]);
|
|
370
|
+
const markRead = useCallback(async (inboxItemId) => {
|
|
371
|
+
const previousItems = items;
|
|
372
|
+
const previousUnreadCount = unreadCount;
|
|
373
|
+
const now = Date.now();
|
|
374
|
+
setItems((current) => current.map((item) => (item._id === inboxItemId ? { ...item, readAt: now } : item)));
|
|
375
|
+
setUnreadCount((current) => Math.max(0, current - (previousItems.some((item) => item._id === inboxItemId && !item.readAt) ? 1 : 0)));
|
|
376
|
+
await ensureSession();
|
|
377
|
+
try {
|
|
378
|
+
await fetchJson("POST", "/widget/read", {
|
|
379
|
+
subscriberId: subscriber.subscriberId,
|
|
380
|
+
inboxItemIds: [inboxItemId],
|
|
381
|
+
});
|
|
382
|
+
await refresh({ silent: true });
|
|
383
|
+
}
|
|
384
|
+
catch (error) {
|
|
385
|
+
setItems(previousItems);
|
|
386
|
+
setUnreadCount(previousUnreadCount);
|
|
387
|
+
throw error;
|
|
388
|
+
}
|
|
389
|
+
}, [ensureSession, fetchJson, items, refresh, subscriber.subscriberId, unreadCount]);
|
|
390
|
+
const markAllRead = useCallback(async () => {
|
|
391
|
+
const previousItems = items;
|
|
392
|
+
const previousUnreadCount = unreadCount;
|
|
393
|
+
const now = Date.now();
|
|
394
|
+
setItems((current) => current.map((item) => (item.readAt ? item : { ...item, readAt: now })));
|
|
395
|
+
setUnreadCount(0);
|
|
396
|
+
await ensureSession();
|
|
397
|
+
try {
|
|
398
|
+
await fetchJson("POST", "/widget/read-all", {
|
|
399
|
+
subscriberId: subscriber.subscriberId,
|
|
400
|
+
});
|
|
401
|
+
await refresh({ silent: true });
|
|
402
|
+
}
|
|
403
|
+
catch (error) {
|
|
404
|
+
setItems(previousItems);
|
|
405
|
+
setUnreadCount(previousUnreadCount);
|
|
406
|
+
throw error;
|
|
407
|
+
}
|
|
408
|
+
}, [ensureSession, fetchJson, items, refresh, subscriber.subscriberId, unreadCount]);
|
|
409
|
+
const registerPushToken = useCallback(async (token, options) => {
|
|
410
|
+
const normalizedToken = token.trim();
|
|
411
|
+
if (!normalizedToken) {
|
|
412
|
+
return;
|
|
413
|
+
}
|
|
414
|
+
await ensureSession();
|
|
415
|
+
await fetchJson("POST", "/widget/push/register", {
|
|
416
|
+
subscriberId: subscriber.subscriberId,
|
|
417
|
+
pushToken: normalizedToken,
|
|
418
|
+
platform: options?.platform ?? "web",
|
|
419
|
+
deviceLabel: options?.deviceLabel,
|
|
420
|
+
metadata: options?.metadata,
|
|
421
|
+
});
|
|
422
|
+
}, [ensureSession, fetchJson, subscriber.subscriberId]);
|
|
423
|
+
const unregisterPushToken = useCallback(async (token) => {
|
|
424
|
+
const normalizedToken = token.trim();
|
|
425
|
+
if (!normalizedToken) {
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
await ensureSession();
|
|
429
|
+
await fetchJson("POST", "/widget/push/unregister", {
|
|
430
|
+
subscriberId: subscriber.subscriberId,
|
|
431
|
+
pushToken: normalizedToken,
|
|
432
|
+
});
|
|
433
|
+
}, [ensureSession, fetchJson, subscriber.subscriberId]);
|
|
434
|
+
const handleActionClick = useCallback(async (item) => {
|
|
435
|
+
const actionUrl = item.actionUrl?.trim();
|
|
436
|
+
if (!actionUrl) {
|
|
437
|
+
return;
|
|
438
|
+
}
|
|
439
|
+
const shouldNavigate = (await onActionClick?.({
|
|
440
|
+
item,
|
|
441
|
+
actionLabel: item.actionLabel,
|
|
442
|
+
actionUrl,
|
|
443
|
+
})) !== false;
|
|
444
|
+
try {
|
|
445
|
+
await ensureSession();
|
|
446
|
+
await fetchJson("POST", "/widget/action-click", {
|
|
447
|
+
subscriberId: subscriber.subscriberId,
|
|
448
|
+
inboxItemId: item._id,
|
|
449
|
+
actionLabel: item.actionLabel,
|
|
450
|
+
actionUrl,
|
|
451
|
+
});
|
|
452
|
+
}
|
|
453
|
+
catch {
|
|
454
|
+
// Best-effort analytics only.
|
|
455
|
+
}
|
|
456
|
+
if (!shouldNavigate || typeof window === "undefined") {
|
|
457
|
+
return;
|
|
458
|
+
}
|
|
459
|
+
const target = resolveActionNavigationTarget(actionUrl, actionLinkTarget);
|
|
460
|
+
if (target === "_blank") {
|
|
461
|
+
window.open(actionUrl, "_blank", "noopener,noreferrer");
|
|
462
|
+
return;
|
|
463
|
+
}
|
|
464
|
+
window.location.assign(actionUrl);
|
|
465
|
+
}, [
|
|
466
|
+
actionLinkTarget,
|
|
467
|
+
ensureSession,
|
|
468
|
+
fetchJson,
|
|
469
|
+
onActionClick,
|
|
470
|
+
subscriber.subscriberId,
|
|
471
|
+
]);
|
|
472
|
+
const reconnect = useCallback(async () => {
|
|
473
|
+
emitEvent({
|
|
474
|
+
type: "realtime.reconnect.manual",
|
|
475
|
+
projectId,
|
|
476
|
+
subscriberId: subscriber.subscriberId,
|
|
477
|
+
});
|
|
478
|
+
setConnectionState("connecting");
|
|
479
|
+
setErrorMessage(null);
|
|
480
|
+
if (getSessionToken || sessionEndpoint) {
|
|
481
|
+
await refreshSession();
|
|
482
|
+
}
|
|
483
|
+
else {
|
|
484
|
+
await ensureSession();
|
|
485
|
+
}
|
|
486
|
+
await refresh();
|
|
487
|
+
}, [
|
|
488
|
+
emitEvent,
|
|
489
|
+
ensureSession,
|
|
490
|
+
getSessionToken,
|
|
491
|
+
projectId,
|
|
492
|
+
refresh,
|
|
493
|
+
refreshSession,
|
|
494
|
+
subscriber.subscriberId,
|
|
495
|
+
]);
|
|
496
|
+
useEffect(() => {
|
|
497
|
+
let cancelled = false;
|
|
498
|
+
async function loadConfig() {
|
|
499
|
+
try {
|
|
500
|
+
const config = await fetchWidgetConfigDocument();
|
|
501
|
+
if (!cancelled && config) {
|
|
502
|
+
setRealtimeConvexUrl(config.convexUrl ?? null);
|
|
503
|
+
setServerConfig({ ...DEFAULT_CONFIG, ...config });
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
catch {
|
|
507
|
+
if (!cancelled) {
|
|
508
|
+
setRealtimeConvexUrl(null);
|
|
509
|
+
setServerConfig(DEFAULT_CONFIG);
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
void loadConfig();
|
|
514
|
+
return () => {
|
|
515
|
+
cancelled = true;
|
|
516
|
+
};
|
|
517
|
+
}, [fetchWidgetConfigDocument]);
|
|
518
|
+
useEffect(() => {
|
|
519
|
+
if (!runtimeSessionToken || !runtimeSessionExpiresAt || !getSessionToken) {
|
|
520
|
+
return;
|
|
521
|
+
}
|
|
522
|
+
const refreshInMs = Math.max(runtimeSessionExpiresAt - Date.now() - 60_000, 1_000);
|
|
523
|
+
const timer = setTimeout(() => {
|
|
524
|
+
refreshSession().catch(() => undefined);
|
|
525
|
+
}, refreshInMs);
|
|
526
|
+
return () => clearTimeout(timer);
|
|
527
|
+
}, [getSessionToken, refreshSession, runtimeSessionExpiresAt, runtimeSessionToken]);
|
|
528
|
+
useEffect(() => {
|
|
529
|
+
if (!push?.token || push.autoRegister === false) {
|
|
530
|
+
return;
|
|
531
|
+
}
|
|
532
|
+
registerPushToken(push.token, {
|
|
533
|
+
platform: push.platform,
|
|
534
|
+
deviceLabel: push.deviceLabel,
|
|
535
|
+
metadata: push.metadata,
|
|
536
|
+
}).catch(() => undefined);
|
|
537
|
+
if (!push.autoUnregister) {
|
|
538
|
+
return;
|
|
539
|
+
}
|
|
540
|
+
return () => {
|
|
541
|
+
unregisterPushToken(push.token ?? "").catch(() => undefined);
|
|
542
|
+
};
|
|
543
|
+
}, [push, registerPushToken, unregisterPushToken]);
|
|
544
|
+
useEffect(() => {
|
|
545
|
+
if (!realtimeConvexUrl) {
|
|
546
|
+
return;
|
|
547
|
+
}
|
|
548
|
+
const client = new ConvexClient(realtimeConvexUrl);
|
|
549
|
+
convexClientRef.current = client;
|
|
550
|
+
return () => {
|
|
551
|
+
convexClientRef.current = null;
|
|
552
|
+
if (typeof client.close === "function") {
|
|
553
|
+
client.close();
|
|
554
|
+
}
|
|
555
|
+
};
|
|
556
|
+
}, [realtimeConvexUrl]);
|
|
557
|
+
useEffect(() => {
|
|
558
|
+
if (!convexClientRef.current) {
|
|
559
|
+
return;
|
|
560
|
+
}
|
|
561
|
+
let disposed = false;
|
|
562
|
+
let retryTimer = null;
|
|
563
|
+
let retryAttempt = 0;
|
|
564
|
+
let unsubscribe = null;
|
|
565
|
+
const clearSubscription = () => {
|
|
566
|
+
if (typeof unsubscribe === "function") {
|
|
567
|
+
unsubscribe();
|
|
568
|
+
}
|
|
569
|
+
else {
|
|
570
|
+
unsubscribe?.unsubscribe?.();
|
|
571
|
+
}
|
|
572
|
+
unsubscribe = null;
|
|
573
|
+
};
|
|
574
|
+
async function subscribe(forceRefreshSession = false) {
|
|
575
|
+
if (!hasLoadedOnceRef.current) {
|
|
576
|
+
setLoading(true);
|
|
577
|
+
}
|
|
578
|
+
setConnectionState("connecting");
|
|
579
|
+
emitEvent({
|
|
580
|
+
type: "realtime.connecting",
|
|
581
|
+
projectId,
|
|
582
|
+
subscriberId: subscriber.subscriberId,
|
|
583
|
+
});
|
|
584
|
+
try {
|
|
585
|
+
const token = forceRefreshSession ? await refreshSession() : await ensureSession();
|
|
586
|
+
if (disposed || !convexClientRef.current) {
|
|
587
|
+
return;
|
|
588
|
+
}
|
|
589
|
+
clearSubscription();
|
|
590
|
+
const subscription = convexClientRef.current.onUpdate("widgetInbox:list", {
|
|
591
|
+
projectId,
|
|
592
|
+
sessionToken: token,
|
|
593
|
+
subscriberId: subscriber.subscriberId,
|
|
594
|
+
limit: 50,
|
|
595
|
+
}, (inbox) => {
|
|
596
|
+
if (disposed) {
|
|
597
|
+
return;
|
|
598
|
+
}
|
|
599
|
+
setItems((inbox?.items ?? []).map(normalizeInboxItem));
|
|
600
|
+
setUnreadCount(Number(inbox?.unreadCount ?? 0));
|
|
601
|
+
setLoading(false);
|
|
602
|
+
setRefreshing(false);
|
|
603
|
+
hasLoadedOnceRef.current = true;
|
|
604
|
+
setConnectionState("live");
|
|
605
|
+
setErrorMessage(null);
|
|
606
|
+
emitEvent({
|
|
607
|
+
type: "realtime.live",
|
|
608
|
+
projectId,
|
|
609
|
+
subscriberId: subscriber.subscriberId,
|
|
610
|
+
});
|
|
611
|
+
});
|
|
612
|
+
unsubscribe = subscription;
|
|
613
|
+
retryAttempt = 0;
|
|
614
|
+
}
|
|
615
|
+
catch (error) {
|
|
616
|
+
if (disposed) {
|
|
617
|
+
return;
|
|
618
|
+
}
|
|
619
|
+
const message = error instanceof Error ? error.message : "Realtime connection failed";
|
|
620
|
+
if (!forceRefreshSession &&
|
|
621
|
+
(getSessionToken || sessionEndpoint) &&
|
|
622
|
+
/session|token|expired|invalid/i.test(message)) {
|
|
623
|
+
await subscribe(true);
|
|
624
|
+
return;
|
|
625
|
+
}
|
|
626
|
+
setLoading(false);
|
|
627
|
+
setRefreshing(false);
|
|
628
|
+
setConnectionState("error");
|
|
629
|
+
setErrorMessage(message);
|
|
630
|
+
emitEvent({
|
|
631
|
+
type: "realtime.error",
|
|
632
|
+
projectId,
|
|
633
|
+
subscriberId: subscriber.subscriberId,
|
|
634
|
+
message,
|
|
635
|
+
});
|
|
636
|
+
const backoffMs = Math.min(30_000, 1_000 * 2 ** retryAttempt);
|
|
637
|
+
retryAttempt += 1;
|
|
638
|
+
emitEvent({
|
|
639
|
+
type: "realtime.retry.scheduled",
|
|
640
|
+
projectId,
|
|
641
|
+
subscriberId: subscriber.subscriberId,
|
|
642
|
+
attempt: retryAttempt,
|
|
643
|
+
retryInMs: backoffMs,
|
|
644
|
+
});
|
|
645
|
+
retryTimer = setTimeout(() => {
|
|
646
|
+
subscribe().catch(() => undefined);
|
|
647
|
+
}, backoffMs);
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
subscribe().catch(() => {
|
|
651
|
+
if (!disposed) {
|
|
652
|
+
setLoading(false);
|
|
653
|
+
setRefreshing(false);
|
|
654
|
+
setConnectionState("error");
|
|
655
|
+
setErrorMessage("Failed to start realtime updates");
|
|
656
|
+
emitEvent({
|
|
657
|
+
type: "realtime.error",
|
|
658
|
+
projectId,
|
|
659
|
+
subscriberId: subscriber.subscriberId,
|
|
660
|
+
message: "Failed to start realtime updates",
|
|
661
|
+
});
|
|
662
|
+
}
|
|
663
|
+
});
|
|
664
|
+
return () => {
|
|
665
|
+
disposed = true;
|
|
666
|
+
if (retryTimer) {
|
|
667
|
+
clearTimeout(retryTimer);
|
|
668
|
+
}
|
|
669
|
+
if (typeof unsubscribe === "function") {
|
|
670
|
+
unsubscribe();
|
|
671
|
+
}
|
|
672
|
+
else {
|
|
673
|
+
unsubscribe?.unsubscribe?.();
|
|
674
|
+
}
|
|
675
|
+
};
|
|
676
|
+
}, [
|
|
677
|
+
emitEvent,
|
|
678
|
+
ensureSession,
|
|
679
|
+
getSessionToken,
|
|
680
|
+
projectId,
|
|
681
|
+
refreshSession,
|
|
682
|
+
sessionEndpoint,
|
|
683
|
+
subscriber.subscriberId,
|
|
684
|
+
]);
|
|
685
|
+
useEffect(() => {
|
|
686
|
+
if (convexClientRef.current) {
|
|
687
|
+
// Live updates are already active via Convex subscription.
|
|
688
|
+
// Keep a low-frequency fallback refresh for resilience.
|
|
689
|
+
const id = setInterval(() => {
|
|
690
|
+
refresh({ silent: true }).catch(() => undefined);
|
|
691
|
+
}, Math.max(pollIntervalMs, 60000));
|
|
692
|
+
return () => clearInterval(id);
|
|
693
|
+
}
|
|
694
|
+
setConnectionState("polling");
|
|
695
|
+
emitEvent({
|
|
696
|
+
type: "transport.polling",
|
|
697
|
+
projectId,
|
|
698
|
+
subscriberId: subscriber.subscriberId,
|
|
699
|
+
});
|
|
700
|
+
refresh().catch(() => undefined);
|
|
701
|
+
const id = setInterval(() => {
|
|
702
|
+
refresh({ silent: true }).catch(() => undefined);
|
|
703
|
+
}, pollIntervalMs);
|
|
704
|
+
return () => clearInterval(id);
|
|
705
|
+
}, [emitEvent, pollIntervalMs, projectId, refresh, realtimeConvexUrl, subscriber.subscriberId]);
|
|
706
|
+
const effectiveConfig = useMemo(() => {
|
|
707
|
+
const merged = {
|
|
708
|
+
...serverConfig,
|
|
709
|
+
...customization,
|
|
710
|
+
};
|
|
711
|
+
return {
|
|
712
|
+
modeDefault: theme,
|
|
713
|
+
accentColor: merged.accentColor ?? DEFAULT_CONFIG.accentColor,
|
|
714
|
+
radius: merged.radius ?? DEFAULT_CONFIG.radius,
|
|
715
|
+
fontScale: merged.fontScale ?? DEFAULT_CONFIG.fontScale,
|
|
716
|
+
compact: merged.compact ?? DEFAULT_CONFIG.compact,
|
|
717
|
+
showTopicTabs: merged.showTopicTabs ?? DEFAULT_CONFIG.showTopicTabs,
|
|
718
|
+
showMarkAll: merged.showMarkAll ?? DEFAULT_CONFIG.showMarkAll,
|
|
719
|
+
headerTitle: merged.headerTitle ?? DEFAULT_CONFIG.headerTitle,
|
|
720
|
+
};
|
|
721
|
+
}, [customization, serverConfig, theme]);
|
|
722
|
+
const value = useMemo(() => ({
|
|
723
|
+
open,
|
|
724
|
+
setOpen,
|
|
725
|
+
unreadCount,
|
|
726
|
+
items,
|
|
727
|
+
loading,
|
|
728
|
+
refreshing,
|
|
729
|
+
connectionState,
|
|
730
|
+
errorMessage,
|
|
731
|
+
refresh,
|
|
732
|
+
reconnect,
|
|
733
|
+
markRead,
|
|
734
|
+
markAllRead,
|
|
735
|
+
registerPushToken,
|
|
736
|
+
unregisterPushToken,
|
|
737
|
+
handleActionClick,
|
|
738
|
+
effectiveConfig,
|
|
739
|
+
triggerRef,
|
|
740
|
+
}), [
|
|
741
|
+
open,
|
|
742
|
+
unreadCount,
|
|
743
|
+
items,
|
|
744
|
+
loading,
|
|
745
|
+
refreshing,
|
|
746
|
+
connectionState,
|
|
747
|
+
errorMessage,
|
|
748
|
+
refresh,
|
|
749
|
+
reconnect,
|
|
750
|
+
markRead,
|
|
751
|
+
markAllRead,
|
|
752
|
+
registerPushToken,
|
|
753
|
+
unregisterPushToken,
|
|
754
|
+
handleActionClick,
|
|
755
|
+
effectiveConfig,
|
|
756
|
+
]);
|
|
757
|
+
return _jsx(Ctx.Provider, { value: value, children: children });
|
|
758
|
+
}
|
|
759
|
+
export function useBeeperInbox() {
|
|
760
|
+
const ctx = useContext(Ctx);
|
|
761
|
+
if (!ctx) {
|
|
762
|
+
throw new Error("useBeeperInbox must be used inside BeeperInboxProvider");
|
|
763
|
+
}
|
|
764
|
+
return ctx;
|
|
765
|
+
}
|
|
766
|
+
function BellGlyph({ size = 20, color = "currentColor", }) {
|
|
767
|
+
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" })] }));
|
|
768
|
+
}
|
|
769
|
+
export function BeeperInboxBell({ variant = "bell", label = "Inbox", className, style, "aria-label": ariaLabel = "Open notifications", renderTrigger, }) {
|
|
770
|
+
const { open, setOpen, unreadCount, effectiveConfig, triggerRef } = useBeeperInbox();
|
|
771
|
+
const toggle = () => setOpen(!open);
|
|
772
|
+
const fs = effectiveConfig.fontScale;
|
|
773
|
+
if (renderTrigger) {
|
|
774
|
+
return (_jsx(_Fragment, { children: renderTrigger({
|
|
775
|
+
unreadCount,
|
|
776
|
+
open,
|
|
777
|
+
toggle,
|
|
778
|
+
accentColor: effectiveConfig.accentColor,
|
|
779
|
+
fontScale: fs,
|
|
780
|
+
triggerRef,
|
|
781
|
+
}) }));
|
|
782
|
+
}
|
|
783
|
+
if (variant === "minimal") {
|
|
784
|
+
return (_jsxs("button", { type: "button", ref: (el) => {
|
|
785
|
+
triggerRef.current = el;
|
|
786
|
+
}, className: className, "aria-label": ariaLabel, onClick: toggle, style: {
|
|
787
|
+
borderRadius: 999,
|
|
788
|
+
border: "1px solid #d1d5db",
|
|
789
|
+
padding: "8px 12px",
|
|
790
|
+
background: "white",
|
|
791
|
+
display: "inline-flex",
|
|
792
|
+
alignItems: "center",
|
|
793
|
+
gap: 8,
|
|
794
|
+
fontSize: `${14 * fs}px`,
|
|
795
|
+
cursor: "pointer",
|
|
796
|
+
...style,
|
|
797
|
+
}, children: [_jsx("span", { children: label }), _jsx("span", { style: {
|
|
798
|
+
background: effectiveConfig.accentColor,
|
|
799
|
+
color: "white",
|
|
800
|
+
borderRadius: 999,
|
|
801
|
+
padding: "2px 8px",
|
|
802
|
+
fontSize: 12,
|
|
803
|
+
minWidth: "1.25rem",
|
|
804
|
+
textAlign: "center",
|
|
805
|
+
}, children: unreadCount })] }));
|
|
806
|
+
}
|
|
807
|
+
const useHostStyles = !className;
|
|
808
|
+
return (_jsxs("button", { type: "button", ref: (el) => {
|
|
809
|
+
triggerRef.current = el;
|
|
810
|
+
}, className: className, "aria-label": ariaLabel, onClick: toggle, style: {
|
|
811
|
+
position: "relative",
|
|
812
|
+
display: "inline-flex",
|
|
813
|
+
alignItems: "center",
|
|
814
|
+
justifyContent: "center",
|
|
815
|
+
...(useHostStyles
|
|
816
|
+
? {
|
|
817
|
+
width: `${40 * fs}px`,
|
|
818
|
+
height: `${40 * fs}px`,
|
|
819
|
+
borderRadius: 999,
|
|
820
|
+
border: "1px solid #d1d5db",
|
|
821
|
+
background: "white",
|
|
822
|
+
color: "#374151",
|
|
823
|
+
}
|
|
824
|
+
: {}),
|
|
825
|
+
cursor: "pointer",
|
|
826
|
+
padding: 0,
|
|
827
|
+
...style,
|
|
828
|
+
}, children: [_jsx(BellGlyph, { size: Math.round(20 * fs) }), unreadCount > 0 ? (_jsx("span", { style: {
|
|
829
|
+
position: "absolute",
|
|
830
|
+
top: 2,
|
|
831
|
+
right: 2,
|
|
832
|
+
minWidth: "1rem",
|
|
833
|
+
height: "1rem",
|
|
834
|
+
padding: unreadCount > 9 ? "0 4px" : 0,
|
|
835
|
+
borderRadius: 999,
|
|
836
|
+
background: effectiveConfig.accentColor,
|
|
837
|
+
color: "white",
|
|
838
|
+
fontSize: 10,
|
|
839
|
+
fontWeight: 600,
|
|
840
|
+
display: "flex",
|
|
841
|
+
alignItems: "center",
|
|
842
|
+
justifyContent: "center",
|
|
843
|
+
lineHeight: 1,
|
|
844
|
+
}, children: unreadCount > 99 ? "99+" : unreadCount })) : null] }));
|
|
845
|
+
}
|
|
846
|
+
function ShadowContainer({ children }) {
|
|
847
|
+
const hostRef = useRef(null);
|
|
848
|
+
const [portalTarget, setPortalTarget] = useState(null);
|
|
849
|
+
useLayoutEffect(() => {
|
|
850
|
+
const el = hostRef.current;
|
|
851
|
+
if (!el) {
|
|
852
|
+
return;
|
|
853
|
+
}
|
|
854
|
+
let root = el.shadowRoot;
|
|
855
|
+
if (!root) {
|
|
856
|
+
root = el.attachShadow({ mode: "open" });
|
|
857
|
+
}
|
|
858
|
+
setPortalTarget(root);
|
|
859
|
+
return () => {
|
|
860
|
+
setPortalTarget(null);
|
|
861
|
+
};
|
|
862
|
+
}, []);
|
|
863
|
+
return (_jsx("div", { ref: hostRef, children: portalTarget
|
|
864
|
+
? createPortal(_jsxs(_Fragment, { children: [_jsx("style", { children: `
|
|
865
|
+
:host { all: initial; display: block; }
|
|
866
|
+
.bw-root { font-family: Manrope, ui-sans-serif, system-ui, sans-serif; width: 100%; max-width: 100%; box-sizing: border-box; }
|
|
867
|
+
` }), children] }), portalTarget)
|
|
868
|
+
: null }));
|
|
869
|
+
}
|
|
870
|
+
const PANEL_WIDTH = 384;
|
|
871
|
+
const PANEL_ESTIMATE_HEIGHT = 440;
|
|
872
|
+
export function BeeperInboxPanel({ placement = "anchor", } = {}) {
|
|
873
|
+
const { open, setOpen, items, loading, refreshing, connectionState, refresh, reconnect, markRead, markAllRead, handleActionClick, effectiveConfig, triggerRef, } = useBeeperInbox();
|
|
874
|
+
const [layout, setLayout] = useState({ top: 16, right: 16, maxListHeight: 320 });
|
|
875
|
+
const panelRef = useRef(null);
|
|
876
|
+
useEffect(() => {
|
|
877
|
+
if (!open) {
|
|
878
|
+
return;
|
|
879
|
+
}
|
|
880
|
+
const isInsideNode = (event, node) => {
|
|
881
|
+
if (!node) {
|
|
882
|
+
return false;
|
|
883
|
+
}
|
|
884
|
+
const path = typeof event.composedPath === "function" ? event.composedPath() : undefined;
|
|
885
|
+
if (path && path.includes(node)) {
|
|
886
|
+
return true;
|
|
887
|
+
}
|
|
888
|
+
const target = event.target;
|
|
889
|
+
return target instanceof Node ? node.contains(target) : false;
|
|
890
|
+
};
|
|
891
|
+
const handleInteractOutside = (event) => {
|
|
892
|
+
if (isInsideNode(event, panelRef.current)) {
|
|
893
|
+
return;
|
|
894
|
+
}
|
|
895
|
+
if (isInsideNode(event, triggerRef.current)) {
|
|
896
|
+
return;
|
|
897
|
+
}
|
|
898
|
+
setOpen(false);
|
|
899
|
+
};
|
|
900
|
+
document.addEventListener("pointerdown", handleInteractOutside, true);
|
|
901
|
+
document.addEventListener("focusin", handleInteractOutside, true);
|
|
902
|
+
return () => {
|
|
903
|
+
document.removeEventListener("pointerdown", handleInteractOutside, true);
|
|
904
|
+
document.removeEventListener("focusin", handleInteractOutside, true);
|
|
905
|
+
};
|
|
906
|
+
}, [open, setOpen, triggerRef]);
|
|
907
|
+
useLayoutEffect(() => {
|
|
908
|
+
if (!open) {
|
|
909
|
+
return;
|
|
910
|
+
}
|
|
911
|
+
const gap = 10;
|
|
912
|
+
const chrome = 168;
|
|
913
|
+
const compute = () => {
|
|
914
|
+
const w = window.innerWidth;
|
|
915
|
+
const h = window.innerHeight;
|
|
916
|
+
if (placement === "fixed-bottom-end") {
|
|
917
|
+
const top = Math.max(8, h - PANEL_ESTIMATE_HEIGHT - 16);
|
|
918
|
+
setLayout({
|
|
919
|
+
top,
|
|
920
|
+
right: 16,
|
|
921
|
+
maxListHeight: Math.max(180, Math.min(400, h - top - chrome)),
|
|
922
|
+
});
|
|
923
|
+
return;
|
|
924
|
+
}
|
|
925
|
+
const el = triggerRef.current;
|
|
926
|
+
if (!el) {
|
|
927
|
+
setLayout({
|
|
928
|
+
top: gap,
|
|
929
|
+
right: gap,
|
|
930
|
+
maxListHeight: Math.max(180, Math.min(400, h - gap - chrome)),
|
|
931
|
+
});
|
|
932
|
+
return;
|
|
933
|
+
}
|
|
934
|
+
const r = el.getBoundingClientRect();
|
|
935
|
+
let top = r.bottom + gap;
|
|
936
|
+
let right = w - r.right;
|
|
937
|
+
right = Math.max(8, Math.min(right, w - PANEL_WIDTH - 8));
|
|
938
|
+
if (top + PANEL_ESTIMATE_HEIGHT > h - 8) {
|
|
939
|
+
const above = r.top - PANEL_ESTIMATE_HEIGHT - gap;
|
|
940
|
+
top = above >= 8 ? above : Math.max(8, h - PANEL_ESTIMATE_HEIGHT - 8);
|
|
941
|
+
}
|
|
942
|
+
const maxList = Math.max(180, Math.min(440, h - top - chrome));
|
|
943
|
+
setLayout({ top, right, maxListHeight: maxList });
|
|
944
|
+
};
|
|
945
|
+
compute();
|
|
946
|
+
const ro = new ResizeObserver(compute);
|
|
947
|
+
if (triggerRef.current) {
|
|
948
|
+
ro.observe(triggerRef.current);
|
|
949
|
+
}
|
|
950
|
+
window.addEventListener("resize", compute);
|
|
951
|
+
window.addEventListener("scroll", compute, true);
|
|
952
|
+
return () => {
|
|
953
|
+
ro.disconnect();
|
|
954
|
+
window.removeEventListener("resize", compute);
|
|
955
|
+
window.removeEventListener("scroll", compute, true);
|
|
956
|
+
};
|
|
957
|
+
}, [open, placement, triggerRef]);
|
|
958
|
+
if (!open) {
|
|
959
|
+
return null;
|
|
960
|
+
}
|
|
961
|
+
const mode = resolveTheme(effectiveConfig.modeDefault);
|
|
962
|
+
const dark = mode === "dark";
|
|
963
|
+
const light = {
|
|
964
|
+
bg: "#fffaf5",
|
|
965
|
+
fg: "#2b221d",
|
|
966
|
+
muted: "#7d685d",
|
|
967
|
+
border: "#eadbcc",
|
|
968
|
+
surface: "#fffdf9",
|
|
969
|
+
itemBg: "#fffcf8",
|
|
970
|
+
shadow: "0 24px 54px rgba(38, 24, 12, 0.14)",
|
|
971
|
+
};
|
|
972
|
+
const toolbarBtn = dark
|
|
973
|
+
? {
|
|
974
|
+
border: "1px solid #3a4250",
|
|
975
|
+
background: "rgba(255,255,255,0.02)",
|
|
976
|
+
color: "#e5e7eb",
|
|
977
|
+
borderRadius: effectiveConfig.radius - 4,
|
|
978
|
+
padding: "6px 10px",
|
|
979
|
+
fontSize: "0.85em",
|
|
980
|
+
cursor: "pointer",
|
|
981
|
+
}
|
|
982
|
+
: {
|
|
983
|
+
border: `1px solid ${light.border}`,
|
|
984
|
+
background: light.surface,
|
|
985
|
+
color: light.fg,
|
|
986
|
+
borderRadius: effectiveConfig.radius - 4,
|
|
987
|
+
padding: "6px 10px",
|
|
988
|
+
fontSize: "0.85em",
|
|
989
|
+
cursor: "pointer",
|
|
990
|
+
};
|
|
991
|
+
const linkBtn = {
|
|
992
|
+
border: "none",
|
|
993
|
+
background: "transparent",
|
|
994
|
+
color: effectiveConfig.accentColor,
|
|
995
|
+
cursor: "pointer",
|
|
996
|
+
fontSize: "0.88em",
|
|
997
|
+
fontWeight: 600,
|
|
998
|
+
padding: "4px 0",
|
|
999
|
+
};
|
|
1000
|
+
return (_jsx("div", { style: {
|
|
1001
|
+
position: "fixed",
|
|
1002
|
+
zIndex: 9999,
|
|
1003
|
+
top: layout.top,
|
|
1004
|
+
right: layout.right,
|
|
1005
|
+
width: PANEL_WIDTH,
|
|
1006
|
+
maxWidth: `calc(100vw - 16px)`,
|
|
1007
|
+
pointerEvents: "none",
|
|
1008
|
+
}, children: _jsx("div", { style: { pointerEvents: "auto" }, children: _jsx(ShadowContainer, { children: _jsxs("div", { ref: panelRef, className: "bw-root", style: {
|
|
1009
|
+
width: "100%",
|
|
1010
|
+
boxSizing: "border-box",
|
|
1011
|
+
background: dark ? "#121418" : light.bg,
|
|
1012
|
+
color: dark ? "#f9fafb" : light.fg,
|
|
1013
|
+
border: dark ? "1px solid #2b313b" : `1px solid ${light.border}`,
|
|
1014
|
+
borderRadius: effectiveConfig.radius,
|
|
1015
|
+
boxShadow: dark ? "0 16px 30px rgba(0,0,0,.45)" : light.shadow,
|
|
1016
|
+
padding: effectiveConfig.compact ? 10 : 14,
|
|
1017
|
+
fontSize: `${14 * effectiveConfig.fontScale}px`,
|
|
1018
|
+
}, children: [_jsxs("div", { style: {
|
|
1019
|
+
display: "flex",
|
|
1020
|
+
justifyContent: "space-between",
|
|
1021
|
+
alignItems: "center",
|
|
1022
|
+
gap: 8,
|
|
1023
|
+
}, children: [_jsx("strong", { 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", { 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" })] })] }), connectionState !== "live" ? (_jsx("div", { children: connectionState === "error" ? (_jsx("button", { type: "button", style: toolbarBtn, onClick: () => reconnect(), children: "Reconnect" })) : null })) : null, _jsx("div", { style: {
|
|
1024
|
+
marginTop: 12,
|
|
1025
|
+
display: "grid",
|
|
1026
|
+
gap: 8,
|
|
1027
|
+
maxHeight: layout.maxListHeight,
|
|
1028
|
+
minHeight: items.length === 0 && !loading ? 140 : undefined,
|
|
1029
|
+
overflowY: "auto",
|
|
1030
|
+
paddingRight: 2,
|
|
1031
|
+
}, children: loading && items.length === 0 ? (_jsx("div", { style: {
|
|
1032
|
+
alignSelf: "center",
|
|
1033
|
+
padding: "18px 0",
|
|
1034
|
+
color: dark ? "#d0d5dd" : light.muted,
|
|
1035
|
+
fontSize: "0.92em",
|
|
1036
|
+
}, children: "Loading notifications..." })) : items.length === 0 ? (_jsx("div", { style: {
|
|
1037
|
+
alignSelf: "center",
|
|
1038
|
+
textAlign: "center",
|
|
1039
|
+
padding: "30px 18px",
|
|
1040
|
+
lineHeight: 1.5,
|
|
1041
|
+
color: dark ? "#c7b6a7" : light.muted,
|
|
1042
|
+
border: dark ? "1px dashed #3a4250" : `1px dashed ${light.border}`,
|
|
1043
|
+
borderRadius: effectiveConfig.radius - 2,
|
|
1044
|
+
background: dark ? "#181411" : "#fffdf9",
|
|
1045
|
+
}, children: "No notifications yet. New activity will appear here as soon as this subscriber receives it." })) : (items.map((item) => (_jsxs("div", { style: {
|
|
1046
|
+
border: dark ? "1px solid #2b313b" : `1px solid ${light.border}`,
|
|
1047
|
+
borderRadius: effectiveConfig.radius - 2,
|
|
1048
|
+
padding: 14,
|
|
1049
|
+
background: item.readAt
|
|
1050
|
+
? dark
|
|
1051
|
+
? "#181411"
|
|
1052
|
+
: "#fffaf4"
|
|
1053
|
+
: dark
|
|
1054
|
+
? "#1b1613"
|
|
1055
|
+
: light.itemBg,
|
|
1056
|
+
boxShadow: item.readAt
|
|
1057
|
+
? "none"
|
|
1058
|
+
: dark
|
|
1059
|
+
? `inset 0 0 0 1px ${withAlpha(effectiveConfig.accentColor, 0.18)}`
|
|
1060
|
+
: `inset 0 0 0 1px ${withAlpha(effectiveConfig.accentColor, 0.14)}`,
|
|
1061
|
+
}, children: [_jsx("div", { style: { fontWeight: 700, marginBottom: 6, letterSpacing: "-0.02em" }, children: item.title ?? "Notification" }), _jsx("div", { style: {
|
|
1062
|
+
opacity: 0.92,
|
|
1063
|
+
marginBottom: 10,
|
|
1064
|
+
lineHeight: 1.5,
|
|
1065
|
+
color: dark ? "#efe3d8" : "#4e3c34",
|
|
1066
|
+
}, children: item.body }), _jsxs("div", { style: {
|
|
1067
|
+
display: "flex",
|
|
1068
|
+
justifyContent: "space-between",
|
|
1069
|
+
alignItems: "center",
|
|
1070
|
+
gap: 12,
|
|
1071
|
+
}, children: [_jsxs("div", { style: {
|
|
1072
|
+
display: "flex",
|
|
1073
|
+
alignItems: "center",
|
|
1074
|
+
gap: 10,
|
|
1075
|
+
flexWrap: "wrap",
|
|
1076
|
+
}, children: [_jsx("small", { style: { opacity: 0.65 }, children: timeAgo(item.createdAt) }), item.actionUrl ? (_jsx("button", { type: "button", onClick: () => {
|
|
1077
|
+
void handleActionClick(item);
|
|
1078
|
+
}, style: linkBtn, children: item.actionLabel ?? "Open" })) : null] }), !item.readAt ? (_jsx("button", { type: "button", style: linkBtn, onClick: () => markRead(item._id), children: "Mark read" })) : (_jsx("small", { style: { opacity: 0.65 }, children: "Read" }))] })] }, item._id)))) }), effectiveConfig.showMarkAll && items.length > 0 ? (_jsx("div", { style: {
|
|
1079
|
+
display: "flex",
|
|
1080
|
+
justifyContent: "flex-end",
|
|
1081
|
+
marginTop: 12,
|
|
1082
|
+
paddingTop: 10,
|
|
1083
|
+
borderTop: dark ? "1px solid #2b313b" : `1px solid ${light.border}`,
|
|
1084
|
+
}, children: _jsx("button", { type: "button", style: linkBtn, onClick: () => markAllRead(), children: "Mark all as read" }) })) : null] }) }) }) }));
|
|
1085
|
+
}
|
|
1086
|
+
export const __internal = {
|
|
1087
|
+
parseTokenExpiryMs,
|
|
1088
|
+
isSessionExpiringSoon,
|
|
1089
|
+
};
|
|
1090
|
+
//# sourceMappingURL=index.js.map
|