@dashx/react 0.3.0 → 0.3.2

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.
Files changed (43) hide show
  1. package/dist/cjs/hooks/index.d.ts +2 -0
  2. package/dist/cjs/hooks/index.js +1 -1
  3. package/dist/cjs/hooks/index.js.map +3 -3
  4. package/dist/cjs/hooks/use-in-app-chat-notifications.d.ts +27 -0
  5. package/dist/cjs/hooks/use-in-app-chat-notifications.js +2 -0
  6. package/dist/cjs/hooks/use-in-app-chat-notifications.js.map +7 -0
  7. package/dist/cjs/hooks/use-in-app-chat.d.ts +4 -1
  8. package/dist/cjs/hooks/use-in-app-chat.js +1 -1
  9. package/dist/cjs/hooks/use-in-app-chat.js.map +3 -3
  10. package/dist/cjs/widgets/InAppChat.d.ts +5 -2
  11. package/dist/cjs/widgets/InAppChat.js +1 -1
  12. package/dist/cjs/widgets/InAppChat.js.map +3 -3
  13. package/dist/cjs/widgets/InAppChatButton.d.ts +1 -1
  14. package/dist/cjs/widgets/InAppChatButton.js +1 -1
  15. package/dist/cjs/widgets/InAppChatButton.js.map +3 -3
  16. package/dist/cjs/widgets/NotificationBell.d.ts +2 -0
  17. package/dist/cjs/widgets/NotificationBell.js +2 -0
  18. package/dist/cjs/widgets/NotificationBell.js.map +7 -0
  19. package/dist/esm/hooks/index.d.ts +2 -0
  20. package/dist/esm/hooks/index.js +1 -1
  21. package/dist/esm/hooks/index.js.map +2 -2
  22. package/dist/esm/hooks/use-in-app-chat-notifications.d.ts +27 -0
  23. package/dist/esm/hooks/use-in-app-chat-notifications.js +2 -0
  24. package/dist/esm/hooks/use-in-app-chat-notifications.js.map +7 -0
  25. package/dist/esm/hooks/use-in-app-chat.d.ts +4 -1
  26. package/dist/esm/hooks/use-in-app-chat.js +1 -1
  27. package/dist/esm/hooks/use-in-app-chat.js.map +3 -3
  28. package/dist/esm/widgets/InAppChat.d.ts +5 -2
  29. package/dist/esm/widgets/InAppChat.js +1 -1
  30. package/dist/esm/widgets/InAppChat.js.map +3 -3
  31. package/dist/esm/widgets/InAppChatButton.d.ts +1 -1
  32. package/dist/esm/widgets/InAppChatButton.js +1 -1
  33. package/dist/esm/widgets/InAppChatButton.js.map +3 -3
  34. package/dist/esm/widgets/NotificationBell.d.ts +2 -0
  35. package/dist/esm/widgets/NotificationBell.js +2 -0
  36. package/dist/esm/widgets/NotificationBell.js.map +7 -0
  37. package/package.json +2 -2
  38. package/src/hooks/index.ts +2 -0
  39. package/src/hooks/use-in-app-chat-notifications.ts +117 -0
  40. package/src/hooks/use-in-app-chat.ts +31 -4
  41. package/src/widgets/InAppChat.tsx +33 -5
  42. package/src/widgets/InAppChatButton.tsx +72 -28
  43. package/styles.css +12 -0
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/hooks/use-in-app-chat.ts"],
4
- "sourcesContent": ["import uuid from 'uuid-random';\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport type { InAppChatMessageData } from '@dashx/browser';\n\nimport useDashXProvider from './use-dashx-provider.js';\nimport { useWebSocket } from '../providers/DashXProvider.js';\n\ntype UseInAppChatHookProps = {\n // The workspace's chat-identity id (the receiving surface), created when the\n // chat integration is installed; pasted into config alongside the public key.\n identityId: string;\n // Caller-supplied conversation key; the server uses it so repeat opens with\n // the same key resolve to the same conversation thread.\n idempotencyKey: string;\n // Optional automated first message sent when the conversation is first\n // created (e.g. \"Help with order #123\"). Sent via `startInAppChatConversation`\n // with a stable client message id, so it lands exactly once across reopens.\n initialMessage?: string;\n};\n\n// UI-level message. `aiRole` distinguishes the visitor from agent/AI replies and\n// drives alignment; it arrives lowercase ('user'/'assistant'), so the widget\n// compares it case-insensitively (see `isOutgoing`).\ntype InAppChatMessage = {\n id: string;\n externalUid: string | null;\n renderedContent: any;\n aiRole: string | null;\n createdAt: string;\n turnSeq?: number;\n isPending?: boolean;\n};\n\ntype UseInAppChatHookResponse = {\n conversationId: string | null;\n messages: InAppChatMessage[];\n isLoading: boolean;\n isConnected: boolean;\n error: string | null;\n // Returns `true` if the message was optimistically queued, `false` if the chat\n // wasn't ready (no conversation yet). Synchronous so the caller can clear the\n // composer immediately on `true`; callers keep the input populated on `false`.\n sendMessage: (text: string) => boolean;\n};\n\nconst CHAT_CHANNEL_PREFIX = 'in_app_chat:conversation:';\n\nconst toUiMessage = (message: InAppChatMessageData): InAppChatMessage => ({\n id: message.id,\n // `externalUid` / `aiRole` are nullable in the schema, so the SDK types them as\n // optional; normalize the absent case to null for the UI message shape.\n externalUid: message.externalUid ?? null,\n renderedContent: message.renderedContent,\n aiRole: message.aiRole ?? null,\n createdAt: message.createdAt,\n turnSeq: message.turnSeq,\n});\n\n// Dedup by externalUid (server message replaces the optimistic pending one)\n// then id; order by createdAt as the authoritative key. `turnSeq` isn't in the\n// fetched message fields, so it's absent from history (which already arrives\n// ordered, preserved by the stable sort); it only breaks same-createdAt ties\n// among realtime WS events, which carry it.\nconst mergeMessages = (\n existing: InAppChatMessage[],\n incoming: InAppChatMessage[],\n): InAppChatMessage[] => {\n const byKey = new Map<string, InAppChatMessage>();\n const keyOf = (message: InAppChatMessage) => message.externalUid || message.id;\n\n [...existing, ...incoming].forEach((message) => {\n const existingForKey = byKey.get(keyOf(message));\n if (!existingForKey || existingForKey.isPending) {\n byKey.set(keyOf(message), message);\n }\n });\n\n return [...byKey.values()].sort((a, b) => {\n if (a.createdAt !== b.createdAt) return a.createdAt < b.createdAt ? -1 : 1;\n return (a.turnSeq ?? 0) - (b.turnSeq ?? 0);\n });\n};\n\n/**\n * Two-way InApp Chat for a visitor.\n *\n * PREREQUISITE: the surrounding `<DashXProvider>` must already have a valid\n * `identityToken` (and matching `identityUid`). The chat mutations require\n * identity-token auth \u2014 if the chat starts before an identity is resolved, they\n * are rejected and the hook surfaces an auth error. It does NOT auto-retry when\n * a token arrives later (its inputs are `identityId`/`idempotencyKey`, not the\n * visitor token), so only render the chat once `identityToken` is available \u2014\n * e.g. `{identityToken && <InAppChat \u2026 />}`. `<InAppChatButton>` largely sidesteps\n * this by starting lazily when the visitor opens it, by which point the provider\n * has applied the token.\n */\nconst useInAppChat = ({ identityId, idempotencyKey, initialMessage }: UseInAppChatHookProps): UseInAppChatHookResponse => {\n const dashX = useDashXProvider();\n const { isConnected, initializeWebSocket } = useWebSocket();\n\n const [conversationId, setConversationId] = useState<string | null>(null);\n const [messages, setMessages] = useState<InAppChatMessage[]>([]);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<string | null>(null);\n\n // Bumped on every identity/key change and on unmount so stale start/fetch/send\n // resolutions are ignored (the classic React async race).\n const generationRef = useRef(0);\n const conversationIdRef = useRef<string | null>(null);\n\n const appendMessages = useCallback((incoming: InAppChatMessage[]) => {\n setMessages((prev) => mergeMessages(prev, incoming));\n }, []);\n\n useEffect(() => {\n const generation = (generationRef.current += 1);\n const isStale = () => generation !== generationRef.current;\n\n setConversationId(null);\n setMessages([]);\n setIsLoading(true);\n setError(null);\n conversationIdRef.current = null;\n\n // Ensure the WS exists (idempotent \u2014 returns early if already created).\n initializeWebSocket();\n\n let unsubscribe: (() => void) | undefined;\n\n (async () => {\n try {\n const conversation = await dashX.startInAppChatConversation({\n identityId,\n clientIdempotencyKey: idempotencyKey,\n // Stable client message id \u2192 the automated message is inserted once,\n // even if the conversation is reopened (the server dedups repeat sends).\n // `-` separator (client ids allow only `[A-Za-z0-9._-]`); the key is\n // truncated so the suffixed id stays within the 1-128 char limit.\n ...(initialMessage\n ? { content: { text: initialMessage }, clientMessageId: `${idempotencyKey.slice(0, 122)}-intro` }\n : {}),\n });\n if (isStale()) return;\n\n const convId = conversation.id;\n setConversationId(convId);\n conversationIdRef.current = convId;\n\n const refetchHistory = async () => {\n const history = await dashX.fetchInAppChatMessages({ conversationId: convId });\n if (isStale()) return;\n appendMessages(history.map(toUiMessage));\n };\n\n // Subscribe BEFORE fetching history so a reply landing in the gap is\n // buffered, not dropped. `onReconnectAck` fires on reconnect re-acks and\n // on a first ack that arrives after a `ready` timeout \u2014 both mean we are\n // (now) subscribed, so clear any connection error and (re)load history.\n const subscription = dashX.subscribeToChannel(\n `${CHAT_CHANNEL_PREFIX}${convId}`,\n (event) => {\n if (!isStale()) appendMessages([toUiMessage(event)]);\n },\n {\n onReconnectAck: () => {\n if (isStale()) return;\n setError(null);\n refetchHistory().catch(() => {});\n },\n },\n );\n unsubscribe = subscription.unsubscribe;\n\n // Load history only once the subscription is acked \u2014 fetching before\n // that would show history while silently never receiving realtime\n // replies. On ack failure, surface an error and defer the fetch to\n // `onReconnectAck` (fires if/when the channel finally acks).\n try {\n await subscription.ready;\n } catch {\n if (!isStale()) setError('Couldn\u2019t connect to live chat. Retrying\u2026');\n return;\n }\n if (isStale()) return;\n await refetchHistory();\n } catch {\n if (!isStale()) setError('Failed to start chat');\n } finally {\n if (!isStale()) setIsLoading(false);\n }\n })();\n\n return () => {\n // Invalidate in-flight async and drop the old channel before the next\n // conversation binds.\n generationRef.current += 1;\n unsubscribe?.();\n };\n }, [dashX, identityId, idempotencyKey, initialMessage, initializeWebSocket, appendMessages]);\n\n // Synchronous on purpose: it returns `true` the moment the message is optimistically\n // queued and runs the network send in the background. The caller clears the composer\n // on `true` immediately \u2014 if it instead awaited the round-trip, a fast second Enter\n // would re-send the still-present text as a new message (fresh clientMessageId, so the\n // backend won't dedupe it) and create a duplicate.\n const sendMessage = useCallback(\n (text: string): boolean => {\n const convId = conversationIdRef.current;\n // Not ready (conversation still starting, or start failed) \u2014 report back so\n // the caller can keep the typed text instead of clearing it on a no-op send.\n if (!text.trim() || !convId) return false;\n\n // Pin the generation so a response that resolves after the identity/key\n // changed (or unmount) can't contaminate the new conversation's state.\n const generation = generationRef.current;\n const clientMessageId = uuid();\n const optimistic: InAppChatMessage = {\n id: clientMessageId,\n externalUid: `in_app_chat:${clientMessageId}`,\n renderedContent: { text },\n aiRole: 'USER',\n createdAt: new Date().toISOString(),\n isPending: true,\n };\n appendMessages([optimistic]);\n\n void (async () => {\n try {\n const serverMessage = await dashX.sendInAppChatMessage({\n conversationId: convId,\n identityId,\n content: { text },\n clientMessageId,\n });\n if (generation !== generationRef.current) return;\n // Reconcile by externalUid (the WS echo reconciles too \u2014 both idempotent).\n appendMessages([toUiMessage(serverMessage)]);\n } catch {\n if (generation === generationRef.current) setError('Failed to send message');\n }\n })();\n\n // Queued (optimistically appended) \u2014 the background send reconciles/errors later.\n return true;\n },\n [dashX, identityId, appendMessages],\n );\n\n return { conversationId, messages, isLoading, isConnected, error, sendMessage };\n};\n\nexport type { UseInAppChatHookProps, UseInAppChatHookResponse, InAppChatMessage };\n\nexport default useInAppChat;\n"],
5
- "mappings": "AAAA,OAAOA,MAAU,cACjB,OAAS,eAAAC,EAAa,aAAAC,EAAW,UAAAC,EAAQ,YAAAC,MAAgB,QAGzD,OAAOC,MAAsB,0BAC7B,OAAS,gBAAAC,MAAoB,gCAwC7B,MAAMC,EAAsB,4BAEtBC,EAAeC,IAAqD,CACxE,GAAIA,EAAQ,GAGZ,YAAaA,EAAQ,aAAe,KACpC,gBAAiBA,EAAQ,gBACzB,OAAQA,EAAQ,QAAU,KAC1B,UAAWA,EAAQ,UACnB,QAASA,EAAQ,OACnB,GAOMC,EAAgB,CACpBC,EACAC,IACuB,CACvB,MAAMC,EAAQ,IAAI,IACZC,EAASL,GAA8BA,EAAQ,aAAeA,EAAQ,GAE5E,OAAC,GAAGE,EAAU,GAAGC,CAAQ,EAAE,QAASH,GAAY,CAC9C,MAAMM,EAAiBF,EAAM,IAAIC,EAAML,CAAO,CAAC,GAC3C,CAACM,GAAkBA,EAAe,YACpCF,EAAM,IAAIC,EAAML,CAAO,EAAGA,CAAO,CAErC,CAAC,EAEM,CAAC,GAAGI,EAAM,OAAO,CAAC,EAAE,KAAK,CAACG,EAAGC,IAC9BD,EAAE,YAAcC,EAAE,UAAkBD,EAAE,UAAYC,EAAE,UAAY,GAAK,GACjED,EAAE,SAAW,IAAMC,EAAE,SAAW,EACzC,CACH,EAeMC,EAAe,CAAC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CAC7C,MAAQ,CACFb,IAAeJ,EAAc,SAASD,EAAS,wBAAwB,CAC7E,CACF,GAAG,EAGI,EACT,EACA,CAACV,EAAOH,EAAYgB,CAAc,CACpC,EAEA,MAAO,CAAE,eAAAV,EAAgB,SAAAE,EAAU,UAAAE,EAAW,YAAAN,EAAa,MAAAQ,EAAO,YAAAe,CAAY,CAChF,EAIA,IAAOK,EAAQjC",
6
- "names": ["uuid", "useCallback", "useEffect", "useRef", "useState", "useDashXProvider", "useWebSocket", "CHAT_CHANNEL_PREFIX", "toUiMessage", "message", "mergeMessages", "existing", "incoming", "byKey", "keyOf", "existingForKey", "a", "b", "useInAppChat", "identityId", "idempotencyKey", "initialMessage", "dashX", "isConnected", "initializeWebSocket", "conversationId", "setConversationId", "messages", "setMessages", "isLoading", "setIsLoading", "error", "setError", "generationRef", "conversationIdRef", "appendMessages", "prev", "generation", "isStale", "unsubscribe", "conversation", "convId", "refetchHistory", "history", "subscription", "event", "sendMessage", "text", "clientMessageId", "optimistic", "serverMessage", "use_in_app_chat_default"]
4
+ "sourcesContent": ["import uuid from 'uuid-random';\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport type { InAppChatMessageData } from '@dashx/browser';\n\nimport useDashXProvider from './use-dashx-provider.js';\nimport { useWebSocket } from '../providers/DashXProvider.js';\n\ntype UseInAppChatHookProps = {\n // The workspace's chat-identity id (the receiving surface), created when the\n // chat integration is installed; pasted into config alongside the public key.\n identityId: string;\n // Caller-supplied conversation key; the server uses it so repeat opens with\n // the same key resolve to the same conversation thread.\n idempotencyKey: string;\n // Optional automated first message sent when the conversation is first\n // created (e.g. \"Help with order #123\"). Sent via `startInAppChatConversation`\n // with a stable client message id, so it lands exactly once across reopens.\n initialMessage?: string;\n // When false, the hook is idle: no conversation is started, subscribed, or\n // fetched. Lets `<InAppChatButton>` defer the conversation until the visitor\n // first opens the launcher, while keeping the hook mounted afterwards so its\n // subscription (and thus notifications) survive the panel being closed.\n enabled?: boolean;\n // Invoked once per LIVE inbound message (not for history load / reconnect\n // refetch). Drives browser notifications without having to diff backfilled\n // history against live events.\n onInboundMessage?: (message: InAppChatMessageData) => void;\n};\n\n// UI-level message. `aiRole` distinguishes the visitor from agent/AI replies and\n// drives alignment; it arrives lowercase ('user'/'assistant'), so the widget\n// compares it case-insensitively (see `isOutgoing`).\ntype InAppChatMessage = {\n id: string;\n externalUid: string | null;\n renderedContent: any;\n aiRole: string | null;\n createdAt: string;\n turnSeq?: number;\n isPending?: boolean;\n};\n\ntype UseInAppChatHookResponse = {\n conversationId: string | null;\n messages: InAppChatMessage[];\n isLoading: boolean;\n isConnected: boolean;\n error: string | null;\n // Returns `true` if the message was optimistically queued, `false` if the chat\n // wasn't ready (no conversation yet). Synchronous so the caller can clear the\n // composer immediately on `true`; callers keep the input populated on `false`.\n sendMessage: (text: string) => boolean;\n};\n\nconst CHAT_CHANNEL_PREFIX = 'in_app_chat:conversation:';\n\nconst toUiMessage = (message: InAppChatMessageData): InAppChatMessage => ({\n id: message.id,\n // `externalUid` / `aiRole` are nullable in the schema, so the SDK types them as\n // optional; normalize the absent case to null for the UI message shape.\n externalUid: message.externalUid ?? null,\n renderedContent: message.renderedContent,\n aiRole: message.aiRole ?? null,\n createdAt: message.createdAt,\n turnSeq: message.turnSeq,\n});\n\n// Dedup by externalUid (server message replaces the optimistic pending one)\n// then id; order by createdAt as the authoritative key. `turnSeq` isn't in the\n// fetched message fields, so it's absent from history (which already arrives\n// ordered, preserved by the stable sort); it only breaks same-createdAt ties\n// among realtime WS events, which carry it.\nconst mergeMessages = (\n existing: InAppChatMessage[],\n incoming: InAppChatMessage[],\n): InAppChatMessage[] => {\n const byKey = new Map<string, InAppChatMessage>();\n const keyOf = (message: InAppChatMessage) => message.externalUid || message.id;\n\n [...existing, ...incoming].forEach((message) => {\n const existingForKey = byKey.get(keyOf(message));\n if (!existingForKey || existingForKey.isPending) {\n byKey.set(keyOf(message), message);\n }\n });\n\n return [...byKey.values()].sort((a, b) => {\n if (a.createdAt !== b.createdAt) return a.createdAt < b.createdAt ? -1 : 1;\n return (a.turnSeq ?? 0) - (b.turnSeq ?? 0);\n });\n};\n\n/**\n * Two-way InApp Chat for a visitor.\n *\n * PREREQUISITE: the surrounding `<DashXProvider>` must already have a valid\n * `identityToken` (and matching `identityUid`). The chat mutations require\n * identity-token auth \u2014 if the chat starts before an identity is resolved, they\n * are rejected and the hook surfaces an auth error. It does NOT auto-retry when\n * a token arrives later (its inputs are `identityId`/`idempotencyKey`, not the\n * visitor token), so only render the chat once `identityToken` is available \u2014\n * e.g. `{identityToken && <InAppChat \u2026 />}`. `<InAppChatButton>` largely sidesteps\n * this by starting lazily when the visitor opens it, by which point the provider\n * has applied the token.\n */\nconst useInAppChat = ({ identityId, idempotencyKey, initialMessage, enabled = true, onInboundMessage }: UseInAppChatHookProps): UseInAppChatHookResponse => {\n const dashX = useDashXProvider();\n const { isConnected, initializeWebSocket } = useWebSocket();\n\n const [conversationId, setConversationId] = useState<string | null>(null);\n const [messages, setMessages] = useState<InAppChatMessage[]>([]);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<string | null>(null);\n\n // Bumped on every identity/key change and on unmount so stale start/fetch/send\n // resolutions are ignored (the classic React async race).\n const generationRef = useRef(0);\n const conversationIdRef = useRef<string | null>(null);\n\n // Latest live-message callback, kept in a ref so changing its identity doesn't\n // tear down and re-create the channel subscription.\n const onInboundMessageRef = useRef(onInboundMessage);\n onInboundMessageRef.current = onInboundMessage;\n\n const appendMessages = useCallback((incoming: InAppChatMessage[]) => {\n setMessages((prev) => mergeMessages(prev, incoming));\n }, []);\n\n useEffect(() => {\n const generation = (generationRef.current += 1);\n const isStale = () => generation !== generationRef.current;\n\n setConversationId(null);\n setMessages([]);\n setError(null);\n conversationIdRef.current = null;\n\n // Idle until enabled (e.g. before the launcher's first open): don't create a\n // conversation, subscribe, or fetch.\n if (!enabled) {\n setIsLoading(false);\n return () => { generationRef.current += 1; };\n }\n\n setIsLoading(true);\n\n // Ensure the WS exists (idempotent \u2014 returns early if already created).\n initializeWebSocket();\n\n let unsubscribe: (() => void) | undefined;\n\n (async () => {\n try {\n const conversation = await dashX.startInAppChatConversation({\n identityId,\n clientIdempotencyKey: idempotencyKey,\n // Stable client message id \u2192 the automated message is inserted once,\n // even if the conversation is reopened (the server dedups repeat sends).\n // `-` separator (client ids allow only `[A-Za-z0-9._-]`); the key is\n // truncated so the suffixed id stays within the 1-128 char limit.\n ...(initialMessage\n ? { content: { text: initialMessage }, clientMessageId: `${idempotencyKey.slice(0, 122)}-intro` }\n : {}),\n });\n if (isStale()) return;\n\n const convId = conversation.id;\n setConversationId(convId);\n conversationIdRef.current = convId;\n\n const refetchHistory = async () => {\n const history = await dashX.fetchInAppChatMessages({ conversationId: convId });\n if (isStale()) return;\n appendMessages(history.map(toUiMessage));\n };\n\n // Subscribe BEFORE fetching history so a reply landing in the gap is\n // buffered, not dropped. `onReconnectAck` fires on reconnect re-acks and\n // on a first ack that arrives after a `ready` timeout \u2014 both mean we are\n // (now) subscribed, so clear any connection error and (re)load history.\n const subscription = dashX.subscribeToChannel(\n `${CHAT_CHANNEL_PREFIX}${convId}`,\n (event) => {\n if (isStale()) return;\n appendMessages([toUiMessage(event)]);\n // LIVE messages only \u2014 history load / reconnect refetch go through\n // `refetchHistory`, so notification consumers never fire for\n // backfilled messages.\n onInboundMessageRef.current?.(event);\n },\n {\n onReconnectAck: () => {\n if (isStale()) return;\n setError(null);\n refetchHistory().catch(() => {});\n },\n },\n );\n unsubscribe = subscription.unsubscribe;\n\n // Load history only once the subscription is acked \u2014 fetching before\n // that would show history while silently never receiving realtime\n // replies. On ack failure, surface an error and defer the fetch to\n // `onReconnectAck` (fires if/when the channel finally acks).\n try {\n await subscription.ready;\n } catch {\n if (!isStale()) setError('Couldn\u2019t connect to live chat. Retrying\u2026');\n return;\n }\n if (isStale()) return;\n await refetchHistory();\n } catch {\n if (!isStale()) setError('Failed to start chat');\n } finally {\n if (!isStale()) setIsLoading(false);\n }\n })();\n\n return () => {\n // Invalidate in-flight async and drop the old channel before the next\n // conversation binds.\n generationRef.current += 1;\n unsubscribe?.();\n };\n }, [dashX, identityId, idempotencyKey, initialMessage, enabled, initializeWebSocket, appendMessages]);\n\n // Synchronous on purpose: it returns `true` the moment the message is optimistically\n // queued and runs the network send in the background. The caller clears the composer\n // on `true` immediately \u2014 if it instead awaited the round-trip, a fast second Enter\n // would re-send the still-present text as a new message (fresh clientMessageId, so the\n // backend won't dedupe it) and create a duplicate.\n const sendMessage = useCallback(\n (text: string): boolean => {\n const convId = conversationIdRef.current;\n // Not ready (conversation still starting, or start failed) \u2014 report back so\n // the caller can keep the typed text instead of clearing it on a no-op send.\n if (!text.trim() || !convId) return false;\n\n // Pin the generation so a response that resolves after the identity/key\n // changed (or unmount) can't contaminate the new conversation's state.\n const generation = generationRef.current;\n const clientMessageId = uuid();\n const optimistic: InAppChatMessage = {\n id: clientMessageId,\n externalUid: `in_app_chat:${clientMessageId}`,\n renderedContent: { text },\n aiRole: 'USER',\n createdAt: new Date().toISOString(),\n isPending: true,\n };\n appendMessages([optimistic]);\n\n void (async () => {\n try {\n const serverMessage = await dashX.sendInAppChatMessage({\n conversationId: convId,\n identityId,\n content: { text },\n clientMessageId,\n });\n if (generation !== generationRef.current) return;\n // Reconcile by externalUid (the WS echo reconciles too \u2014 both idempotent).\n appendMessages([toUiMessage(serverMessage)]);\n } catch {\n if (generation === generationRef.current) setError('Failed to send message');\n }\n })();\n\n // Queued (optimistically appended) \u2014 the background send reconciles/errors later.\n return true;\n },\n [dashX, identityId, appendMessages],\n );\n\n return { conversationId, messages, isLoading, isConnected, error, sendMessage };\n};\n\nexport type { UseInAppChatHookProps, UseInAppChatHookResponse, InAppChatMessage };\n\nexport default useInAppChat;\n"],
5
+ "mappings": "AAAA,OAAOA,MAAU,cACjB,OAAS,eAAAC,EAAa,aAAAC,EAAW,UAAAC,EAAQ,YAAAC,MAAgB,QAGzD,OAAOC,MAAsB,0BAC7B,OAAS,gBAAAC,M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NEL_PREFIX", "toUiMessage", "message", "mergeMessages", "existing", "incoming", "byKey", "keyOf", "existingForKey", "a", "b", "useInAppChat", "identityId", "idempotencyKey", "initialMessage", "enabled", "onInboundMessage", "dashX", "isConnected", "initializeWebSocket", "conversationId", "setConversationId", "messages", "setMessages", "isLoading", "setIsLoading", "error", "setError", "generationRef", "conversationIdRef", "onInboundMessageRef", "appendMessages", "prev", "generation", "isStale", "unsubscribe", "conversation", "convId", "refetchHistory", "history", "subscription", "event", "sendMessage", "text", "clientMessageId", "optimistic", "serverMessage", "use_in_app_chat_default"]
7
7
  }
