@realtimexsco/live-chat 1.4.3 → 1.4.4

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.d.mts CHANGED
@@ -1548,6 +1548,8 @@ declare function Calendar({ className, classNames, showOutsideDays, captionLayou
1548
1548
  }): React.JSX.Element;
1549
1549
  declare function CalendarDayButton({ className, day, modifiers, ...props }: React.ComponentProps<typeof DayButton>): React.JSX.Element;
1550
1550
 
1551
+ /** Fired on window whenever this device's push opt-in changes. */
1552
+ declare const PUSH_CHANGED_EVENT = "realtimex:push-changed";
1551
1553
  interface PushConfig {
1552
1554
  /** Firebase credentials present on the backend deployment. */
1553
1555
  configured: boolean;
@@ -1634,4 +1636,30 @@ interface PushNotificationToggleProps {
1634
1636
  */
1635
1637
  declare const PushNotificationToggle: ({ className, label, description, }: PushNotificationToggleProps) => React.JSX.Element | null;
1636
1638
 
1637
- export { type ActiveChannelMessagesSlotProps, type AdminsDrawerSlotProps, type AttachmentsDrawerSlotProps, type AvatarSlotProps, CHAT_API_KEYS, CHAT_GET_API_KEYS, Calendar, CalendarDayButton, Channel, type ChannelDetailsDrawerSlotProps, ChannelHeaderView as ChannelHeader, type ChannelHeaderSlotProps, ChannelListView as ChannelList, ChannelListItem, type ChannelListItemSlotProps, type ChannelListSlotProps, type ChannelMessageBoxSlotProps, Chat, type ChatActionModalSlotProps, ChatAlertsProvider, type ChatApiKey, ChatAvatar, type ChatCallContext, type ChatClassNames, type ChatColorMode, type ChatComponents, type ChatCustomizationConfig, ChatCustomizationProvider, ChatDateJumpMenu, type ChatDateTimePreferences, type ChatFeatures, type ChatGetApiKey, ChatLayout, type ChatLayoutConfig, type ChatLayoutSlotProps, ChatLocaleProvider, ChatMain, type ChatPanelAlertsSlotProps, type ChatQueryParams, type ChatQueryParamsByApi, ChatThemeProvider, ChatViewport, type ChatViewportHeight, DefaultChannelListItem, DefaultChatAvatar, DefaultChatLayout, ForwardModalView as ForwardModal, type ForwardModalSlotProps, HeaderCallActions, type HeaderCallActionsSlotProps, type HeaderLeftSideSlotProps, type HeaderRightSideSlotProps, type HeaderSearchOverlaySlotProps, type IAttachment, type IChannel, type IDMDelete, type IDMEditMessage, type IDMForward, type IDMMessage, type IDMPin, type IDMReaction, type IDMRead, type IDMStar, type IDMTyping, type IDMUnstar, type IMessage, type ISocketConfig, type JumpToPreset, LoggedUserDetails, type LoggedUserDetailsSlotProps, type MembersDrawerSlotProps, type MessageAttachmentsSlotProps, ChannelMessageBoxView as MessageInput, MessageItemView as MessageItem, type MessageItemSlotProps, ActiveChannelMessagesView as MessageList, type MessageReactionsSlotProps, type MessageReplySnippetSlotProps, type MessageStatusSlotProps, type MessageToolbarSlotProps, type PendingJump, type PermissionDrawerSlotProps, type PhoneCallButtonSlotProps, type PinnedMessagesDrawerSlotProps, type PushConfig, PushNotificationToggle, type PushNotificationToggleProps, type PushNotificationsState, type PushPreference, type StarredMessagesDrawerSlotProps, type UIConfig, type UsePushNotifications, type VideoCallButtonSlotProps, apiGetPushConfig, apiGetPushPreference, apiRegisterPushToken, apiRemovePushToken, apiUpdatePushPreference, capitalizeFirst, clampJumpDate, ChatMain as default, defaultChatClassNames, defaultChatComponents, defaultChatFeatures, defaultChatLayoutConfig, disablePushOnThisDevice, downloadFile, enablePushOnThisDevice, getChatBaseUrl, getChatQueryParamApis, getChatQueryParams, getChatQueryParamsByApi, getChatSocketUrl, getFirstAndLastNameOneCharacter, getResponsiveWidth, getSocketConfig, getStoredPushToken, isEmpty, isPushSupported, mergeChatCustomization, mergeChatLayoutConfig, onForegroundPush, packageDefaultComponents, resolveApiUrl, resolveChatApiKey, resolveJumpDateBounds, resolveJumpPreset, resolveJumpStep, resolveSocketUrl, setChatAccessToken, setChatBaseURL, setChatClientId, setChatQueryParamApis, setChatQueryParams, setChatQueryParamsByApi, setChatSocketUrl, showNotification, smoothScrollToMessage, socketService, startOfLocalDay, toDateInputValue, uniqueList, useChatAlerts, useChatContext, useChatController, useChatCustomization, useChatCustomizationOptional, useChatFeatures, useChatFeaturesOptional, useChatLocale, useStore as useChatStore, useChatTheme, usePushNotifications };
1639
+ interface ForegroundPushPayload {
1640
+ title?: string;
1641
+ body?: string;
1642
+ data?: Record<string, string>;
1643
+ }
1644
+ interface ForegroundPushBridgeProps {
1645
+ /**
1646
+ * Replace the default toast with your own handler. Return `false` from it
1647
+ * to fall back to the default toast.
1648
+ */
1649
+ onPush?: (payload: ForegroundPushPayload) => void | boolean;
1650
+ }
1651
+ /**
1652
+ * Slack-style routing for pushes that arrive while the tab is FOCUSED
1653
+ * (unfocused tabs / other apps are handled by the service worker, which shows
1654
+ * the OS notification):
1655
+ *
1656
+ * - message belongs to the conversation currently open → suppressed
1657
+ * entirely (the user is already reading it)
1658
+ * - any other conversation → in-app toast
1659
+ *
1660
+ * Mounted automatically by ChatMain; does nothing until this device has
1661
+ * opted in to push (no firebase import, no listeners).
1662
+ */
1663
+ declare const ForegroundPushBridge: ({ onPush }: ForegroundPushBridgeProps) => null;
1664
+
1665
+ export { type ActiveChannelMessagesSlotProps, type AdminsDrawerSlotProps, type AttachmentsDrawerSlotProps, type AvatarSlotProps, CHAT_API_KEYS, CHAT_GET_API_KEYS, Calendar, CalendarDayButton, Channel, type ChannelDetailsDrawerSlotProps, ChannelHeaderView as ChannelHeader, type ChannelHeaderSlotProps, ChannelListView as ChannelList, ChannelListItem, type ChannelListItemSlotProps, type ChannelListSlotProps, type ChannelMessageBoxSlotProps, Chat, type ChatActionModalSlotProps, ChatAlertsProvider, type ChatApiKey, ChatAvatar, type ChatCallContext, type ChatClassNames, type ChatColorMode, type ChatComponents, type ChatCustomizationConfig, ChatCustomizationProvider, ChatDateJumpMenu, type ChatDateTimePreferences, type ChatFeatures, type ChatGetApiKey, ChatLayout, type ChatLayoutConfig, type ChatLayoutSlotProps, ChatLocaleProvider, ChatMain, type ChatPanelAlertsSlotProps, type ChatQueryParams, type ChatQueryParamsByApi, ChatThemeProvider, ChatViewport, type ChatViewportHeight, DefaultChannelListItem, DefaultChatAvatar, DefaultChatLayout, ForegroundPushBridge, type ForegroundPushBridgeProps, type ForegroundPushPayload, ForwardModalView as ForwardModal, type ForwardModalSlotProps, HeaderCallActions, type HeaderCallActionsSlotProps, type HeaderLeftSideSlotProps, type HeaderRightSideSlotProps, type HeaderSearchOverlaySlotProps, type IAttachment, type IChannel, type IDMDelete, type IDMEditMessage, type IDMForward, type IDMMessage, type IDMPin, type IDMReaction, type IDMRead, type IDMStar, type IDMTyping, type IDMUnstar, type IMessage, type ISocketConfig, type JumpToPreset, LoggedUserDetails, type LoggedUserDetailsSlotProps, type MembersDrawerSlotProps, type MessageAttachmentsSlotProps, ChannelMessageBoxView as MessageInput, MessageItemView as MessageItem, type MessageItemSlotProps, ActiveChannelMessagesView as MessageList, type MessageReactionsSlotProps, type MessageReplySnippetSlotProps, type MessageStatusSlotProps, type MessageToolbarSlotProps, PUSH_CHANGED_EVENT, type PendingJump, type PermissionDrawerSlotProps, type PhoneCallButtonSlotProps, type PinnedMessagesDrawerSlotProps, type PushConfig, PushNotificationToggle, type PushNotificationToggleProps, type PushNotificationsState, type PushPreference, type StarredMessagesDrawerSlotProps, type UIConfig, type UsePushNotifications, type VideoCallButtonSlotProps, apiGetPushConfig, apiGetPushPreference, apiRegisterPushToken, apiRemovePushToken, apiUpdatePushPreference, capitalizeFirst, clampJumpDate, ChatMain as default, defaultChatClassNames, defaultChatComponents, defaultChatFeatures, defaultChatLayoutConfig, disablePushOnThisDevice, downloadFile, enablePushOnThisDevice, getChatBaseUrl, getChatQueryParamApis, getChatQueryParams, getChatQueryParamsByApi, getChatSocketUrl, getFirstAndLastNameOneCharacter, getResponsiveWidth, getSocketConfig, getStoredPushToken, isEmpty, isPushSupported, mergeChatCustomization, mergeChatLayoutConfig, onForegroundPush, packageDefaultComponents, resolveApiUrl, resolveChatApiKey, resolveJumpDateBounds, resolveJumpPreset, resolveJumpStep, resolveSocketUrl, setChatAccessToken, setChatBaseURL, setChatClientId, setChatQueryParamApis, setChatQueryParams, setChatQueryParamsByApi, setChatSocketUrl, showNotification, smoothScrollToMessage, socketService, startOfLocalDay, toDateInputValue, uniqueList, useChatAlerts, useChatContext, useChatController, useChatCustomization, useChatCustomizationOptional, useChatFeatures, useChatFeaturesOptional, useChatLocale, useStore as useChatStore, useChatTheme, usePushNotifications };
package/dist/index.d.ts CHANGED
@@ -1548,6 +1548,8 @@ declare function Calendar({ className, classNames, showOutsideDays, captionLayou
1548
1548
  }): React.JSX.Element;
1549
1549
  declare function CalendarDayButton({ className, day, modifiers, ...props }: React.ComponentProps<typeof DayButton>): React.JSX.Element;
1550
1550
 
1551
+ /** Fired on window whenever this device's push opt-in changes. */
1552
+ declare const PUSH_CHANGED_EVENT = "realtimex:push-changed";
1551
1553
  interface PushConfig {
1552
1554
  /** Firebase credentials present on the backend deployment. */
1553
1555
  configured: boolean;
@@ -1634,4 +1636,30 @@ interface PushNotificationToggleProps {
1634
1636
  */
1635
1637
  declare const PushNotificationToggle: ({ className, label, description, }: PushNotificationToggleProps) => React.JSX.Element | null;
1636
1638
 
1637
- export { type ActiveChannelMessagesSlotProps, type AdminsDrawerSlotProps, type AttachmentsDrawerSlotProps, type AvatarSlotProps, CHAT_API_KEYS, CHAT_GET_API_KEYS, Calendar, CalendarDayButton, Channel, type ChannelDetailsDrawerSlotProps, ChannelHeaderView as ChannelHeader, type ChannelHeaderSlotProps, ChannelListView as ChannelList, ChannelListItem, type ChannelListItemSlotProps, type ChannelListSlotProps, type ChannelMessageBoxSlotProps, Chat, type ChatActionModalSlotProps, ChatAlertsProvider, type ChatApiKey, ChatAvatar, type ChatCallContext, type ChatClassNames, type ChatColorMode, type ChatComponents, type ChatCustomizationConfig, ChatCustomizationProvider, ChatDateJumpMenu, type ChatDateTimePreferences, type ChatFeatures, type ChatGetApiKey, ChatLayout, type ChatLayoutConfig, type ChatLayoutSlotProps, ChatLocaleProvider, ChatMain, type ChatPanelAlertsSlotProps, type ChatQueryParams, type ChatQueryParamsByApi, ChatThemeProvider, ChatViewport, type ChatViewportHeight, DefaultChannelListItem, DefaultChatAvatar, DefaultChatLayout, ForwardModalView as ForwardModal, type ForwardModalSlotProps, HeaderCallActions, type HeaderCallActionsSlotProps, type HeaderLeftSideSlotProps, type HeaderRightSideSlotProps, type HeaderSearchOverlaySlotProps, type IAttachment, type IChannel, type IDMDelete, type IDMEditMessage, type IDMForward, type IDMMessage, type IDMPin, type IDMReaction, type IDMRead, type IDMStar, type IDMTyping, type IDMUnstar, type IMessage, type ISocketConfig, type JumpToPreset, LoggedUserDetails, type LoggedUserDetailsSlotProps, type MembersDrawerSlotProps, type MessageAttachmentsSlotProps, ChannelMessageBoxView as MessageInput, MessageItemView as MessageItem, type MessageItemSlotProps, ActiveChannelMessagesView as MessageList, type MessageReactionsSlotProps, type MessageReplySnippetSlotProps, type MessageStatusSlotProps, type MessageToolbarSlotProps, type PendingJump, type PermissionDrawerSlotProps, type PhoneCallButtonSlotProps, type PinnedMessagesDrawerSlotProps, type PushConfig, PushNotificationToggle, type PushNotificationToggleProps, type PushNotificationsState, type PushPreference, type StarredMessagesDrawerSlotProps, type UIConfig, type UsePushNotifications, type VideoCallButtonSlotProps, apiGetPushConfig, apiGetPushPreference, apiRegisterPushToken, apiRemovePushToken, apiUpdatePushPreference, capitalizeFirst, clampJumpDate, ChatMain as default, defaultChatClassNames, defaultChatComponents, defaultChatFeatures, defaultChatLayoutConfig, disablePushOnThisDevice, downloadFile, enablePushOnThisDevice, getChatBaseUrl, getChatQueryParamApis, getChatQueryParams, getChatQueryParamsByApi, getChatSocketUrl, getFirstAndLastNameOneCharacter, getResponsiveWidth, getSocketConfig, getStoredPushToken, isEmpty, isPushSupported, mergeChatCustomization, mergeChatLayoutConfig, onForegroundPush, packageDefaultComponents, resolveApiUrl, resolveChatApiKey, resolveJumpDateBounds, resolveJumpPreset, resolveJumpStep, resolveSocketUrl, setChatAccessToken, setChatBaseURL, setChatClientId, setChatQueryParamApis, setChatQueryParams, setChatQueryParamsByApi, setChatSocketUrl, showNotification, smoothScrollToMessage, socketService, startOfLocalDay, toDateInputValue, uniqueList, useChatAlerts, useChatContext, useChatController, useChatCustomization, useChatCustomizationOptional, useChatFeatures, useChatFeaturesOptional, useChatLocale, useStore as useChatStore, useChatTheme, usePushNotifications };
1639
+ interface ForegroundPushPayload {
1640
+ title?: string;
1641
+ body?: string;
1642
+ data?: Record<string, string>;
1643
+ }
1644
+ interface ForegroundPushBridgeProps {
1645
+ /**
1646
+ * Replace the default toast with your own handler. Return `false` from it
1647
+ * to fall back to the default toast.
1648
+ */
1649
+ onPush?: (payload: ForegroundPushPayload) => void | boolean;
1650
+ }
1651
+ /**
1652
+ * Slack-style routing for pushes that arrive while the tab is FOCUSED
1653
+ * (unfocused tabs / other apps are handled by the service worker, which shows
1654
+ * the OS notification):
1655
+ *
1656
+ * - message belongs to the conversation currently open → suppressed
1657
+ * entirely (the user is already reading it)
1658
+ * - any other conversation → in-app toast
1659
+ *
1660
+ * Mounted automatically by ChatMain; does nothing until this device has
1661
+ * opted in to push (no firebase import, no listeners).
1662
+ */
1663
+ declare const ForegroundPushBridge: ({ onPush }: ForegroundPushBridgeProps) => null;
1664
+
1665
+ export { type ActiveChannelMessagesSlotProps, type AdminsDrawerSlotProps, type AttachmentsDrawerSlotProps, type AvatarSlotProps, CHAT_API_KEYS, CHAT_GET_API_KEYS, Calendar, CalendarDayButton, Channel, type ChannelDetailsDrawerSlotProps, ChannelHeaderView as ChannelHeader, type ChannelHeaderSlotProps, ChannelListView as ChannelList, ChannelListItem, type ChannelListItemSlotProps, type ChannelListSlotProps, type ChannelMessageBoxSlotProps, Chat, type ChatActionModalSlotProps, ChatAlertsProvider, type ChatApiKey, ChatAvatar, type ChatCallContext, type ChatClassNames, type ChatColorMode, type ChatComponents, type ChatCustomizationConfig, ChatCustomizationProvider, ChatDateJumpMenu, type ChatDateTimePreferences, type ChatFeatures, type ChatGetApiKey, ChatLayout, type ChatLayoutConfig, type ChatLayoutSlotProps, ChatLocaleProvider, ChatMain, type ChatPanelAlertsSlotProps, type ChatQueryParams, type ChatQueryParamsByApi, ChatThemeProvider, ChatViewport, type ChatViewportHeight, DefaultChannelListItem, DefaultChatAvatar, DefaultChatLayout, ForegroundPushBridge, type ForegroundPushBridgeProps, type ForegroundPushPayload, ForwardModalView as ForwardModal, type ForwardModalSlotProps, HeaderCallActions, type HeaderCallActionsSlotProps, type HeaderLeftSideSlotProps, type HeaderRightSideSlotProps, type HeaderSearchOverlaySlotProps, type IAttachment, type IChannel, type IDMDelete, type IDMEditMessage, type IDMForward, type IDMMessage, type IDMPin, type IDMReaction, type IDMRead, type IDMStar, type IDMTyping, type IDMUnstar, type IMessage, type ISocketConfig, type JumpToPreset, LoggedUserDetails, type LoggedUserDetailsSlotProps, type MembersDrawerSlotProps, type MessageAttachmentsSlotProps, ChannelMessageBoxView as MessageInput, MessageItemView as MessageItem, type MessageItemSlotProps, ActiveChannelMessagesView as MessageList, type MessageReactionsSlotProps, type MessageReplySnippetSlotProps, type MessageStatusSlotProps, type MessageToolbarSlotProps, PUSH_CHANGED_EVENT, type PendingJump, type PermissionDrawerSlotProps, type PhoneCallButtonSlotProps, type PinnedMessagesDrawerSlotProps, type PushConfig, PushNotificationToggle, type PushNotificationToggleProps, type PushNotificationsState, type PushPreference, type StarredMessagesDrawerSlotProps, type UIConfig, type UsePushNotifications, type VideoCallButtonSlotProps, apiGetPushConfig, apiGetPushPreference, apiRegisterPushToken, apiRemovePushToken, apiUpdatePushPreference, capitalizeFirst, clampJumpDate, ChatMain as default, defaultChatClassNames, defaultChatComponents, defaultChatFeatures, defaultChatLayoutConfig, disablePushOnThisDevice, downloadFile, enablePushOnThisDevice, getChatBaseUrl, getChatQueryParamApis, getChatQueryParams, getChatQueryParamsByApi, getChatSocketUrl, getFirstAndLastNameOneCharacter, getResponsiveWidth, getSocketConfig, getStoredPushToken, isEmpty, isPushSupported, mergeChatCustomization, mergeChatLayoutConfig, onForegroundPush, packageDefaultComponents, resolveApiUrl, resolveChatApiKey, resolveJumpDateBounds, resolveJumpPreset, resolveJumpStep, resolveSocketUrl, setChatAccessToken, setChatBaseURL, setChatClientId, setChatQueryParamApis, setChatQueryParams, setChatQueryParamsByApi, setChatSocketUrl, showNotification, smoothScrollToMessage, socketService, startOfLocalDay, toDateInputValue, uniqueList, useChatAlerts, useChatContext, useChatController, useChatCustomization, useChatCustomizationOptional, useChatFeatures, useChatFeaturesOptional, useChatLocale, useStore as useChatStore, useChatTheme, usePushNotifications };
package/dist/index.mjs CHANGED
@@ -17355,6 +17355,279 @@ function ChatViewport({
17355
17355
  );
17356
17356
  }
17357
17357
  var ChatViewport_default = ChatViewport;
17358
+ var showNotification = (message, type = "info", icon, duration) => {
17359
+ const options = {
17360
+ icon,
17361
+ duration
17362
+ };
17363
+ switch (type) {
17364
+ case "success":
17365
+ toast.success(message, options);
17366
+ break;
17367
+ case "error":
17368
+ toast.error(message, options);
17369
+ break;
17370
+ case "info":
17371
+ toast(message, options);
17372
+ break;
17373
+ case "warning":
17374
+ toast(message, { ...options, icon: "\u26A0\uFE0F" });
17375
+ break;
17376
+ default:
17377
+ toast(message, options);
17378
+ }
17379
+ };
17380
+ var downloadFile = async (src, name) => {
17381
+ try {
17382
+ const link = document.createElement("a");
17383
+ link.href = src;
17384
+ link.setAttribute("download", name);
17385
+ link.setAttribute("rel", "noopener noreferrer");
17386
+ link.click();
17387
+ showNotification("File Downloaded Successfully", "success");
17388
+ } catch (err) {
17389
+ console.error("File download failed:", err);
17390
+ showNotification("Failed to download file", "error");
17391
+ }
17392
+ };
17393
+ var getResponsiveWidth = (width) => {
17394
+ const screenWidth = window.innerWidth;
17395
+ if (width) {
17396
+ return width;
17397
+ } else if (screenWidth < 640) {
17398
+ return 350;
17399
+ } else if (screenWidth >= 640 && screenWidth < 1024) {
17400
+ return 600;
17401
+ } else if (screenWidth >= 1024 && screenWidth < 1280) {
17402
+ return 800;
17403
+ } else {
17404
+ return 1e3;
17405
+ }
17406
+ };
17407
+ var isEmpty = (value) => {
17408
+ if (value === null || value === void 0) return true;
17409
+ if (typeof value === "string") return value.trim().length === 0;
17410
+ if (Array.isArray(value)) {
17411
+ return value.length === 0 || value.every((item) => isEmpty(item));
17412
+ }
17413
+ if (typeof value === "object") {
17414
+ return Object.keys(value).length === 0;
17415
+ }
17416
+ return false;
17417
+ };
17418
+ function uniqueList(list, key) {
17419
+ const seen = /* @__PURE__ */ new Set();
17420
+ return list.filter((item) => {
17421
+ const value = item[key];
17422
+ if (seen.has(value)) return false;
17423
+ seen.add(value);
17424
+ return true;
17425
+ });
17426
+ }
17427
+ var capitalizeFirst = (str) => str.charAt(0).toUpperCase() + str.slice(1);
17428
+ var getFirstAndLastNameOneCharacter = (name) => {
17429
+ const names = name.split(" ");
17430
+ return names.map((name2) => name2.charAt(0).toUpperCase()).join("");
17431
+ };
17432
+
17433
+ // src/notifications/ForegroundPushBridge.tsx
17434
+ init_useStore();
17435
+
17436
+ // src/notifications/push.service.ts
17437
+ init_client();
17438
+ var PUSH_TOKEN_STORAGE_KEY = "realtimex-push-token";
17439
+ var SERVICE_WORKER_PATH = "/firebase-messaging-sw.js";
17440
+ var PUSH_CHANGED_EVENT = "realtimex:push-changed";
17441
+ var emitPushChanged = (enabled) => {
17442
+ try {
17443
+ window.dispatchEvent(
17444
+ new CustomEvent(PUSH_CHANGED_EVENT, { detail: { enabled } })
17445
+ );
17446
+ } catch {
17447
+ }
17448
+ };
17449
+ var v2Url = "https://realtimex.softwareco.com/api/v2";
17450
+ var apiGetPushConfig = async () => {
17451
+ const { data } = await apiClient.get(`${v2Url}/notifications/push/config`);
17452
+ return data?.data;
17453
+ };
17454
+ var apiRegisterPushToken = async (token, deviceLabel) => {
17455
+ const { data } = await apiClient.post(`${v2Url}/notifications/push/token`, {
17456
+ token,
17457
+ deviceLabel
17458
+ });
17459
+ return data?.data;
17460
+ };
17461
+ var apiRemovePushToken = async (token) => {
17462
+ const { data } = await apiClient.delete(`${v2Url}/notifications/push/token`, {
17463
+ data: { token }
17464
+ });
17465
+ return data;
17466
+ };
17467
+ var apiGetPushPreference = async () => {
17468
+ const { data } = await apiClient.get(
17469
+ `${v2Url}/notifications/push/preference`
17470
+ );
17471
+ return data?.data;
17472
+ };
17473
+ var apiUpdatePushPreference = async (enabled) => {
17474
+ const { data } = await apiClient.patch(
17475
+ `${v2Url}/notifications/push/preference`,
17476
+ { enabled }
17477
+ );
17478
+ return data?.data;
17479
+ };
17480
+ var isPushSupported = () => typeof window !== "undefined" && "Notification" in window && "serviceWorker" in navigator && "PushManager" in window;
17481
+ var getStoredPushToken = () => {
17482
+ try {
17483
+ return localStorage.getItem(PUSH_TOKEN_STORAGE_KEY);
17484
+ } catch {
17485
+ return null;
17486
+ }
17487
+ };
17488
+ var storePushToken = (token) => {
17489
+ try {
17490
+ if (token) localStorage.setItem(PUSH_TOKEN_STORAGE_KEY, token);
17491
+ else localStorage.removeItem(PUSH_TOKEN_STORAGE_KEY);
17492
+ } catch {
17493
+ }
17494
+ };
17495
+ var defaultDeviceLabel = () => {
17496
+ const ua = navigator.userAgent;
17497
+ const browser = /edg\//i.test(ua) ? "Edge" : /chrome/i.test(ua) ? "Chrome" : /safari/i.test(ua) ? "Safari" : /firefox/i.test(ua) ? "Firefox" : "Browser";
17498
+ const os = /mac/i.test(ua) ? "macOS" : /windows/i.test(ua) ? "Windows" : /android/i.test(ua) ? "Android" : /iphone|ipad/i.test(ua) ? "iOS" : /linux/i.test(ua) ? "Linux" : "Unknown OS";
17499
+ return `${browser} on ${os}`;
17500
+ };
17501
+ var loadFirebaseMessaging = async () => {
17502
+ try {
17503
+ const [{ initializeApp, getApps }, messagingModule] = await Promise.all([
17504
+ import('firebase/app'),
17505
+ import('firebase/messaging')
17506
+ ]);
17507
+ return { initializeApp, getApps, ...messagingModule };
17508
+ } catch {
17509
+ throw new Error(
17510
+ 'Push notifications need the "firebase" package \u2014 run: npm install firebase'
17511
+ );
17512
+ }
17513
+ };
17514
+ var getFirebaseMessaging = async (firebaseConfig) => {
17515
+ const fb = await loadFirebaseMessaging();
17516
+ const app = fb.getApps().length ? fb.getApps()[0] : fb.initializeApp(firebaseConfig);
17517
+ return { fb, messaging: fb.getMessaging(app) };
17518
+ };
17519
+ var enablePushOnThisDevice = async () => {
17520
+ if (!isPushSupported()) {
17521
+ throw new Error("Push notifications are not supported in this browser");
17522
+ }
17523
+ const config = await apiGetPushConfig();
17524
+ if (!config?.enabled) {
17525
+ throw new Error("Push notifications are disabled for this workspace");
17526
+ }
17527
+ if (!config.configured || !config.firebaseConfig || !config.vapidKey) {
17528
+ throw new Error(
17529
+ "Push notifications are not configured on the server yet"
17530
+ );
17531
+ }
17532
+ const permission = await Notification.requestPermission();
17533
+ if (permission !== "granted") {
17534
+ throw new Error("Notification permission was not granted");
17535
+ }
17536
+ let registration;
17537
+ try {
17538
+ registration = await navigator.serviceWorker.register(
17539
+ `${SERVICE_WORKER_PATH}?config=${encodeURIComponent(
17540
+ JSON.stringify(config.firebaseConfig)
17541
+ )}`
17542
+ );
17543
+ } catch {
17544
+ throw new Error(
17545
+ `Could not register ${SERVICE_WORKER_PATH} \u2014 copy it from node_modules/@realtimexsco/live-chat/dist/firebase-messaging-sw.js into your app's public folder`
17546
+ );
17547
+ }
17548
+ const { fb, messaging } = await getFirebaseMessaging(config.firebaseConfig);
17549
+ const token = await fb.getToken(messaging, {
17550
+ vapidKey: config.vapidKey,
17551
+ serviceWorkerRegistration: registration
17552
+ });
17553
+ if (!token) {
17554
+ throw new Error("Could not obtain a push token from Firebase");
17555
+ }
17556
+ await apiRegisterPushToken(token, defaultDeviceLabel());
17557
+ storePushToken(token);
17558
+ emitPushChanged(true);
17559
+ return token;
17560
+ };
17561
+ var disablePushOnThisDevice = async () => {
17562
+ const token = getStoredPushToken();
17563
+ if (!token) return;
17564
+ try {
17565
+ const config = await apiGetPushConfig();
17566
+ if (config?.firebaseConfig) {
17567
+ const { fb, messaging } = await getFirebaseMessaging(
17568
+ config.firebaseConfig
17569
+ );
17570
+ await fb.deleteToken(messaging).catch(() => void 0);
17571
+ }
17572
+ } catch {
17573
+ }
17574
+ await apiRemovePushToken(token).catch(() => void 0);
17575
+ storePushToken(null);
17576
+ emitPushChanged(false);
17577
+ };
17578
+ var onForegroundPush = async (callback) => {
17579
+ const config = await apiGetPushConfig();
17580
+ if (!config?.configured || !config.firebaseConfig) return () => void 0;
17581
+ const { fb, messaging } = await getFirebaseMessaging(config.firebaseConfig);
17582
+ return fb.onMessage(messaging, (payload) => {
17583
+ callback({
17584
+ title: payload?.notification?.title,
17585
+ body: payload?.notification?.body,
17586
+ data: payload?.data
17587
+ });
17588
+ });
17589
+ };
17590
+
17591
+ // src/notifications/ForegroundPushBridge.tsx
17592
+ var ForegroundPushBridge = ({ onPush }) => {
17593
+ useEffect(() => {
17594
+ let unsubscribe = null;
17595
+ let cancelled = false;
17596
+ const handlePayload = (payload) => {
17597
+ const incoming = payload.data?.conversationId;
17598
+ const activeId = useStore.getState().activeConversationId;
17599
+ if (incoming && activeId && incoming === activeId) return;
17600
+ if (onPush && onPush(payload) !== false) return;
17601
+ const text = payload.title ? payload.body ? `${payload.title}: ${payload.body}` : payload.title : payload.body;
17602
+ if (text) showNotification(text, "info");
17603
+ };
17604
+ const start = async () => {
17605
+ if (cancelled || unsubscribe || !getStoredPushToken()) return;
17606
+ try {
17607
+ const stop = await onForegroundPush(handlePayload);
17608
+ if (cancelled) stop();
17609
+ else unsubscribe = stop;
17610
+ } catch {
17611
+ }
17612
+ };
17613
+ void start();
17614
+ const onPushChanged = (event) => {
17615
+ const enabled = event.detail?.enabled;
17616
+ if (enabled) void start();
17617
+ else {
17618
+ unsubscribe?.();
17619
+ unsubscribe = null;
17620
+ }
17621
+ };
17622
+ window.addEventListener(PUSH_CHANGED_EVENT, onPushChanged);
17623
+ return () => {
17624
+ cancelled = true;
17625
+ unsubscribe?.();
17626
+ window.removeEventListener(PUSH_CHANGED_EVENT, onPushChanged);
17627
+ };
17628
+ }, [onPush]);
17629
+ return null;
17630
+ };
17358
17631
  var ChatMain = ({
17359
17632
  clientId,
17360
17633
  loggedUserDetails,
@@ -17419,7 +17692,7 @@ var ChatMain = ({
17419
17692
  defaultHour12,
17420
17693
  onDateTimePreferencesChange,
17421
17694
  showDateTimeSettings,
17422
- children: /* @__PURE__ */ jsx(
17695
+ children: /* @__PURE__ */ jsxs(
17423
17696
  Chat,
17424
17697
  {
17425
17698
  client: clientObj,
@@ -17433,25 +17706,28 @@ var ChatMain = ({
17433
17706
  queryParams,
17434
17707
  queryParamApis,
17435
17708
  queryParamsByApi,
17436
- children: /* @__PURE__ */ jsx(
17437
- ChatAlertsProvider,
17438
- {
17439
- value: {
17440
- error,
17441
- info,
17442
- onDismissError: onErrorDismiss,
17443
- onDismissInfo: onInfoDismiss
17444
- },
17445
- children: /* @__PURE__ */ jsx(
17446
- ChatLayout_default,
17447
- {
17448
- layout,
17449
- loggedUserDetails,
17450
- themeColor
17451
- }
17452
- )
17453
- }
17454
- )
17709
+ children: [
17710
+ /* @__PURE__ */ jsx(ForegroundPushBridge, {}),
17711
+ /* @__PURE__ */ jsx(
17712
+ ChatAlertsProvider,
17713
+ {
17714
+ value: {
17715
+ error,
17716
+ info,
17717
+ onDismissError: onErrorDismiss,
17718
+ onDismissInfo: onInfoDismiss
17719
+ },
17720
+ children: /* @__PURE__ */ jsx(
17721
+ ChatLayout_default,
17722
+ {
17723
+ layout,
17724
+ loggedUserDetails,
17725
+ themeColor
17726
+ }
17727
+ )
17728
+ }
17729
+ )
17730
+ ]
17455
17731
  }
17456
17732
  )
17457
17733
  }
@@ -17505,80 +17781,6 @@ var getSocketConfig = (accessToken, tenantId, options) => {
17505
17781
  }
17506
17782
  };
17507
17783
  };
17508
- var showNotification = (message, type = "info", icon, duration) => {
17509
- const options = {
17510
- icon,
17511
- duration
17512
- };
17513
- switch (type) {
17514
- case "success":
17515
- toast.success(message, options);
17516
- break;
17517
- case "error":
17518
- toast.error(message, options);
17519
- break;
17520
- case "info":
17521
- toast(message, options);
17522
- break;
17523
- case "warning":
17524
- toast(message, { ...options, icon: "\u26A0\uFE0F" });
17525
- break;
17526
- default:
17527
- toast(message, options);
17528
- }
17529
- };
17530
- var downloadFile = async (src, name) => {
17531
- try {
17532
- const link = document.createElement("a");
17533
- link.href = src;
17534
- link.setAttribute("download", name);
17535
- link.setAttribute("rel", "noopener noreferrer");
17536
- link.click();
17537
- showNotification("File Downloaded Successfully", "success");
17538
- } catch (err) {
17539
- console.error("File download failed:", err);
17540
- showNotification("Failed to download file", "error");
17541
- }
17542
- };
17543
- var getResponsiveWidth = (width) => {
17544
- const screenWidth = window.innerWidth;
17545
- if (width) {
17546
- return width;
17547
- } else if (screenWidth < 640) {
17548
- return 350;
17549
- } else if (screenWidth >= 640 && screenWidth < 1024) {
17550
- return 600;
17551
- } else if (screenWidth >= 1024 && screenWidth < 1280) {
17552
- return 800;
17553
- } else {
17554
- return 1e3;
17555
- }
17556
- };
17557
- var isEmpty = (value) => {
17558
- if (value === null || value === void 0) return true;
17559
- if (typeof value === "string") return value.trim().length === 0;
17560
- if (Array.isArray(value)) {
17561
- return value.length === 0 || value.every((item) => isEmpty(item));
17562
- }
17563
- if (typeof value === "object") {
17564
- return Object.keys(value).length === 0;
17565
- }
17566
- return false;
17567
- };
17568
- function uniqueList(list, key) {
17569
- const seen = /* @__PURE__ */ new Set();
17570
- return list.filter((item) => {
17571
- const value = item[key];
17572
- if (seen.has(value)) return false;
17573
- seen.add(value);
17574
- return true;
17575
- });
17576
- }
17577
- var capitalizeFirst = (str) => str.charAt(0).toUpperCase() + str.slice(1);
17578
- var getFirstAndLastNameOneCharacter = (name) => {
17579
- const names = name.split(" ");
17580
- return names.map((name2) => name2.charAt(0).toUpperCase()).join("");
17581
- };
17582
17784
  var SIZE_MAP = {
17583
17785
  xs: "size-6",
17584
17786
  sm: "size-8",
@@ -17752,150 +17954,6 @@ var packageDefaultComponents = {
17752
17954
  ChatDateTimeSettings: ChatDateTimeSettings_default,
17753
17955
  ChatSocketStatus: ChatSocketStatus_default
17754
17956
  };
17755
-
17756
- // src/notifications/push.service.ts
17757
- init_client();
17758
- var PUSH_TOKEN_STORAGE_KEY = "realtimex-push-token";
17759
- var SERVICE_WORKER_PATH = "/firebase-messaging-sw.js";
17760
- var v2Url = "https://realtimex.softwareco.com/api/v2";
17761
- var apiGetPushConfig = async () => {
17762
- const { data } = await apiClient.get(`${v2Url}/notifications/push/config`);
17763
- return data?.data;
17764
- };
17765
- var apiRegisterPushToken = async (token, deviceLabel) => {
17766
- const { data } = await apiClient.post(`${v2Url}/notifications/push/token`, {
17767
- token,
17768
- deviceLabel
17769
- });
17770
- return data?.data;
17771
- };
17772
- var apiRemovePushToken = async (token) => {
17773
- const { data } = await apiClient.delete(`${v2Url}/notifications/push/token`, {
17774
- data: { token }
17775
- });
17776
- return data;
17777
- };
17778
- var apiGetPushPreference = async () => {
17779
- const { data } = await apiClient.get(
17780
- `${v2Url}/notifications/push/preference`
17781
- );
17782
- return data?.data;
17783
- };
17784
- var apiUpdatePushPreference = async (enabled) => {
17785
- const { data } = await apiClient.patch(
17786
- `${v2Url}/notifications/push/preference`,
17787
- { enabled }
17788
- );
17789
- return data?.data;
17790
- };
17791
- var isPushSupported = () => typeof window !== "undefined" && "Notification" in window && "serviceWorker" in navigator && "PushManager" in window;
17792
- var getStoredPushToken = () => {
17793
- try {
17794
- return localStorage.getItem(PUSH_TOKEN_STORAGE_KEY);
17795
- } catch {
17796
- return null;
17797
- }
17798
- };
17799
- var storePushToken = (token) => {
17800
- try {
17801
- if (token) localStorage.setItem(PUSH_TOKEN_STORAGE_KEY, token);
17802
- else localStorage.removeItem(PUSH_TOKEN_STORAGE_KEY);
17803
- } catch {
17804
- }
17805
- };
17806
- var defaultDeviceLabel = () => {
17807
- const ua = navigator.userAgent;
17808
- const browser = /edg\//i.test(ua) ? "Edge" : /chrome/i.test(ua) ? "Chrome" : /safari/i.test(ua) ? "Safari" : /firefox/i.test(ua) ? "Firefox" : "Browser";
17809
- const os = /mac/i.test(ua) ? "macOS" : /windows/i.test(ua) ? "Windows" : /android/i.test(ua) ? "Android" : /iphone|ipad/i.test(ua) ? "iOS" : /linux/i.test(ua) ? "Linux" : "Unknown OS";
17810
- return `${browser} on ${os}`;
17811
- };
17812
- var loadFirebaseMessaging = async () => {
17813
- try {
17814
- const [{ initializeApp, getApps }, messagingModule] = await Promise.all([
17815
- import('firebase/app'),
17816
- import('firebase/messaging')
17817
- ]);
17818
- return { initializeApp, getApps, ...messagingModule };
17819
- } catch {
17820
- throw new Error(
17821
- 'Push notifications need the "firebase" package \u2014 run: npm install firebase'
17822
- );
17823
- }
17824
- };
17825
- var getFirebaseMessaging = async (firebaseConfig) => {
17826
- const fb = await loadFirebaseMessaging();
17827
- const app = fb.getApps().length ? fb.getApps()[0] : fb.initializeApp(firebaseConfig);
17828
- return { fb, messaging: fb.getMessaging(app) };
17829
- };
17830
- var enablePushOnThisDevice = async () => {
17831
- if (!isPushSupported()) {
17832
- throw new Error("Push notifications are not supported in this browser");
17833
- }
17834
- const config = await apiGetPushConfig();
17835
- if (!config?.enabled) {
17836
- throw new Error("Push notifications are disabled for this workspace");
17837
- }
17838
- if (!config.configured || !config.firebaseConfig || !config.vapidKey) {
17839
- throw new Error(
17840
- "Push notifications are not configured on the server yet"
17841
- );
17842
- }
17843
- const permission = await Notification.requestPermission();
17844
- if (permission !== "granted") {
17845
- throw new Error("Notification permission was not granted");
17846
- }
17847
- let registration;
17848
- try {
17849
- registration = await navigator.serviceWorker.register(
17850
- `${SERVICE_WORKER_PATH}?config=${encodeURIComponent(
17851
- JSON.stringify(config.firebaseConfig)
17852
- )}`
17853
- );
17854
- } catch {
17855
- throw new Error(
17856
- `Could not register ${SERVICE_WORKER_PATH} \u2014 copy it from node_modules/@realtimexsco/live-chat/dist/firebase-messaging-sw.js into your app's public folder`
17857
- );
17858
- }
17859
- const { fb, messaging } = await getFirebaseMessaging(config.firebaseConfig);
17860
- const token = await fb.getToken(messaging, {
17861
- vapidKey: config.vapidKey,
17862
- serviceWorkerRegistration: registration
17863
- });
17864
- if (!token) {
17865
- throw new Error("Could not obtain a push token from Firebase");
17866
- }
17867
- await apiRegisterPushToken(token, defaultDeviceLabel());
17868
- storePushToken(token);
17869
- return token;
17870
- };
17871
- var disablePushOnThisDevice = async () => {
17872
- const token = getStoredPushToken();
17873
- if (!token) return;
17874
- try {
17875
- const config = await apiGetPushConfig();
17876
- if (config?.firebaseConfig) {
17877
- const { fb, messaging } = await getFirebaseMessaging(
17878
- config.firebaseConfig
17879
- );
17880
- await fb.deleteToken(messaging).catch(() => void 0);
17881
- }
17882
- } catch {
17883
- }
17884
- await apiRemovePushToken(token).catch(() => void 0);
17885
- storePushToken(null);
17886
- };
17887
- var onForegroundPush = async (callback) => {
17888
- const config = await apiGetPushConfig();
17889
- if (!config?.configured || !config.firebaseConfig) return () => void 0;
17890
- const { fb, messaging } = await getFirebaseMessaging(config.firebaseConfig);
17891
- return fb.onMessage(messaging, (payload) => {
17892
- callback({
17893
- title: payload?.notification?.title,
17894
- body: payload?.notification?.body,
17895
- data: payload?.data
17896
- });
17897
- });
17898
- };
17899
17957
  var usePushNotifications = () => {
17900
17958
  const [state, setState] = useState({
17901
17959
  supported: false,
@@ -18029,6 +18087,6 @@ var PushNotificationToggle = ({
18029
18087
  // src/index.ts
18030
18088
  var index_default = ChatMain_default;
18031
18089
 
18032
- export { CHAT_API_KEYS, CHAT_GET_API_KEYS, Calendar, CalendarDayButton, Channel, ChannelHeaderView_default as ChannelHeader, ChannelListView_default as ChannelList, ChannelListItem_default as ChannelListItem, Chat, ChatAlertsProvider, ChatAvatar_default as ChatAvatar, ChatCustomizationProvider, ChatDateJumpMenu, ChatLayout_default as ChatLayout, ChatLocaleProvider, ChatMain_default as ChatMain, ChatThemeProvider, ChatViewport, DefaultChannelListItem, DefaultChatAvatar, DefaultChatLayout_default as DefaultChatLayout, ForwardModalView as ForwardModal, HeaderCallActions_default as HeaderCallActions, LoggedUserDetails_default as LoggedUserDetails, ChannelMessageBoxView_default as MessageInput, MessageItemView as MessageItem, ActiveChannelMessagesView_default as MessageList, PushNotificationToggle, apiGetPushConfig, apiGetPushPreference, apiRegisterPushToken, apiRemovePushToken, apiUpdatePushPreference, capitalizeFirst, clampJumpDate, index_default as default, defaultChatClassNames, defaultChatComponents, defaultChatFeatures, defaultChatLayoutConfig, disablePushOnThisDevice, downloadFile, enablePushOnThisDevice, getChatBaseUrl, getChatQueryParamApis, getChatQueryParams, getChatQueryParamsByApi, getChatSocketUrl, getFirstAndLastNameOneCharacter, getResponsiveWidth, getSocketConfig, getStoredPushToken, isEmpty, isPushSupported, mergeChatCustomization, mergeChatLayoutConfig, onForegroundPush, packageDefaultComponents, resolveApiUrl, resolveChatApiKey, resolveJumpDateBounds, resolveJumpPreset, resolveJumpStep, resolveSocketUrl, setChatAccessToken, setChatBaseURL, setChatClientId, setChatQueryParamApis, setChatQueryParams, setChatQueryParamsByApi, setChatSocketUrl, showNotification, smoothScrollToMessage, socket_service_default as socketService, startOfLocalDay, toDateInputValue, uniqueList, useChatAlerts, useChatContext, useChatController, useChatCustomization, useChatCustomizationOptional, useChatFeatures, useChatFeaturesOptional, useChatLocale, useStore as useChatStore, useChatTheme, usePushNotifications };
18090
+ export { CHAT_API_KEYS, CHAT_GET_API_KEYS, Calendar, CalendarDayButton, Channel, ChannelHeaderView_default as ChannelHeader, ChannelListView_default as ChannelList, ChannelListItem_default as ChannelListItem, Chat, ChatAlertsProvider, ChatAvatar_default as ChatAvatar, ChatCustomizationProvider, ChatDateJumpMenu, ChatLayout_default as ChatLayout, ChatLocaleProvider, ChatMain_default as ChatMain, ChatThemeProvider, ChatViewport, DefaultChannelListItem, DefaultChatAvatar, DefaultChatLayout_default as DefaultChatLayout, ForegroundPushBridge, ForwardModalView as ForwardModal, HeaderCallActions_default as HeaderCallActions, LoggedUserDetails_default as LoggedUserDetails, ChannelMessageBoxView_default as MessageInput, MessageItemView as MessageItem, ActiveChannelMessagesView_default as MessageList, PUSH_CHANGED_EVENT, PushNotificationToggle, apiGetPushConfig, apiGetPushPreference, apiRegisterPushToken, apiRemovePushToken, apiUpdatePushPreference, capitalizeFirst, clampJumpDate, index_default as default, defaultChatClassNames, defaultChatComponents, defaultChatFeatures, defaultChatLayoutConfig, disablePushOnThisDevice, downloadFile, enablePushOnThisDevice, getChatBaseUrl, getChatQueryParamApis, getChatQueryParams, getChatQueryParamsByApi, getChatSocketUrl, getFirstAndLastNameOneCharacter, getResponsiveWidth, getSocketConfig, getStoredPushToken, isEmpty, isPushSupported, mergeChatCustomization, mergeChatLayoutConfig, onForegroundPush, packageDefaultComponents, resolveApiUrl, resolveChatApiKey, resolveJumpDateBounds, resolveJumpPreset, resolveJumpStep, resolveSocketUrl, setChatAccessToken, setChatBaseURL, setChatClientId, setChatQueryParamApis, setChatQueryParams, setChatQueryParamsByApi, setChatSocketUrl, showNotification, smoothScrollToMessage, socket_service_default as socketService, startOfLocalDay, toDateInputValue, uniqueList, useChatAlerts, useChatContext, useChatController, useChatCustomization, useChatCustomizationOptional, useChatFeatures, useChatFeaturesOptional, useChatLocale, useStore as useChatStore, useChatTheme, usePushNotifications };
18033
18091
  //# sourceMappingURL=index.mjs.map
18034
18092
  //# sourceMappingURL=index.mjs.map