@@ -1,4 +1,5 @@
1
1
  import { type UseInAppChatHookProps, type UseInAppChatHookResponse } from '../hooks/use-in-app-chat.js';
2
+ import { type InAppChatNotificationOptions } from '../hooks/use-in-app-chat-notifications.js';
2
3
  type InAppChatProps = UseInAppChatHookResponse & {
3
4
  withChatHeader?: boolean;
4
5
  withPopoverClose?: boolean;
@@ -6,8 +7,10 @@ type InAppChatProps = UseInAppChatHookResponse & {
6
7
  title?: string;
7
8
  };
8
9
  declare const InAppChat: ({ messages, isLoading, error, sendMessage, withChatHeader, withPopoverClose, borderless, title, }: InAppChatProps) => import("react/jsx-runtime").JSX.Element;
9
- type InAppChatWrapperProps = Omit<InAppChatProps, keyof UseInAppChatHookResponse> & UseInAppChatHookProps;
10
- declare const InAppChatWrapper: ({ identityId, idempotencyKey, initialMessage, ...props }: InAppChatWrapperProps) => import("react/jsx-runtime").JSX.Element;
10
+ type InAppChatWrapperProps = Omit<InAppChatProps, keyof UseInAppChatHookResponse> & Omit<UseInAppChatHookProps, 'enabled' | 'onInboundMessage'> & {
11
+ notifications?: boolean | InAppChatNotificationOptions;
12
+ };
13
+ declare const InAppChatWrapper: ({ identityId, idempotencyKey, initialMessage, notifications, ...props }: InAppChatWrapperProps) => import("react/jsx-runtime").JSX.Element;
11
14
  export type { InAppChatProps, InAppChatWrapperProps };
12
15
  export { InAppChat };
13
16
  export default InAppChatWrapper;
@@ -1,2 +1,2 @@
1
- import{jsx as e,jsxs as n}from"react/jsx-runtime";import*as r from"@radix-ui/react-scroll-area";import{useEffect as I,useState as w}from"react";import{Send as N,X as T}from"lucide-react";import{Button as g,Flex as s,Heading as P,Popover as S,Text as u,TextArea as k,Theme as H}from"../components";import{cn as f}from"../utils/cn.js";import R from"../hooks/use-auto-scroll.js";import U from"../hooks/use-in-app-chat.js";const z=o=>{const a=o.renderedContent;return typeof a=="string"?a:a?.text??""},E=o=>o.aiRole?.toUpperCase()==="USER",x=({messages:o,isLoading:a,error:p,sendMessage:i,withChatHeader:m=!1,withPopoverClose:b=!1,borderless:y=!1,title:C="Chat"})=>{const[l,c]=w(""),{scrollAreaRef:A,scrollToBottom:d}=R();I(()=>{setTimeout(()=>d({smooth:!0}),0)},[o.length,d]);const h=()=>{l.trim()&&i(l)&&c("")},v=t=>{t.key==="Enter"&&!t.shiftKey&&(t.preventDefault(),h())};return e(H,{asChild:!0,children:n(s,{direction:"column",className:f("h-full",!y&&"border border-gray-400/40"),children:[m&&n(s,{align:"center",justify:"between",className:"border-b border-b-gray-400/40 px-6 py-4",children:[e(P,{size:3,children:C}),b&&e(S.Close,{children:e(g,{shape:"square",roundness:"full",variant:"ghost",mode:"subtle",inset:"right",children:e(T,{})})})]}),e(s,{direction:"column",className:"grow overflow-auto bg-gray-50",children:n(r.Root,{ref:A,className:"h-full grow-1 p-6",children:[e(r.Viewport,{className:"h-full",children:n(s,{direction:"column",gap:3,children:[o.map(t=>e("div",{className:f("max-w-[80%] rounded-lg py-2 px-3",E(t)?"bg-accent-600 ml-auto items-end text-white":"bg-gray-200 mr-auto items-start text-gray-900"),children:e(u,{as:"p",size:2,children:z(t)})},t.externalUid||t.id)),a&&e(u,{as:"p",size:2,className:"mr-auto text-gray-500",children:"Loading\u2026"}),p&&e(u,{as:"p",size:2,className:"bg-negative-100 text-negative-900 mx-auto rounded-lg py-2 px-3",children:p})]})}),e(r.Scrollbar,{orientation:"vertical",className:"w-1 bg-gray-200 opacity-50",children:e(r.Thumb,{className:"flex-1 rounded-2xl bg-gray-400"})}),e(r.Corner,{})]})}),e("div",{className:"shrink-0 grow-0 border-t border-t-gray-400/40",children:n(s,{gap:2,align:"end",className:"w-full",children:[e("div",{className:"w-full [&_textarea]:!border-none [&_textarea]:!outline-none",children:e(k,{"aria-label":"message",size:"extralarge",placeholder:"Type a message\u2026",value:l,onKeyDown:v,onChange:t=>c(t),roundness:"none",autogrow:!0})}),e("div",{className:"mr-[7px] mb-[7px]",children:e(g,{shape:"square",roundness:"full",variant:"fill",size:"medium",onPress:h,isDisabled:!l.trim(),children:e(N,{size:20})})})]})})]})})},F=({identityId:o,idempotencyKey:a,initialMessage:p,...i})=>{const m=U({identityId:o,idempotencyKey:a,initialMessage:p});return e(x,{...m,...i})};var L=F;export{x as InAppChat,L as default};
1
+ import{jsx as e,jsxs as p}from"react/jsx-runtime";import*as n from"@radix-ui/react-scroll-area";import{useEffect as v,useState as w}from"react";import{Send as N,X as P}from"lucide-react";import{Button as b,Flex as s,Heading as T,Popover as S,Text as c,TextArea as k,Theme as H}from"../components";import{cn as x}from"../utils/cn.js";import R from"../hooks/use-auto-scroll.js";import U from"../hooks/use-in-app-chat.js";import z from"../hooks/use-in-app-chat-notifications.js";const M=o=>{const a=o.renderedContent;return typeof a=="string"?a:a?.text??""},O=o=>o.aiRole?.toUpperCase()==="USER",y=({messages:o,isLoading:a,error:l,sendMessage:r,withChatHeader:u=!1,withPopoverClose:m=!1,borderless:d=!1,title:C="Chat"})=>{const[i,h]=w(""),{scrollAreaRef:A,scrollToBottom:g}=R();v(()=>{setTimeout(()=>g({smooth:!0}),0)},[o.length,g]);const f=()=>{i.trim()&&r(i)&&h("")},I=t=>{t.key==="Enter"&&!t.shiftKey&&(t.preventDefault(),f())};return e(H,{asChild:!0,children:p(s,{direction:"column",className:x("h-full",!d&&"border border-gray-400/40"),children:[u&&p(s,{align:"center",justify:"between",className:"border-b border-b-gray-400/40 px-6 py-4",children:[e(T,{size:3,children:C}),m&&e(S.Close,{children:e(b,{shape:"square",roundness:"full",variant:"ghost",mode:"subtle",inset:"right",children:e(P,{})})})]}),e(s,{direction:"column",className:"grow overflow-auto bg-gray-50",children:p(n.Root,{ref:A,className:"h-full grow p-6",children:[e(n.Viewport,{className:"h-full",children:p(s,{direction:"column",gap:3,children:[o.map(t=>e("div",{className:x("max-w-[80%] rounded-lg py-2 px-3",O(t)?"bg-accent-600 ml-auto items-end text-white":"bg-gray-200 mr-auto items-start text-gray-900"),children:e(c,{as:"p",size:2,children:M(t)})},t.externalUid||t.id)),a&&e(c,{as:"p",size:2,className:"mr-auto text-gray-500",children:"Loading\u2026"}),l&&e(c,{as:"p",size:2,className:"bg-negative-100 text-negative-900 mx-auto rounded-lg py-2 px-3",children:l})]})}),e(n.Scrollbar,{orientation:"vertical",className:"w-1 bg-gray-200 opacity-50",children:e(n.Thumb,{className:"flex-1 rounded-2xl bg-gray-400"})}),e(n.Corner,{})]})}),e("div",{className:"shrink-0 grow-0 border-t border-t-gray-400/40",children:p(s,{gap:2,align:"end",className:"w-full",children:[e("div",{className:"w-full [&_textarea]:border-none! [&_textarea]:outline-none!",children:e(k,{"aria-label":"message",size:"extralarge",placeholder:"Type a message\u2026",value:i,onKeyDown:I,onChange:t=>h(t),roundness:"none",autogrow:!0})}),e("div",{className:"mr-[7px] mb-[7px]",children:e(b,{shape:"square",roundness:"full",variant:"fill",size:"medium",onPress:f,isDisabled:!i.trim(),children:e(N,{size:20})})})]})})]})})},E=({identityId:o,idempotencyKey:a,initialMessage:l,notifications:r=!0,...u})=>{const m=z({isOpen:!0,enabled:r!==!1,options:{requestPermissionOn:"manual",...typeof r=="object"?r:void 0}}),d=U({identityId:o,idempotencyKey:a,initialMessage:l,onInboundMessage:m.handleInboundMessage});return e(y,{...d,...u})};var _=E;export{y as InAppChat,_ as default};
2
2
  //# sourceMappingURL=InAppChat.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/widgets/InAppChat.tsx"],
4
- "sourcesContent": ["import * as ScrollArea from '@radix-ui/react-scroll-area';\nimport React, { useEffect, useState } from 'react';\nimport { Send, X } from 'lucide-react';\nimport type { KeyboardEvent } from 'react';\n\nimport { Button, Flex, Heading, Popover, Text, TextArea, Theme } from '../components';\nimport { cn } from '../utils/cn.js';\nimport useAutoScroll from '../hooks/use-auto-scroll.js';\nimport useInAppChat, {\n type InAppChatMessage,\n type UseInAppChatHookProps,\n type UseInAppChatHookResponse,\n} from '../hooks/use-in-app-chat.js';\n\ntype InAppChatProps = UseInAppChatHookResponse & {\n withChatHeader?: boolean;\n withPopoverClose?: boolean;\n borderless?: boolean;\n title?: string;\n};\n\nconst messageText = (message: InAppChatMessage): string => {\n const content = message.renderedContent;\n if (typeof content === 'string') return content;\n return content?.text ?? '';\n};\n\nconst isOutgoing = (message: InAppChatMessage): boolean => message.aiRole?.toUpperCase() === 'USER';\n\nconst InAppChat = ({\n messages,\n isLoading,\n error,\n sendMessage,\n withChatHeader = false,\n withPopoverClose = false,\n borderless = false,\n title = 'Chat',\n}: InAppChatProps) => {\n const [inputValue, setInputValue] = useState('');\n const { scrollAreaRef, scrollToBottom } = useAutoScroll();\n\n useEffect(() => {\n setTimeout(() => scrollToBottom({ smooth: true }), 0);\n }, [messages.length, scrollToBottom]);\n\n const handleSubmit = () => {\n if (!inputValue.trim()) return;\n // `sendMessage` is synchronous: it returns true the instant the message is\n // optimistically queued (network send runs in the background). Clear the\n // composer right away on success so a fast second Enter can't re-send the same\n // text as a duplicate; on false (chat not ready) keep the visitor's text.\n if (sendMessage(inputValue)) setInputValue('');\n };\n\n const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {\n if (e.key === 'Enter' && !e.shiftKey) {\n e.preventDefault();\n handleSubmit();\n }\n };\n\n return (\n <Theme asChild>\n <Flex direction=\"column\" className={cn('h-full', !borderless && 'border border-gray-400/40')}>\n {withChatHeader && (\n <Flex align=\"center\" justify=\"between\" className=\"border-b border-b-gray-400/40 px-6 py-4\">\n <Heading size={3}>{title}</Heading>\n {withPopoverClose && (\n <Popover.Close>\n <Button shape=\"square\" roundness=\"full\" variant=\"ghost\" mode=\"subtle\" inset=\"right\">\n <X />\n </Button>\n </Popover.Close>\n )}\n </Flex>\n )}\n\n <Flex direction=\"column\" className=\"grow overflow-auto bg-gray-50\">\n <ScrollArea.Root ref={scrollAreaRef} className=\"h-full grow-1 p-6\">\n <ScrollArea.Viewport className=\"h-full\">\n <Flex direction=\"column\" gap={3}>\n {messages.map((message) => (\n <div\n key={message.externalUid || message.id}\n className={cn(\n 'max-w-[80%] rounded-lg py-2 px-3',\n isOutgoing(message)\n ? 'bg-accent-600 ml-auto items-end text-white'\n : 'bg-gray-200 mr-auto items-start text-gray-900',\n )}\n >\n <Text as=\"p\" size={2}>{messageText(message)}</Text>\n </div>\n ))}\n\n {isLoading && (\n <Text as=\"p\" size={2} className=\"mr-auto text-gray-500\">\n Loading\u2026\n </Text>\n )}\n\n {error && (\n <Text\n as=\"p\"\n size={2}\n className=\"bg-negative-100 text-negative-900 mx-auto rounded-lg py-2 px-3\"\n >\n {error}\n </Text>\n )}\n </Flex>\n </ScrollArea.Viewport>\n <ScrollArea.Scrollbar orientation=\"vertical\" className=\"w-1 bg-gray-200 opacity-50\">\n <ScrollArea.Thumb className=\"flex-1 rounded-2xl bg-gray-400\" />\n </ScrollArea.Scrollbar>\n <ScrollArea.Corner />\n </ScrollArea.Root>\n </Flex>\n\n <div className=\"shrink-0 grow-0 border-t border-t-gray-400/40\">\n <Flex gap={2} align=\"end\" className=\"w-full\">\n <div className=\"w-full [&_textarea]:!border-none [&_textarea]:!outline-none\">\n <TextArea\n aria-label=\"message\"\n size=\"extralarge\"\n placeholder=\"Type a message\u2026\"\n value={inputValue}\n onKeyDown={handleKeyDown}\n onChange={(text) => setInputValue(text)}\n roundness=\"none\"\n autogrow\n />\n </div>\n <div className=\"mr-[7px] mb-[7px]\">\n <Button\n shape=\"square\"\n roundness=\"full\"\n variant=\"fill\"\n size=\"medium\"\n onPress={handleSubmit}\n isDisabled={!inputValue.trim()}\n >\n <Send size={20} />\n </Button>\n </div>\n </Flex>\n </div>\n </Flex>\n </Theme>\n );\n};\n\ntype InAppChatWrapperProps = Omit<InAppChatProps, keyof UseInAppChatHookResponse> & UseInAppChatHookProps;\n\nconst InAppChatWrapper = ({ identityId, idempotencyKey, initialMessage, ...props }: InAppChatWrapperProps) => {\n const chat = useInAppChat({ identityId, idempotencyKey, initialMessage });\n return <InAppChat {...chat} {...props} />;\n};\n\nexport type { InAppChatProps, InAppChatWrapperProps };\n\nexport { InAppChat };\n\nexport default InAppChatWrapper;\n"],
5
- "mappings": "AAkEU,OACE,OAAAA,EADF,QAAAC,MAAA,oBAlEV,UAAYC,MAAgB,8BAC5B,OAAgB,aAAAC,EAAW,YAAAC,MAAgB,QAC3C,OAAS,QAAAC,EAAM,KAAAC,MAAS,eAGxB,OAAS,UAAAC,EAAQ,QAAAC,EAAM,WAAAC,EAAS,WAAAC,EAAS,QAAAC,EAAM,YAAAC,EAAU,SAAAC,MAAa,gBACtE,OAAS,MAAAC,MAAU,iBACnB,OAAOC,MAAmB,8BAC1B,OAAOC,MAIA,8BASP,MAAMC,EAAeC,GAAsC,CACzD,MAAMC,EAAUD,EAAQ,gBACxB,OAAI,OAAOC,GAAY,SAAiBA,EACjCA,GAAS,MAAQ,EAC1B,EAEMC,EAAcF,GAAuCA,EAAQ,QAAQ,YAAY,IAAM,OAEvFG,EAAY,CAAC,CACjB,SAAAC,EACA,UAAAC,EACA,MAAAC,EACA,YAAAC,EACA,eAAAC,EAAiB,GACjB,iBAAAC,EAAmB,GACnB,WAAAC,EAAa,GACb,MAAAC,EAAQ,MACV,IAAsB,CACpB,KAAM,CAACC,EAAYC,CAAa,EAAI3B,EAAS,EAAE,EACzC,CAAE,cAAA4B,EAAe,eAAAC,CAAe,EAAIlB,EAAc,EAExDZ,EAAU,IAAM,CACd,WAAW,IAAM8B,EAAe,CAAE,OAAQ,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AM,EACN,UAAU,iEAET,SAAAa,EACH,GAEJ,EACF,EACAxB,EAACE,EAAW,UAAX,CAAqB,YAAY,WAAW,UAAU,6BACrD,SAAAF,EAACE,EAAW,MAAX,CAAiB,UAAU,iCAAiC,EAC/D,EACAF,EAACE,EAAW,OAAX,EAAkB,GACrB,EACF,EAEAF,EAAC,OAAI,UAAU,gDACb,SAAAC,EAACO,EAAA,CAAK,IAAK,EAAG,MAAM,MAAM,UAAU,SAClC,UAAAR,EAAC,OAAI,UAAU,8DACb,SAAAA,EAACY,EAAA,CACC,aAAW,UACX,KAAK,aACL,YAAY,uBACZ,MAAOkB,EACP,UAAWK,EACX,SAAWE,GAASN,EAAcM,CAAI,EACtC,UAAU,OACV,SAAQ,GACV,EACF,EACArC,EAAC,OAAI,UAAU,oBACb,SAAAA,EAACO,EAAA,CACC,MAAM,SACN,UAAU,OACV,QAAQ,OACR,KAAK,SACL,QAAS2B,EACT,WAAY,CAACJ,EAAW,KAAK,EAE7B,SAAA9B,EAACK,EAAA,CAAK,KAAM,GAAI,EAClB,EACF,GACF,EACF,GACF,EACF,CAEJ,EAIMiC,EAAmB,CAAC,CAAE,WAAAC,EAAY,eAAAC,EAAgB,eAAAC,EAAgB,GAAGC,CAAM,IAA6B,CAC5G,MAAMC,EAAO3B,EAAa,CAAE,WAAAuB,EAAY,eAAAC,EAAgB,eAAAC,CAAe,CAAC,EACxE,OAAOzC,EAACqB,EAAA,CAAW,GAAGsB,EAAO,GAAGD,EAAO,CACzC,EAMA,IAAOE,EAAQN",
6
- "names": ["jsx", "jsxs", "ScrollArea", "useEffect", "useState", "Send", "X", "Button", "Flex", "Heading", "Popover", "Text", "TextArea", "Theme", "cn", "useAutoScroll", "useInAppChat", "messageText", "message", "content", "isOutgoing", "InAppChat", "messages", "isLoading", "error", "sendMessage", "withChatHeader", "withPopoverClose", "borderless", "title", "inputValue", "setInputValue", "scrollAreaRef", "scrollToBottom", "handleSubmit", "handleKeyDown", "e", "text", "InAppChatWrapper", "identityId", "idempotencyKey", "initialMessage", "props", "chat", "InAppChat_default"]
4
+ "sourcesContent": ["import * as ScrollArea from '@radix-ui/react-scroll-area';\nimport React, { useEffect, useState } from 'react';\nimport { Send, X } from 'lucide-react';\nimport type { KeyboardEvent } from 'react';\n\nimport { Button, Flex, Heading, Popover, Text, TextArea, Theme } from '../components';\nimport { cn } from '../utils/cn.js';\nimport useAutoScroll from '../hooks/use-auto-scroll.js';\nimport useInAppChat, {\n type InAppChatMessage,\n type UseInAppChatHookProps,\n type UseInAppChatHookResponse,\n} from '../hooks/use-in-app-chat.js';\nimport useInAppChatNotifications, {\n type InAppChatNotificationOptions,\n} from '../hooks/use-in-app-chat-notifications.js';\n\ntype InAppChatProps = UseInAppChatHookResponse & {\n withChatHeader?: boolean;\n withPopoverClose?: boolean;\n borderless?: boolean;\n title?: string;\n};\n\nconst messageText = (message: InAppChatMessage): string => {\n const content = message.renderedContent;\n if (typeof content === 'string') return content;\n return content?.text ?? '';\n};\n\nconst isOutgoing = (message: InAppChatMessage): boolean => message.aiRole?.toUpperCase() === 'USER';\n\nconst InAppChat = ({\n messages,\n isLoading,\n error,\n sendMessage,\n withChatHeader = false,\n withPopoverClose = false,\n borderless = false,\n title = 'Chat',\n}: InAppChatProps) => {\n const [inputValue, setInputValue] = useState('');\n const { scrollAreaRef, scrollToBottom } = useAutoScroll();\n\n useEffect(() => {\n setTimeout(() => scrollToBottom({ smooth: true }), 0);\n }, [messages.length, scrollToBottom]);\n\n const handleSubmit = () => {\n if (!inputValue.trim()) return;\n // `sendMessage` is synchronous: it returns true the instant the message is\n // optimistically queued (network send runs in the background). Clear the\n // composer right away on success so a fast second Enter can't re-send the same\n // text as a duplicate; on false (chat not ready) keep the visitor's text.\n if (sendMessage(inputValue)) setInputValue('');\n };\n\n const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {\n if (e.key === 'Enter' && !e.shiftKey) {\n e.preventDefault();\n handleSubmit();\n }\n };\n\n return (\n <Theme asChild>\n <Flex direction=\"column\" className={cn('h-full', !borderless && 'border border-gray-400/40')}>\n {withChatHeader && (\n <Flex align=\"center\" justify=\"between\" className=\"border-b border-b-gray-400/40 px-6 py-4\">\n <Heading size={3}>{title}</Heading>\n {withPopoverClose && (\n <Popover.Close>\n <Button shape=\"square\" roundness=\"full\" variant=\"ghost\" mode=\"subtle\" inset=\"right\">\n <X />\n </Button>\n </Popover.Close>\n )}\n </Flex>\n )}\n\n <Flex direction=\"column\" className=\"grow overflow-auto bg-gray-50\">\n <ScrollArea.Root ref={scrollAreaRef} className=\"h-full grow p-6\">\n <ScrollArea.Viewport className=\"h-full\">\n <Flex direction=\"column\" gap={3}>\n {messages.map((message) => (\n <div\n key={message.externalUid || message.id}\n className={cn(\n 'max-w-[80%] rounded-lg py-2 px-3',\n isOutgoing(message)\n ? 'bg-accent-600 ml-auto items-end text-white'\n : 'bg-gray-200 mr-auto items-start text-gray-900',\n )}\n >\n <Text as=\"p\" size={2}>{messageText(message)}</Text>\n </div>\n ))}\n\n {isLoading && (\n <Text as=\"p\" size={2} className=\"mr-auto text-gray-500\">\n Loading\u2026\n </Text>\n )}\n\n {error && (\n <Text\n as=\"p\"\n size={2}\n className=\"bg-negative-100 text-negative-900 mx-auto rounded-lg py-2 px-3\"\n >\n {error}\n </Text>\n )}\n </Flex>\n </ScrollArea.Viewport>\n <ScrollArea.Scrollbar orientation=\"vertical\" className=\"w-1 bg-gray-200 opacity-50\">\n <ScrollArea.Thumb className=\"flex-1 rounded-2xl bg-gray-400\" />\n </ScrollArea.Scrollbar>\n <ScrollArea.Corner />\n </ScrollArea.Root>\n </Flex>\n\n <div className=\"shrink-0 grow-0 border-t border-t-gray-400/40\">\n <Flex gap={2} align=\"end\" className=\"w-full\">\n <div className=\"w-full [&_textarea]:border-none! [&_textarea]:outline-none!\">\n <TextArea\n aria-label=\"message\"\n size=\"extralarge\"\n placeholder=\"Type a message\u2026\"\n value={inputValue}\n onKeyDown={handleKeyDown}\n onChange={(text) => setInputValue(text)}\n roundness=\"none\"\n autogrow\n />\n </div>\n <div className=\"mr-[7px] mb-[7px]\">\n <Button\n shape=\"square\"\n roundness=\"full\"\n variant=\"fill\"\n size=\"medium\"\n onPress={handleSubmit}\n isDisabled={!inputValue.trim()}\n >\n <Send size={20} />\n </Button>\n </div>\n </Flex>\n </div>\n </Flex>\n </Theme>\n );\n};\n\ntype InAppChatWrapperProps = Omit<InAppChatProps, keyof UseInAppChatHookResponse>\n & Omit<UseInAppChatHookProps, 'enabled' | 'onInboundMessage'>\n & {\n // Foreground browser notifications for incoming agent/AI messages while the\n // chat isn't focused. `false` disables; an object customizes title/icon/body.\n // Default: enabled but silent until permission is granted (this always-visible\n // surface never auto-prompts \u2014 call `Client.requestNotificationPermission()`\n // from your own UI, or use `<InAppChatButton>` which prompts on first open).\n notifications?: boolean | InAppChatNotificationOptions;\n };\n\nconst InAppChatWrapper = ({ identityId, idempotencyKey, initialMessage, notifications = true, ...props }: InAppChatWrapperProps) => {\n // Always-visible surface: treat as \"open\" and gate notifications on tab\n // visibility/focus only. No launcher gesture exists here, so default to\n // 'manual' permission (auto-requesting would prompt on mount).\n const notifier = useInAppChatNotifications({\n isOpen: true,\n enabled: notifications !== false,\n options: {\n requestPermissionOn: 'manual',\n ...(typeof notifications === 'object' ? notifications : undefined),\n },\n });\n const chat = useInAppChat({\n identityId,\n idempotencyKey,\n initialMessage,\n onInboundMessage: notifier.handleInboundMessage,\n });\n return <InAppChat {...chat} {...props} />;\n};\n\nexport type { InAppChatProps, InAppChatWrapperProps };\n\nexport { InAppChat };\n\nexport default InAppChatWrapper;\n"],
5
+ "mappings": "AAqEU,OACE,OAAAA,EADF,QAAAC,MAAA,oBArEV,UAAYC,MAAgB,8BAC5B,OAAgB,aAAAC,EAAW,YAAAC,MAAgB,QAC3C,OAAS,QAAAC,EAAM,KAAAC,MAAS,eAGxB,OAAS,UAAAC,EAAQ,QAAAC,EAAM,WAAAC,EAAS,WAAAC,EAAS,QAAAC,EAAM,YAAAC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AAA,CAAK,KAAM,GAAI,EAClB,EACF,GACF,EACF,GACF,EACF,CAEJ,EAaMkC,EAAmB,CAAC,CAAE,WAAAC,EAAY,eAAAC,EAAgB,eAAAC,EAAgB,cAAAC,EAAgB,GAAM,GAAGC,CAAM,IAA6B,CAIlI,MAAMC,EAAW5B,EAA0B,CACzC,OAAQ,GACR,QAAS0B,IAAkB,GAC3B,QAAS,CACP,oBAAqB,SACrB,GAAI,OAAOA,GAAkB,SAAWA,EAAgB,MAC1D,CACF,CAAC,EACKG,EAAO9B,EAAa,CACxB,WAAAwB,EACA,eAAAC,EACA,eAAAC,EACA,iBAAkBG,EAAS,oBAC7B,CAAC,EACD,OAAO7C,EAACsB,EAAA,CAAW,GAAGwB,EAAO,GAAGF,EAAO,CACzC,EAMA,IAAOG,EAAQR",
6
+ "names": ["jsx", "jsxs", "ScrollArea", "useEffect", "useState", "Send", "X", "Button", "Flex", "Heading", "Popover", "Text", "TextArea", "Theme", "cn", "useAutoScroll", "useInAppChat", "useInAppChatNotifications", "messageText", "message", "content", "isOutgoing", "InAppChat", "messages", "isLoading", "error", "sendMessage", "withChatHeader", "withPopoverClose", "borderless", "title", "inputValue", "setInputValue", "scrollAreaRef", "scrollToBottom", "handleSubmit", "handleKeyDown", "e", "text", "InAppChatWrapper", "identityId", "idempotencyKey", "initialMessage", "notifications", "props", "notifier", "chat", "InAppChat_default"]
7
7
  }
@@ -7,6 +7,6 @@ type InAppChatButtonProps = InAppChatWrapperProps & {
7
7
  /** Theme overrides for the launcher + chat surface (accent color, mode, roundness, …). */
8
8
  theme?: ThemeProps;
9
9
  };
10
- declare const InAppChatButton: ({ identityId, idempotencyKey, position, theme, ...props }: InAppChatButtonProps) => import("react/jsx-runtime").JSX.Element;
10
+ declare const InAppChatButton: ({ identityId, idempotencyKey, initialMessage, notifications, position, theme, ...props }: InAppChatButtonProps) => import("react/jsx-runtime").JSX.Element;
11
11
  export type { InAppChatButtonProps };
12
12
  export default InAppChatButton;
@@ -1,2 +1,2 @@
1
- import{jsx as t,jsxs as f}from"react/jsx-runtime";import"react";import{MessageCircle as h}from"lucide-react";import{Button as s,Flex as a,Popover as o,Theme as m}from"../components";import l from"./InAppChat.js";const g={"bottom-right":"right-4 bottom-4","bottom-left":"left-4 bottom-4","top-right":"right-4 top-4","top-left":"left-4 top-4"},P=({identityId:e,idempotencyKey:p,position:r="bottom-right",theme:i,...n})=>t(m,{...i,children:t(a,{className:`fixed z-50 ${g[r]}`,children:f(o.Root,{children:[t(o.Trigger,{children:t(s,{shape:"square",roundness:"full",variant:"fill",size:"large",children:t(h,{})})}),t(o.Content,{spacing:"large",width:"350px",height:"450px",children:t(l,{identityId:e,idempotencyKey:p,borderless:!0,withChatHeader:!0,withPopoverClose:!0,...n})})]})})});var b=P;export{b as default};
1
+ import{jsx as t,jsxs as w}from"react/jsx-runtime";import{useCallback as i,useRef as I,useState as A}from"react";import{MessageCircle as O}from"lucide-react";import{Button as v,Flex as T,Popover as p,Theme as y}from"../components";import{InAppChat as B}from"./InAppChat.js";import R from"../hooks/use-in-app-chat.js";import x from"../hooks/use-in-app-chat-notifications.js";const L={"bottom-right":"right-4 bottom-4","bottom-left":"left-4 bottom-4","top-right":"right-4 top-4","top-left":"left-4 top-4"},S=({identityId:h,idempotencyKey:l,initialMessage:u,notifications:e=!0,position:m="bottom-right",theme:f,...c})=>{const[o,n]=A(!1),r=I(!1);o&&(r.current=!0);const g=r.current,C=i(()=>n(!0),[]),{handleInboundMessage:P,requestPermissionOnOpen:s}=x({isOpen:o,enabled:e!==!1,options:typeof e=="object"?e:void 0,onActivate:C}),d=i(a=>{a&&s(),n(a)},[s]),b=R({identityId:h,idempotencyKey:l,initialMessage:u,enabled:g,onInboundMessage:P});return t(y,{...f,children:t(T,{className:`fixed z-50 ${L[m]}`,children:w(p.Root,{open:o,onOpenChange:d,children:[t(p.Trigger,{children:t(v,{shape:"square",roundness:"full",variant:"fill",size:"large",children:t(O,{})})}),t(p.Content,{spacing:"large",width:"350px",height:"450px",children:t(B,{...b,borderless:!0,withChatHeader:!0,withPopoverClose:!0,...c})})]})})})};var H=S;export{H as default};
2
2
  //# sourceMappingURL=InAppChatButton.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/widgets/InAppChatButton.tsx"],
4
- "sourcesContent": ["import React from 'react';\nimport { MessageCircle } from 'lucide-react';\n\nimport { Button, Flex, Popover, Theme, type ThemeProps } from '../components';\nimport InAppChat, { type InAppChatWrapperProps } from './InAppChat.js';\n\ntype LauncherPosition = 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left';\n\ntype InAppChatButtonProps = InAppChatWrapperProps & {\n /** Where the floating launcher sits on screen. Defaults to `bottom-right`. */\n position?: LauncherPosition,\n /** Theme overrides for the launcher + chat surface (accent color, mode, roundness, \u2026). */\n theme?: ThemeProps,\n};\n\n// Full, non-interpolated class strings so Tailwind can detect them.\nconst POSITION_CLASS: Record<LauncherPosition, string> = {\n 'bottom-right': 'right-4 bottom-4',\n 'bottom-left': 'left-4 bottom-4',\n 'top-right': 'right-4 top-4',\n 'top-left': 'left-4 top-4',\n};\n\nconst InAppChatButton = ({\n identityId,\n idempotencyKey,\n position = 'bottom-right',\n theme,\n ...props\n}: InAppChatButtonProps) => (\n <Theme {...theme}>\n <Flex className={`fixed z-50 ${POSITION_CLASS[position]}`}>\n <Popover.Root>\n <Popover.Trigger>\n <Button shape=\"square\" roundness=\"full\" variant=\"fill\" size=\"large\">\n <MessageCircle />\n </Button>\n </Popover.Trigger>\n {/* Radix unmounts Content while closed, so the chat hook (start \u2192\n subscribe \u2192 fetch) runs only once the visitor opens the launcher \u2014\n no empty conversation is created on page load. */}\n <Popover.Content spacing=\"large\" width=\"350px\" height=\"450px\">\n <InAppChat\n identityId={identityId}\n idempotencyKey={idempotencyKey}\n borderless\n withChatHeader\n withPopoverClose\n {...props}\n />\n </Popover.Content>\n </Popover.Root>\n </Flex>\n </Theme>\n);\n\nexport type { InAppChatButtonProps };\n\nexport default InAppChatButton;\n"],
5
- "mappings": "AAgCM,OAGM,OAAAA,EAHN,QAAAC,MAAA,oBAhCN,MAAkB,QAClB,OAAS,iBAAAC,MAAqB,eAE9B,OAAS,UAAAC,EAAQ,QAAAC,EAAM,WAAAC,EAAS,SAAAC,MAA8B,gBAC9D,OAAOC,MAA+C,iBAYtD,MAAMC,EAAmD,CACvD,eAAgB,mBAChB,cAAe,kBACf,YAAa,gBACb,WAAY,cACd,EAEMC,EAAkB,CAAC,CACvB,WAAAC,EACA,eAAAC,EACA,SAAAC,EAAW,eACX,MAAAC,EACA,GAAGC,CACL,IACEd,EAACM,EAAA,CAAO,GAAGO,EACT,SAAAb,EAACI,EAAA,CAAK,UAAW,cAAcI,EAAeI,CAAQ,CAAC,GACrD,SAAAX,EAACI,EAAQ,KAAR,CACC,UAAAL,EAACK,EAAQ,QAAR,CACC,SAAAL,EAACG,EAAA,CAAO,MAAM,SAAS,UAAU,OAAO,QAAQ,OAAO,KAAK,QAC1D,SAAAH,EAACE,EAAA,EAAc,EACjB,EACF,EAIAF,EAACK,EAAQ,QAAR,CAAgB,QAAQ,QAAQ,MAAM,QAAQ,OAAO,QACpD,SAAAL,EAACO,EAAA,CACC,WAAYG,EACZ,eAAgBC,EAChB,WAAU,GACV,eAAc,GACd,iBAAgB,GACf,GAAGG,EACN,EACF,GACF,EACF,EACF,EAKF,IAAOC,EAAQN",
6
- "names": ["jsx", "jsxs", "MessageCircle", "Button", "Flex", "Popover", "Theme", "InAppChat", "POSITION_CLASS", "InAppChatButton", "identityId", "idempotencyKey", "position", "theme", "props", "InAppChatButton_default"]
4
+ "sourcesContent": ["import React, { useCallback, useRef, useState } from 'react';\nimport { MessageCircle } from 'lucide-react';\n\nimport { Button, Flex, Popover, Theme, type ThemeProps } from '../components';\nimport { InAppChat, type InAppChatWrapperProps } from './InAppChat.js';\nimport useInAppChat from '../hooks/use-in-app-chat.js';\nimport useInAppChatNotifications from '../hooks/use-in-app-chat-notifications.js';\n\ntype LauncherPosition = 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left';\n\ntype InAppChatButtonProps = InAppChatWrapperProps & {\n /** Where the floating launcher sits on screen. Defaults to `bottom-right`. */\n position?: LauncherPosition,\n /** Theme overrides for the launcher + chat surface (accent color, mode, roundness, \u2026). */\n theme?: ThemeProps,\n};\n\n// Full, non-interpolated class strings so Tailwind can detect them.\nconst POSITION_CLASS: Record<LauncherPosition, string> = {\n 'bottom-right': 'right-4 bottom-4',\n 'bottom-left': 'left-4 bottom-4',\n 'top-right': 'right-4 top-4',\n 'top-left': 'left-4 top-4',\n};\n\nconst InAppChatButton = ({\n identityId,\n idempotencyKey,\n initialMessage,\n notifications = true,\n position = 'bottom-right',\n theme,\n ...props\n}: InAppChatButtonProps) => {\n const [isOpen, setIsOpen] = useState(false);\n\n // Latch: once the launcher has been opened, keep the chat hook active so its\n // channel subscription persists while the panel is closed \u2014 that's what lets\n // us notify on replies that land while the panel is shut. Before the first\n // open the hook is idle, so no conversation is created on page load.\n const hasOpenedRef = useRef(false);\n if (isOpen) hasOpenedRef.current = true;\n const enabled = hasOpenedRef.current;\n\n const open = useCallback(() => setIsOpen(true), []);\n\n const { handleInboundMessage, requestPermissionOnOpen } = useInAppChatNotifications({\n isOpen,\n enabled: notifications !== false,\n options: typeof notifications === 'object' ? notifications : undefined,\n onActivate: open,\n });\n\n // Request notification permission inside the open gesture (synchronously), so\n // the prompt runs within the browser's transient user activation \u2014 requesting\n // from an effect after the click unwinds is ignored on some browsers.\n const handleOpenChange = useCallback(\n (nextOpen: boolean) => {\n if (nextOpen) requestPermissionOnOpen();\n setIsOpen(nextOpen);\n },\n [requestPermissionOnOpen],\n );\n\n const chat = useInAppChat({\n identityId,\n idempotencyKey,\n initialMessage,\n enabled,\n onInboundMessage: handleInboundMessage,\n });\n\n return (\n <Theme {...theme}>\n <Flex className={`fixed z-50 ${POSITION_CLASS[position]}`}>\n <Popover.Root open={isOpen} onOpenChange={handleOpenChange}>\n <Popover.Trigger>\n <Button shape=\"square\" roundness=\"full\" variant=\"fill\" size=\"large\">\n <MessageCircle />\n </Button>\n </Popover.Trigger>\n {/* The chat hook lives at the launcher level (above the popover) so its\n subscription survives the panel closing \u2014 required to notify on\n replies that arrive while the panel is shut. It activates lazily on\n first open, so no empty conversation is created on page load. */}\n <Popover.Content spacing=\"large\" width=\"350px\" height=\"450px\">\n <InAppChat\n {...chat}\n borderless\n withChatHeader\n withPopoverClose\n {...props}\n />\n </Popover.Content>\n </Popover.Root>\n </Flex>\n </Theme>\n );\n};\n\nexport type { InAppChatButtonProps };\n\nexport default InAppChatButton;\n"],
5
+ "mappings": "AA2EQ,OAGM,OAAAA,EAHN,QAAAC,MAAA,oBA3ER,OAAgB,eAAAC,EAAa,UAAAC,EAAQ,YAAAC,MAAgB,QACrD,OAAS,iBAAAC,MAAqB,eAE9B,OAAS,UAAAC,EAAQ,QAAAC,EAAM,WAAAC,EAAS,SAAAC,MAA8B,gBAC9D,OAAS,aAAAC,MAA6C,iBACtD,OAAOC,MAAkB,8BACzB,OAAOC,MAA+B,4CAYtC,MAAMC,EAAmD,CACvD,eAAgB,mBAChB,cAAe,kBACf,YAAa,gBACb,WAAY,cACd,EAEMC,EAAkB,CAAC,CACvB,WAAAC,EACA,eAAAC,EACA,eAAAC,EACA,cAAAC,EAAgB,GAChB,SAAAC,EAAW,eACX,MAAAC,EACA,GAAGC,CACL,IAA4B,CAC1B,KAAM,CAACC,EAAQC,CAAS,EAAInB,EAAS,EAAK,EAMpCoB,EAAerB,EAAO,EAAK,EAC7BmB,IAAQE,EAAa,QAAU,IACnC,MAAMC,EAAUD,EAAa,QAEvBE,EAAOxB,EAAY,IAAMqB,EAAU,EAAI,EAAG,CAAC,CAAC,EAE5C,CAAE,qBAAAI,EAAsB,wBAAAC,CAAwB,EAAIhB,EAA0B,CAClF,OAAAU,EACA,QAASJ,IAAkB,GAC3B,QAAS,OAAOA,GAAkB,SAAWA,EAAgB,OAC7D,WAAYQ,CACd,CAAC,EAKKG,EAAmB3B,EACtB4B,GAAsB,CACjBA,GAAUF,EAAwB,EACtCL,EAAUO,CAAQ,CACpB,EACA,CAACF,CAAuB,CAC1B,EAEMG,EAAOpB,EAAa,CACxB,WAAAI,EACA,eAAAC,EACA,eAAAC,EACA,QAAAQ,EACA,iBAAkBE,CACpB,CAAC,EAED,OACE3B,EAACS,EAAA,CAAO,GAAGW,EACT,SAAApB,EAACO,EAAA,CAAK,UAAW,cAAcM,EAAeM,CAAQ,CAAC,GACrD,SAAAlB,EAACO,EAAQ,KAAR,CAAa,KAAMc,EAAQ,aAAcO,EACxC,UAAA7B,EAACQ,EAAQ,QAAR,CACC,SAAAR,EAACM,EAAA,CAAO,MAAM,SAAS,UAAU,OAAO,QAAQ,OAAO,KAAK,QAC1D,SAAAN,EAACK,EAAA,EAAc,EACjB,EACF,EAKAL,EAACQ,EAAQ,QAAR,CAAgB,QAAQ,QAAQ,MAAM,QAAQ,OAAO,QACpD,SAAAR,EAACU,EAAA,CACE,GAAGqB,EACJ,WAAU,GACV,eAAc,GACd,iBAAgB,GACf,GAAGV,EACN,EACF,GACF,EACF,EACF,CAEJ,EAIA,IAAOW,EAAQlB",
6
+ "names": ["jsx", "jsxs", "useCallback", "useRef", "useState", "MessageCircle", "Button", "Flex", "Popover", "Theme", "InAppChat", "useInAppChat", "useInAppChatNotifications", "POSITION_CLASS", "InAppChatButton", "identityId", "idempotencyKey", "initialMessage", "notifications", "position", "theme", "props", "isOpen", "setIsOpen", "hasOpenedRef", "enabled", "open", "handleInboundMessage", "requestPermissionOnOpen", "handleOpenChange", "nextOpen", "chat", "InAppChatButton_default"]
7
7
  }
@@ -0,0 +1,2 @@
1
+ declare const NotificationBell: () => import("react/jsx-runtime").JSX.Element;
2
+ export default NotificationBell;
@@ -0,0 +1,2 @@
1
+ import{jsx as e,jsxs as o}from"react/jsx-runtime";import{intlFormatDistance as u}from"date-fns";import{useInApp as c}from"../hooks/index.js";import{Button as s,Card as m,Flex as i,Heading as T,Popover as r,Text as n,Theme as h,Tooltip as a}from"../components";import{Inbox as v,Mail as x,MailOpen as f,X as y}from"../icons/index.js";const C=()=>{let{markNotificationAsRead:d,markNotificationAsUnread:p,notifications:l,unreadNotificationsCount:g}=c();return e(h,{children:o(r.Root,{children:[o(a.Root,{children:[e(a.Trigger,{children:e(r.Trigger,{children:e(s,{shape:"square",roundness:"full",variant:g?"fill":"ghost",children:e(v,{})})})}),e(a.Content,{content:"Notification"})]}),o(r.Content,{spacing:"large",width:"350px",height:"450px",children:[e(r.Header,{asChild:!0,children:o(i,{justify:"between",align:"center",children:[e(T,{size:3,children:"Notifications"}),e(r.Close,{children:e(s,{shape:"square",roundness:"full",variant:"ghost",mode:"subtle",inset:"right",children:e(y,{})})})]})}),e(r.Body,{children:o(i,{direction:"column",gap:1,children:[l.length===0&&e(i,{justify:"center",align:"center",children:e(n,{variant:"tertiary",size:2,children:"No notifications yet."})}),l.map(t=>e(m,{children:o(i,{align:"center",gap:4,justify:"between",children:[o(i,{direction:"column",gap:1,children:[e(n,{as:"p",variant:"secondary",weight:"semibold",size:2,children:t.renderedContent.body}),e(n,{size:1,variant:"tertiary",children:u(t.sentAt,new Date)})]}),o(a.Root,{children:[e(a.Trigger,{children:e(s,{shape:"square",variant:"ghost",roundness:"full",mode:t.readAt?"subtle":"distinct",onPress:()=>{t.readAt?p(t.id):d(t.id)},children:t.readAt?e(f,{}):e(x,{})})}),e(a.Content,{content:t.readAt?"Mark as unread":"Mark as read"})]})]})},t.id))]})}),e(r.Footer,{asChild:!0,children:e(n,{as:"p",align:"center",color:"accent",variant:"tertiary",size:1,children:"Powered by DashX"})})]})]})})};var B=C;export{B as default};
2
+ //# sourceMappingURL=NotificationBell.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/widgets/NotificationBell.tsx"],
4
+ "sourcesContent": ["import { intlFormatDistance } from 'date-fns';\n\nimport { useInApp } from '../hooks/index.js';\nimport { Button, Card, Flex, Heading, Popover, Text, Theme, Tooltip } from '../components';\nimport { Inbox, Mail, MailOpen, X } from '../icons/index.js';\n\nconst NotificationBell = () => {\n let {\n markNotificationAsRead,\n markNotificationAsUnread,\n notifications,\n unreadNotificationsCount,\n } = useInApp();\n\n return (\n <Theme>\n <Popover.Root>\n <Tooltip.Root>\n <Tooltip.Trigger>\n <Popover.Trigger>\n <Button\n shape=\"square\"\n roundness=\"full\"\n variant={unreadNotificationsCount ? 'fill' : 'ghost'}\n >\n <Inbox />\n </Button>\n </Popover.Trigger>\n </Tooltip.Trigger>\n <Tooltip.Content content=\"Notification\" />\n </Tooltip.Root>\n <Popover.Content spacing=\"large\" width=\"350px\" height=\"450px\">\n <Popover.Header asChild>\n <Flex justify=\"between\" align=\"center\">\n <Heading size={3}>Notifications</Heading>\n <Popover.Close>\n <Button shape=\"square\" roundness=\"full\" variant=\"ghost\" mode=\"subtle\" inset=\"right\">\n <X />\n </Button>\n </Popover.Close>\n </Flex>\n </Popover.Header>\n <Popover.Body>\n <Flex direction=\"column\" gap={1}>\n {notifications.length === 0 && (\n <Flex justify=\"center\" align=\"center\">\n <Text variant=\"tertiary\" size={2}>\n No notifications yet.\n </Text>\n </Flex>\n )}\n {notifications.map((notification) => (\n <Card key={notification.id}>\n <Flex align=\"center\" gap={4} justify=\"between\">\n <Flex direction=\"column\" gap={1}>\n <Text as=\"p\" variant=\"secondary\" weight=\"semibold\" size={2}>\n {notification.renderedContent.body}\n </Text>\n <Text size={1} variant=\"tertiary\">\n {intlFormatDistance(notification.sentAt, new Date())}\n </Text>\n </Flex>\n <Tooltip.Root>\n <Tooltip.Trigger>\n <Button\n shape=\"square\"\n variant=\"ghost\"\n roundness=\"full\"\n mode={notification.readAt ? 'subtle' : 'distinct'}\n onPress={() => {\n if (notification.readAt) {\n markNotificationAsUnread(notification.id);\n } else {\n markNotificationAsRead(notification.id);\n }\n }}\n >\n {notification.readAt ? <MailOpen /> : <Mail />}\n </Button>\n </Tooltip.Trigger>\n <Tooltip.Content\n content={notification.readAt ? 'Mark as unread' : 'Mark as read'}\n />\n </Tooltip.Root>\n </Flex>\n </Card>\n ))}\n </Flex>\n </Popover.Body>\n <Popover.Footer asChild>\n <Text as=\"p\" align=\"center\" color=\"accent\" variant=\"tertiary\" size={1}>\n Powered by DashX\n </Text>\n </Popover.Footer>\n </Popover.Content>\n </Popover.Root>\n </Theme>\n );\n};\n\nexport default NotificationBell;\n"],
5
+ "mappings": "AAiBQ,OAQQ,OAAAA,EARR,QAAAC,MAAA,oBAjBR,OAAS,sBAAAC,MAA0B,WAEnC,OAAS,YAAAC,MAAgB,oBACzB,OAAS,UAAAC,EAAQ,QAAAC,EAAM,QAAAC,EAAM,WAAAC,EAAS,WAAAC,EAAS,QAAAC,EAAM,SAAAC,EAAO,WAAAC,MAAe,gBAC3E,OAAS,SAAAC,EAAO,QAAAC,EAAM,YAAAC,EAAU,KAAAC,MAAS,oBAEzC,MAAMC,EAAmB,IAAM,CAC7B,GAAI,CACF,uBAAAC,EACA,yBAAAC,EACA,cAAAC,EACA,yBAAAC,CACF,EAAIjB,EAAS,EAEb,OACEH,EAACU,EAAA,CACC,SAAAT,EAACO,EAAQ,KAAR,CACC,UAAAP,EAACU,EAAQ,KAAR,CACC,UAAAX,EAACW,EAAQ,QAAR,CACC,SAAAX,EAACQ,EAAQ,QAAR,CACC,SAAAR,EAACI,EAAA,CACC,MAAM,SACN,UAAU,OACV,QAASgB,EAA2B,OAAS,QAE7C,SAAApB,EAACY,EAAA,EAAM,EACT,EACF,EACF,EACAZ,EAACW,EAAQ,QAAR,CAAgB,QAAQ,eAAe,GAC1C,EACAV,EAACO,EAAQ,QAAR,CAAgB,QAAQ,QAAQ,MAAM,QAAQ,OAAO,QACpD,UAAAR,EAACQ,EAAQ,OAAR,CAAe,QAAO,GACrB,SAAAP,EAACK,EAAA,CAAK,QAAQ,UAAU,MAAM,SAC5B,UAAAN,EAACO,EAAA,CAAQ,KAAM,EAAG,yBAAa,EAC/BP,EAACQ,EAAQ,M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AAI,MAAM,SAAS,MAAM,SAAS,QAAQ,WAAW,KAAM,EAAG,4BAEvE,EACF,GACF,GACF,EACF,CAEJ,EAEA,IAAOa,EAAQN",
6
+ "names": ["jsx", "jsxs", "intlFormatDistance", "useInApp", "Button", "Card", "Flex", "Heading", "Popover", "Text", "Theme", "Tooltip", "Inbox", "Mail", "MailOpen", "X", "NotificationBell", "markNotificationAsRead", "markNotificationAsUnread", "notifications", "unreadNotificationsCount", "notification", "NotificationBell_default"]
7
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dashx/react",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
4
4
  "license": "UNLICENSED",
5
5
  "type": "commonjs",
6
6
  "main": "./dist/cjs/index.js",
@@ -75,7 +75,7 @@
75
75
  "clean": "rm -rf .turbo node_modules dist tokens layout *.css"
76
76
  },
77
77
  "dependencies": {
78
- "@dashx/browser": "^0.8.0",
78
+ "@dashx/browser": "^0.8.2",
79
79
  "@radix-ui/colors": "^3.0.0",
80
80
  "@radix-ui/primitive": "^1.1.3",
81
81
  "@radix-ui/react-accessible-icon": "^1.1.8",
@@ -3,4 +3,6 @@ export { default as useAgent } from './use-agent.js';
3
3
  export { default as useDashXProvider } from './use-dashx-provider.js';
4
4
  export { default as useInApp } from './use-in-app.js';
5
5
  export { default as useInAppChat } from './use-in-app-chat.js';
6
+ export { default as useInAppChatNotifications } from './use-in-app-chat-notifications.js';
7
+ export type { InAppChatNotificationOptions } from './use-in-app-chat-notifications.js';
6
8
  export { default as useProductRelease } from './use-product-release.js';
@@ -0,0 +1,117 @@
1
+ import { useCallback, useRef } from 'react';
2
+ import type { InAppChatMessageData } from '@dashx/browser';
3
+
4
+ import useDashXProvider from './use-dashx-provider.js';
5
+
6
+ type InAppChatNotificationOptions = {
7
+ // Notification title. Defaults to 'New message'.
8
+ title?: string;
9
+ // Icon URL shown in the notification.
10
+ icon?: string;
11
+ // Custom body text from the inbound message; defaults to the message text.
12
+ renderBody?: (message: InAppChatMessageData) => string;
13
+ // When to request notification permission. 'firstOpen' (the default for the
14
+ // launcher) requests it the first time the visitor opens chat — a real user
15
+ // gesture, which browsers require for a non-penalized prompt. 'manual' never
16
+ // auto-requests (use for always-visible surfaces, where the embedder drives
17
+ // the prompt via the returned `requestPermission`).
18
+ requestPermissionOn?: 'firstOpen' | 'manual';
19
+ };
20
+
21
+ type UseInAppChatNotificationsProps = {
22
+ // Whether the chat surface is currently open/visible. Combined with tab
23
+ // visibility + window focus to decide if the visitor is actively looking at
24
+ // chat (in which case we don't notify).
25
+ isOpen: boolean;
26
+ // `false` disables notifications entirely.
27
+ enabled?: boolean;
28
+ options?: InAppChatNotificationOptions;
29
+ // Invoked when the visitor clicks a notification — focus is handled by the
30
+ // SDK; this opens the chat panel.
31
+ onActivate?: () => void;
32
+ };
33
+
34
+ const textFromContent = (content: any): string => {
35
+ if (typeof content === 'string') return content;
36
+ return content?.text ?? content?.body ?? '';
37
+ };
38
+
39
+ /**
40
+ * Foreground browser notifications for incoming In-App Chat messages. Returns a
41
+ * `handleInboundMessage` to pass as `useInAppChat`'s `onInboundMessage`; it
42
+ * fires a notification only for agent/AI replies that arrive while the chat
43
+ * isn't focused (panel closed, or tab hidden/unfocused) and only once the
44
+ * visitor has granted permission.
45
+ */
46
+ const useInAppChatNotifications = ({
47
+ isOpen,
48
+ enabled = true,
49
+ options,
50
+ onActivate,
51
+ }: UseInAppChatNotificationsProps) => {
52
+ const dashX = useDashXProvider();
53
+
54
+ // Latest values for the message handler, so it stays referentially stable
55
+ // (it's wired into the chat hook's subscription).
56
+ const isOpenRef = useRef(isOpen);
57
+ isOpenRef.current = isOpen;
58
+ const enabledRef = useRef(enabled);
59
+ enabledRef.current = enabled;
60
+ const optionsRef = useRef(options);
61
+ optionsRef.current = options;
62
+ const onActivateRef = useRef(onActivate);
63
+ onActivateRef.current = onActivate;
64
+
65
+ const isChatFocused = (): boolean => {
66
+ if (!isOpenRef.current) return false;
67
+ if (typeof document === 'undefined') return false;
68
+ if (document.hidden) return false;
69
+ if (typeof document.hasFocus === 'function' && !document.hasFocus()) return false;
70
+ return true;
71
+ };
72
+
73
+ const handleInboundMessage = useCallback(
74
+ (message: InAppChatMessageData) => {
75
+ if (!enabledRef.current) return;
76
+ // Agent/AI replies only — never the visitor's own echoed message.
77
+ if ((message.aiRole ?? '').toUpperCase() === 'USER') return;
78
+ // Don't interrupt a visitor who's actively looking at the chat.
79
+ if (isChatFocused()) return;
80
+
81
+ const body = optionsRef.current?.renderBody?.(message) ?? textFromContent(message.renderedContent);
82
+ if (!body) return;
83
+
84
+ dashX.showInAppChatNotification?.({
85
+ title: optionsRef.current?.title ?? 'New message',
86
+ body,
87
+ icon: optionsRef.current?.icon,
88
+ tag: message.conversationId ? `in_app_chat:${message.conversationId}` : undefined,
89
+ onClick: () => onActivateRef.current?.(),
90
+ });
91
+ },
92
+ [dashX],
93
+ );
94
+
95
+ const requestPermission = useCallback(
96
+ () => dashX.requestNotificationPermission?.() ?? Promise.resolve('denied' as const),
97
+ [dashX],
98
+ );
99
+
100
+ // Call this SYNCHRONOUSLY from the surface's open event (a real user gesture)
101
+ // so the permission prompt lands inside the browser's transient activation
102
+ // window. Requesting from an effect after the click has unwound is
103
+ // ignored/rejected by some browsers. Honors `requestPermissionOn` ('manual'
104
+ // skips it), and is safe to call on every open (no-ops once permission is
105
+ // decided — see Client.requestNotificationPermission).
106
+ const requestPermissionOnOpen = useCallback(() => {
107
+ if (!enabledRef.current) return;
108
+ if ((optionsRef.current?.requestPermissionOn ?? 'firstOpen') !== 'firstOpen') return;
109
+ dashX.requestNotificationPermission?.().catch(() => {});
110
+ }, [dashX]);
111
+
112
+ return { handleInboundMessage, requestPermission, requestPermissionOnOpen };
113
+ };
114
+
115
+ export type { InAppChatNotificationOptions, UseInAppChatNotificationsProps };
116
+
117
+ export default useInAppChatNotifications;
@@ -16,6 +16,15 @@ type UseInAppChatHookProps = {
16
16
  // created (e.g. "Help with order #123"). Sent via `startInAppChatConversation`
17
17
  // with a stable client message id, so it lands exactly once across reopens.
18
18
  initialMessage?: string;
19
+ // When false, the hook is idle: no conversation is started, subscribed, or
20
+ // fetched. Lets `<InAppChatButton>` defer the conversation until the visitor
21
+ // first opens the launcher, while keeping the hook mounted afterwards so its
22
+ // subscription (and thus notifications) survive the panel being closed.
23
+ enabled?: boolean;
24
+ // Invoked once per LIVE inbound message (not for history load / reconnect
25
+ // refetch). Drives browser notifications without having to diff backfilled
26
+ // history against live events.
27
+ onInboundMessage?: (message: InAppChatMessageData) => void;
19
28
  };
20
29
 
21
30
  // UI-level message. `aiRole` distinguishes the visitor from agent/AI replies and
@@ -94,7 +103,7 @@ const mergeMessages = (
94
103
  * this by starting lazily when the visitor opens it, by which point the provider
95
104
  * has applied the token.
96
105
  */
97
- const useInAppChat = ({ identityId, idempotencyKey, initialMessage }: UseInAppChatHookProps): UseInAppChatHookResponse => {
106
+ const useInAppChat = ({ identityId, idempotencyKey, initialMessage, enabled = true, onInboundMessage }: UseInAppChatHookProps): UseInAppChatHookResponse => {
98
107
  const dashX = useDashXProvider();
99
108
  const { isConnected, initializeWebSocket } = useWebSocket();
100
109
 
@@ -108,6 +117,11 @@ const useInAppChat = ({ identityId, idempotencyKey, initialMessage }: UseInAppCh
108
117
  const generationRef = useRef(0);
109
118
  const conversationIdRef = useRef<string | null>(null);
110
119
 
120
+ // Latest live-message callback, kept in a ref so changing its identity doesn't
121
+ // tear down and re-create the channel subscription.
122
+ const onInboundMessageRef = useRef(onInboundMessage);
123
+ onInboundMessageRef.current = onInboundMessage;
124
+
111
125
  const appendMessages = useCallback((incoming: InAppChatMessage[]) => {
112
126
  setMessages((prev) => mergeMessages(prev, incoming));
113
127
  }, []);
@@ -118,10 +132,18 @@ const useInAppChat = ({ identityId, idempotencyKey, initialMessage }: UseInAppCh
118
132
 
119
133
  setConversationId(null);
120
134
  setMessages([]);
121
- setIsLoading(true);
122
135
  setError(null);
123
136
  conversationIdRef.current = null;
124
137
 
138
+ // Idle until enabled (e.g. before the launcher's first open): don't create a
139
+ // conversation, subscribe, or fetch.
140
+ if (!enabled) {
141
+ setIsLoading(false);
142
+ return () => { generationRef.current += 1; };
143
+ }
144
+
145
+ setIsLoading(true);
146
+
125
147
  // Ensure the WS exists (idempotent — returns early if already created).
126
148
  initializeWebSocket();
127
149
 
@@ -159,7 +181,12 @@ const useInAppChat = ({ identityId, idempotencyKey, initialMessage }: UseInAppCh
159
181
  const subscription = dashX.subscribeToChannel(
160
182
  `${CHAT_CHANNEL_PREFIX}${convId}`,
161
183
  (event) => {
162
- if (!isStale()) appendMessages([toUiMessage(event)]);
184
+ if (isStale()) return;
185
+ appendMessages([toUiMessage(event)]);
186
+ // LIVE messages only — history load / reconnect refetch go through
187
+ // `refetchHistory`, so notification consumers never fire for
188
+ // backfilled messages.
189
+ onInboundMessageRef.current?.(event);
163
190
  },
164
191
  {
165
192
  onReconnectAck: () => {
@@ -196,7 +223,7 @@ const useInAppChat = ({ identityId, idempotencyKey, initialMessage }: UseInAppCh
196
223
  generationRef.current += 1;
197
224
  unsubscribe?.();
198
225
  };
199
- }, [dashX, identityId, idempotencyKey, initialMessage, initializeWebSocket, appendMessages]);
226
+ }, [dashX, identityId, idempotencyKey, initialMessage, enabled, initializeWebSocket, appendMessages]);
200
227
 
201
228
  // Synchronous on purpose: it returns `true` the moment the message is optimistically
202
229
  // queued and runs the network send in the background. The caller clears the composer
@@ -11,6 +11,9 @@ import useInAppChat, {
11
11
  type UseInAppChatHookProps,
12
12
  type UseInAppChatHookResponse,
13
13
  } from '../hooks/use-in-app-chat.js';
14
+ import useInAppChatNotifications, {
15
+ type InAppChatNotificationOptions,
16
+ } from '../hooks/use-in-app-chat-notifications.js';
14
17
 
15
18
  type InAppChatProps = UseInAppChatHookResponse & {
16
19
  withChatHeader?: boolean;
@@ -77,7 +80,7 @@ const InAppChat = ({
77
80
  )}
78
81
 
79
82
  <Flex direction="column" className="grow overflow-auto bg-gray-50">
80
- <ScrollArea.Root ref={scrollAreaRef} className="h-full grow-1 p-6">
83
+ <ScrollArea.Root ref={scrollAreaRef} className="h-full grow p-6">
81
84
  <ScrollArea.Viewport className="h-full">
82
85
  <Flex direction="column" gap={3}>
83
86
  {messages.map((message) => (
@@ -120,7 +123,7 @@ const InAppChat = ({
120
123
 
121
124
  <div className="shrink-0 grow-0 border-t border-t-gray-400/40">
122
125
  <Flex gap={2} align="end" className="w-full">
123
- <div className="w-full [&_textarea]:!border-none [&_textarea]:!outline-none">
126
+ <div className="w-full [&_textarea]:border-none! [&_textarea]:outline-none!">
124
127
  <TextArea
125
128
  aria-label="message"
126
129
  size="extralarge"
@@ -151,10 +154,35 @@ const InAppChat = ({
151
154
  );
152
155
  };
153
156
 
154
- type InAppChatWrapperProps = Omit<InAppChatProps, keyof UseInAppChatHookResponse> & UseInAppChatHookProps;
157
+ type InAppChatWrapperProps = Omit<InAppChatProps, keyof UseInAppChatHookResponse>
158
+ & Omit<UseInAppChatHookProps, 'enabled' | 'onInboundMessage'>
159
+ & {
160
+ // Foreground browser notifications for incoming agent/AI messages while the
161
+ // chat isn't focused. `false` disables; an object customizes title/icon/body.
162
+ // Default: enabled but silent until permission is granted (this always-visible
163
+ // surface never auto-prompts — call `Client.requestNotificationPermission()`
164
+ // from your own UI, or use `<InAppChatButton>` which prompts on first open).
165
+ notifications?: boolean | InAppChatNotificationOptions;
166
+ };
155
167
 
156
- const InAppChatWrapper = ({ identityId, idempotencyKey, initialMessage, ...props }: InAppChatWrapperProps) => {
157
- const chat = useInAppChat({ identityId, idempotencyKey, initialMessage });
168
+ const InAppChatWrapper = ({ identityId, idempotencyKey, initialMessage, notifications = true, ...props }: InAppChatWrapperProps) => {
169
+ // Always-visible surface: treat as "open" and gate notifications on tab
170
+ // visibility/focus only. No launcher gesture exists here, so default to
171
+ // 'manual' permission (auto-requesting would prompt on mount).
172
+ const notifier = useInAppChatNotifications({
173
+ isOpen: true,
174
+ enabled: notifications !== false,
175
+ options: {
176
+ requestPermissionOn: 'manual',
177
+ ...(typeof notifications === 'object' ? notifications : undefined),
178
+ },
179
+ });
180
+ const chat = useInAppChat({
181
+ identityId,
182
+ idempotencyKey,
183
+ initialMessage,
184
+ onInboundMessage: notifier.handleInboundMessage,
185
+ });
158
186
  return <InAppChat {...chat} {...props} />;
159
187
  };
160
188