@dashx/react 0.3.7 → 0.4.1
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/CHANGELOG.md +46 -0
- package/dist/cjs/hooks/use-in-app-chat-notifications.d.ts +1 -1
- package/dist/cjs/hooks/use-in-app-chat-notifications.js +1 -1
- package/dist/cjs/hooks/use-in-app-chat-notifications.js.map +2 -2
- package/dist/cjs/hooks/use-in-app-chat.d.ts +15 -13
- package/dist/cjs/hooks/use-in-app-chat.js +1 -1
- package/dist/cjs/hooks/use-in-app-chat.js.map +3 -3
- package/dist/cjs/widgets/InAppChat.d.ts +1 -1
- package/dist/cjs/widgets/InAppChat.js +1 -1
- package/dist/cjs/widgets/InAppChat.js.map +3 -3
- package/dist/cjs/widgets/InAppChatButton.d.ts +1 -1
- package/dist/cjs/widgets/InAppChatButton.js +1 -1
- package/dist/cjs/widgets/InAppChatButton.js.map +3 -3
- package/dist/esm/hooks/use-in-app-chat-notifications.d.ts +1 -1
- package/dist/esm/hooks/use-in-app-chat-notifications.js +1 -1
- package/dist/esm/hooks/use-in-app-chat-notifications.js.map +2 -2
- package/dist/esm/hooks/use-in-app-chat.d.ts +15 -13
- package/dist/esm/hooks/use-in-app-chat.js +1 -1
- package/dist/esm/hooks/use-in-app-chat.js.map +3 -3
- package/dist/esm/widgets/InAppChat.d.ts +1 -1
- package/dist/esm/widgets/InAppChat.js +1 -1
- package/dist/esm/widgets/InAppChat.js.map +3 -3
- package/dist/esm/widgets/InAppChatButton.d.ts +1 -1
- package/dist/esm/widgets/InAppChatButton.js +1 -1
- package/dist/esm/widgets/InAppChatButton.js.map +3 -3
- package/package.json +2 -2
- package/src/hooks/use-in-app-chat-notifications.ts +5 -3
- package/src/hooks/use-in-app-chat.ts +42 -70
- package/src/widgets/InAppChat.tsx +6 -3
- package/src/widgets/InAppChatButton.tsx +7 -7
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,52 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to `@dashx/react` are documented in this file. Format loosely follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), versions follow [SemVer](https://semver.org/).
|
|
4
4
|
|
|
5
|
+
## [0.4.1] — 2026-08-05
|
|
6
|
+
|
|
7
|
+
### Changed
|
|
8
|
+
|
|
9
|
+
- **`useInAppChatNotifications`'s `onActivate` now receives the message that raised the notification.**
|
|
10
|
+
|
|
11
|
+
```diff
|
|
12
|
+
- onActivate?: () => void
|
|
13
|
+
+ onActivate?: (message: InAppChatMessageData) => void
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
Notifications are tagged per conversation, so a surface watching more than one thread could raise several at once — but the old zero-argument callback gave the handler no way to tell them apart, and it closed over whichever message arrived last. Clicking an older notification opened the wrong conversation.
|
|
17
|
+
|
|
18
|
+
**Backward compatible.** A `() => void` handler is still assignable and still behaves as before; take the parameter only if you need to route by `message.conversationId`. `InAppChatMessageData` is imported from `@dashx/browser`, same as the existing `renderBody` option on this hook.
|
|
19
|
+
|
|
20
|
+
## [0.4.0] — 2026-07-29
|
|
21
|
+
|
|
22
|
+
### Changed
|
|
23
|
+
|
|
24
|
+
- **BREAKING — In-App Chat no longer creates conversations; the caller supplies one.** `useInAppChat` and both widgets participate in an EXISTING conversation:
|
|
25
|
+
|
|
26
|
+
```diff
|
|
27
|
+
- useInAppChat({ identityId, idempotencyKey, initialMessage? })
|
|
28
|
+
+ useInAppChat({ identityId, conversationId })
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
`idempotencyKey` and `initialMessage` are gone, along with the create-on-mount behaviour. `<InAppChat>` and `<InAppChatButton>` take a required `conversationId` prop in place of `idempotencyKey`/`initialMessage`.
|
|
32
|
+
|
|
33
|
+
**Why.** Creating a chat is now server-only in DashX: identity-token callers are rejected outright, and the operation requires an `accountUid` naming the visitor — a claim no browser should be able to make. The conversation's `data`/`issueProperties` are metadata the agent console trusts, so they must be derived server-side. `@dashx/browser@0.10.0` therefore removes `startInAppChatConversation`, which is what this hook used.
|
|
34
|
+
|
|
35
|
+
**Migration.** Create the conversation in your backend (for JVM services, `dashx-java` ≥ 1.5.0 exposes `DashX.startInAppChatConversation(input)`), return the id to your client, and pass it in:
|
|
36
|
+
|
|
37
|
+
```tsx
|
|
38
|
+
const { conversationId } = useMyBackendChatSession(); // your endpoint
|
|
39
|
+
<InAppChatButton identityId="<chat-identity-id>" conversationId={conversationId} />
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
`conversationId` accepts `null` while you're still fetching it — the hook stays idle (no subscription, no history fetch) rather than guessing, so you can render the widget unconditionally.
|
|
43
|
+
- **`conversationId` is no longer returned from the hook.** The caller now owns it, so echoing it back was noise. Everything else in the response is unchanged: `messages`, `isLoading`, `isConnected`, `error`, `sendMessage`.
|
|
44
|
+
- `sendMessage(text)` returns `false` when there is no `conversationId` yet (or the hook is disabled) — same contract as before, so callers that keep the composer populated on `false` need no change.
|
|
45
|
+
- **`@dashx/browser` dependency raised to `^0.10.0`** (a regular `dependencies` entry, as before), which is the release that removes the creation method.
|
|
46
|
+
|
|
47
|
+
### Unchanged
|
|
48
|
+
|
|
49
|
+
- History fetch, realtime subscribe, optimistic send + reconciliation, reconnect refetch, and the notification hook all behave exactly as before. `<InAppChatButton>` still activates lazily on first open, so a launcher the visitor never opens does no chat work.
|
|
50
|
+
|
|
5
51
|
## [0.3.0] — 2026-06-18
|
|
6
52
|
|
|
7
53
|
### Added
|
|
@@ -9,7 +9,7 @@ type UseInAppChatNotificationsProps = {
|
|
|
9
9
|
isOpen: boolean;
|
|
10
10
|
enabled?: boolean;
|
|
11
11
|
options?: InAppChatNotificationOptions;
|
|
12
|
-
onActivate?: () => void;
|
|
12
|
+
onActivate?: (message: InAppChatMessageData) => void;
|
|
13
13
|
};
|
|
14
14
|
/**
|
|
15
15
|
* Foreground browser notifications for incoming In-App Chat messages. Returns a
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var y=Object.create;var p=Object.defineProperty;var N=Object.getOwnPropertyDescriptor;var O=Object.getOwnPropertyNames;var P=Object.getPrototypeOf,b=Object.prototype.hasOwnProperty;var g=(t,e)=>{for(var r in e)p(t,r,{get:e[r],enumerable:!0})},h=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of O(e))!b.call(t,n)&&n!==r&&p(t,n,{get:()=>e[n],enumerable:!(s=N(e,n))||s.enumerable});return t};var R=(t,e,r)=>(r=t!=null?y(P(t)):{},h(e||!t||!t.__esModule?p(r,"default",{value:t,enumerable:!0}):r,t)),q=t=>h(p({},"__esModule",{value:!0}),t);var M={};g(M,{default:()=>D});module.exports=q(M);var o=require("react"),l=R(require("./use-dashx-provider.js"));const v=t=>typeof t=="string"?t:t?.text??t?.body??"",x=({isOpen:t,enabled:e=!0,options:r,onActivate:s})=>{const n=(0,l.default)(),u=(0,o.useRef)(t);u.current=t;const c=(0,o.useRef)(e);c.current=e;const a=(0,o.useRef)(r);a.current=r;const f=(0,o.useRef)(s);f.current=s;const C=()=>!(!u.current||typeof document>"u"||document.hidden||typeof document.hasFocus=="function"&&!document.hasFocus()),m=(0,o.useCallback)(i=>{if(!c.current||(i.aiRole??"").toUpperCase()==="USER"||C())return;const d=a.current?.renderBody?.(i)??v(i.renderedContent);d&&n.showInAppChatNotification?.({title:a.current?.title??"New message",body:d,icon:a.current?.icon,tag:i.conversationId?`in_app_chat:${i.conversationId}`:void 0,onClick:()=>f.current?.(i)})},[n]),I=(0,o.useCallback)(()=>n.requestNotificationPermission?.()??Promise.resolve("denied"),[n]),A=(0,o.useCallback)(()=>{c.current&&(a.current?.requestPermissionOn??"firstOpen")==="firstOpen"&&n.requestNotificationPermission?.().catch(()=>{})},[n]);return{handleInboundMessage:m,requestPermission:I,requestPermissionOnOpen:A}};var D=x;
|
|
2
2
|
//# sourceMappingURL=use-in-app-chat-notifications.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/hooks/use-in-app-chat-notifications.ts"],
|
|
4
|
-
"sourcesContent": ["import { useCallback, useRef } from 'react';\nimport type { InAppChatMessageData } from '@dashx/browser';\n\nimport useDashXProvider from './use-dashx-provider.js';\n\ntype InAppChatNotificationOptions = {\n // Notification title. Defaults to 'New message'.\n title?: string;\n // Icon URL shown in the notification.\n icon?: string;\n // Custom body text from the inbound message; defaults to the message text.\n renderBody?: (message: InAppChatMessageData) => string;\n // When to request notification permission. 'firstOpen' (the default for the\n // launcher) requests it the first time the visitor opens chat \u2014 a real user\n // gesture, which browsers require for a non-penalized prompt. 'manual' never\n // auto-requests (use for always-visible surfaces, where the embedder drives\n // the prompt via the returned `requestPermission`).\n requestPermissionOn?: 'firstOpen' | 'manual';\n};\n\ntype UseInAppChatNotificationsProps = {\n // Whether the chat surface is currently open/visible. Combined with tab\n // visibility + window focus to decide if the visitor is actively looking at\n // chat (in which case we don't notify).\n isOpen: boolean;\n // `false` disables notifications entirely.\n enabled?: boolean;\n options?: InAppChatNotificationOptions;\n // Invoked when the visitor clicks a notification \u2014 focus is handled by the\n // SDK; this opens the chat panel.\n onActivate?: () => void;\n};\n\nconst textFromContent = (content: any): string => {\n if (typeof content === 'string') return content;\n return content?.text ?? content?.body ?? '';\n};\n\n/**\n * Foreground browser notifications for incoming In-App Chat messages. Returns a\n * `handleInboundMessage` to pass as `useInAppChat`'s `onInboundMessage`; it\n * fires a notification only for agent/AI replies that arrive while the chat\n * isn't focused (panel closed, or tab hidden/unfocused) and only once the\n * visitor has granted permission.\n */\nconst useInAppChatNotifications = ({\n isOpen,\n enabled = true,\n options,\n onActivate,\n}: UseInAppChatNotificationsProps) => {\n const dashX = useDashXProvider();\n\n // Latest values for the message handler, so it stays referentially stable\n // (it's wired into the chat hook's subscription).\n const isOpenRef = useRef(isOpen);\n isOpenRef.current = isOpen;\n const enabledRef = useRef(enabled);\n enabledRef.current = enabled;\n const optionsRef = useRef(options);\n optionsRef.current = options;\n const onActivateRef = useRef(onActivate);\n onActivateRef.current = onActivate;\n\n const isChatFocused = (): boolean => {\n if (!isOpenRef.current) return false;\n if (typeof document === 'undefined') return false;\n if (document.hidden) return false;\n if (typeof document.hasFocus === 'function' && !document.hasFocus()) return false;\n return true;\n };\n\n const handleInboundMessage = useCallback(\n (message: InAppChatMessageData) => {\n if (!enabledRef.current) return;\n // Agent/AI replies only \u2014 never the visitor's own echoed message.\n if ((message.aiRole ?? '').toUpperCase() === 'USER') return;\n // Don't interrupt a visitor who's actively looking at the chat.\n if (isChatFocused()) return;\n\n const body = optionsRef.current?.renderBody?.(message) ?? textFromContent(message.renderedContent);\n if (!body) return;\n\n dashX.showInAppChatNotification?.({\n title: optionsRef.current?.title ?? 'New message',\n body,\n icon: optionsRef.current?.icon,\n tag: message.conversationId ? `in_app_chat:${message.conversationId}` : undefined,\n onClick: () => onActivateRef.current?.(),\n });\n },\n [dashX],\n );\n\n const requestPermission = useCallback(\n () => dashX.requestNotificationPermission?.() ?? Promise.resolve('denied' as const),\n [dashX],\n );\n\n // Call this SYNCHRONOUSLY from the surface's open event (a real user gesture)\n // so the permission prompt lands inside the browser's transient activation\n // window. Requesting from an effect after the click has unwound is\n // ignored/rejected by some browsers. Honors `requestPermissionOn` ('manual'\n // skips it), and is safe to call on every open (no-ops once permission is\n // decided \u2014 see Client.requestNotificationPermission).\n const requestPermissionOnOpen = useCallback(() => {\n if (!enabledRef.current) return;\n if ((optionsRef.current?.requestPermissionOn ?? 'firstOpen') !== 'firstOpen') return;\n dashX.requestNotificationPermission?.().catch(() => {});\n }, [dashX]);\n\n return { handleInboundMessage, requestPermission, requestPermissionOnOpen };\n};\n\nexport type { InAppChatNotificationOptions, UseInAppChatNotificationsProps };\n\nexport default useInAppChatNotifications;\n"],
|
|
5
|
-
"mappings": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAoC,iBAGpCC,EAA6B,
|
|
4
|
+
"sourcesContent": ["import { useCallback, useRef } from 'react';\nimport type { InAppChatMessageData } from '@dashx/browser';\n\nimport useDashXProvider from './use-dashx-provider.js';\n\ntype InAppChatNotificationOptions = {\n // Notification title. Defaults to 'New message'.\n title?: string;\n // Icon URL shown in the notification.\n icon?: string;\n // Custom body text from the inbound message; defaults to the message text.\n renderBody?: (message: InAppChatMessageData) => string;\n // When to request notification permission. 'firstOpen' (the default for the\n // launcher) requests it the first time the visitor opens chat \u2014 a real user\n // gesture, which browsers require for a non-penalized prompt. 'manual' never\n // auto-requests (use for always-visible surfaces, where the embedder drives\n // the prompt via the returned `requestPermission`).\n requestPermissionOn?: 'firstOpen' | 'manual';\n};\n\ntype UseInAppChatNotificationsProps = {\n // Whether the chat surface is currently open/visible. Combined with tab\n // visibility + window focus to decide if the visitor is actively looking at\n // chat (in which case we don't notify).\n isOpen: boolean;\n // `false` disables notifications entirely.\n enabled?: boolean;\n options?: InAppChatNotificationOptions;\n // Invoked when the visitor clicks a notification \u2014 focus is handled by the\n // SDK; this opens the chat panel. Receives the message that raised THAT\n // notification, so a surface watching several conversations can open the right\n // one: without it, every notification resolves to whichever arrived last.\n onActivate?: (message: InAppChatMessageData) => void;\n};\n\nconst textFromContent = (content: any): string => {\n if (typeof content === 'string') return content;\n return content?.text ?? content?.body ?? '';\n};\n\n/**\n * Foreground browser notifications for incoming In-App Chat messages. Returns a\n * `handleInboundMessage` to pass as `useInAppChat`'s `onInboundMessage`; it\n * fires a notification only for agent/AI replies that arrive while the chat\n * isn't focused (panel closed, or tab hidden/unfocused) and only once the\n * visitor has granted permission.\n */\nconst useInAppChatNotifications = ({\n isOpen,\n enabled = true,\n options,\n onActivate,\n}: UseInAppChatNotificationsProps) => {\n const dashX = useDashXProvider();\n\n // Latest values for the message handler, so it stays referentially stable\n // (it's wired into the chat hook's subscription).\n const isOpenRef = useRef(isOpen);\n isOpenRef.current = isOpen;\n const enabledRef = useRef(enabled);\n enabledRef.current = enabled;\n const optionsRef = useRef(options);\n optionsRef.current = options;\n const onActivateRef = useRef(onActivate);\n onActivateRef.current = onActivate;\n\n const isChatFocused = (): boolean => {\n if (!isOpenRef.current) return false;\n if (typeof document === 'undefined') return false;\n if (document.hidden) return false;\n if (typeof document.hasFocus === 'function' && !document.hasFocus()) return false;\n return true;\n };\n\n const handleInboundMessage = useCallback(\n (message: InAppChatMessageData) => {\n if (!enabledRef.current) return;\n // Agent/AI replies only \u2014 never the visitor's own echoed message.\n if ((message.aiRole ?? '').toUpperCase() === 'USER') return;\n // Don't interrupt a visitor who's actively looking at the chat.\n if (isChatFocused()) return;\n\n const body = optionsRef.current?.renderBody?.(message) ?? textFromContent(message.renderedContent);\n if (!body) return;\n\n dashX.showInAppChatNotification?.({\n title: optionsRef.current?.title ?? 'New message',\n body,\n icon: optionsRef.current?.icon,\n tag: message.conversationId ? `in_app_chat:${message.conversationId}` : undefined,\n onClick: () => onActivateRef.current?.(message),\n });\n },\n [dashX],\n );\n\n const requestPermission = useCallback(\n () => dashX.requestNotificationPermission?.() ?? Promise.resolve('denied' as const),\n [dashX],\n );\n\n // Call this SYNCHRONOUSLY from the surface's open event (a real user gesture)\n // so the permission prompt lands inside the browser's transient activation\n // window. Requesting from an effect after the click has unwound is\n // ignored/rejected by some browsers. Honors `requestPermissionOn` ('manual'\n // skips it), and is safe to call on every open (no-ops once permission is\n // decided \u2014 see Client.requestNotificationPermission).\n const requestPermissionOnOpen = useCallback(() => {\n if (!enabledRef.current) return;\n if ((optionsRef.current?.requestPermissionOn ?? 'firstOpen') !== 'firstOpen') return;\n dashX.requestNotificationPermission?.().catch(() => {});\n }, [dashX]);\n\n return { handleInboundMessage, requestPermission, requestPermissionOnOpen };\n};\n\nexport type { InAppChatNotificationOptions, UseInAppChatNotificationsProps };\n\nexport default useInAppChatNotifications;\n"],
|
|
5
|
+
"mappings": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAoC,iBAGpCC,EAA6B,sCAgC7B,MAAMC,EAAmBC,GACnB,OAAOA,GAAY,SAAiBA,EACjCA,GAAS,MAAQA,GAAS,MAAQ,GAUrCC,EAA4B,CAAC,CACjC,OAAAC,EACA,QAAAC,EAAU,GACV,QAAAC,EACA,WAAAC,CACF,IAAsC,CACpC,MAAMC,KAAQ,EAAAC,SAAiB,EAIzBC,KAAY,UAAON,CAAM,EAC/BM,EAAU,QAAUN,EACpB,MAAMO,KAAa,UAAON,CAAO,EACjCM,EAAW,QAAUN,EACrB,MAAMO,KAAa,UAAON,CAAO,EACjCM,EAAW,QAAUN,EACrB,MAAMO,KAAgB,UAAON,CAAU,EACvCM,EAAc,QAAUN,EAExB,MAAMO,EAAgB,IAChB,GAACJ,EAAU,SACX,OAAO,SAAa,KACpB,SAAS,QACT,OAAO,SAAS,UAAa,YAAc,CAAC,SAAS,SAAS,GAI9DK,KAAuB,eAC1BC,GAAkC,CAKjC,GAJI,CAACL,EAAW,UAEXK,EAAQ,QAAU,IAAI,YAAY,IAAM,QAEzCF,EAAc,EAAG,OAErB,MAAMG,EAAOL,EAAW,SAAS,aAAaI,CAAO,GAAKf,EAAgBe,EAAQ,eAAe,EAC5FC,GAELT,EAAM,4BAA4B,CAChC,MAAOI,EAAW,SAAS,OAAS,cACpC,KAAAK,EACA,KAAML,EAAW,SAAS,KAC1B,IAAKI,EAAQ,eAAiB,eAAeA,EAAQ,cAAc,GAAK,OACxE,QAAS,IAAMH,EAAc,UAAUG,CAAO,CAChD,CAAC,CACH,EACA,CAACR,CAAK,CACR,EAEMU,KAAoB,eACxB,IAAMV,EAAM,gCAAgC,GAAK,QAAQ,QAAQ,QAAiB,EAClF,CAACA,CAAK,CACR,EAQMW,KAA0B,eAAY,IAAM,CAC3CR,EAAW,UACXC,EAAW,SAAS,qBAAuB,eAAiB,aACjEJ,EAAM,gCAAgC,EAAE,MAAM,IAAM,CAAC,CAAC,CACxD,EAAG,CAACA,CAAK,CAAC,EAEV,MAAO,CAAE,qBAAAO,EAAsB,kBAAAG,EAAmB,wBAAAC,CAAwB,CAC5E,EAIA,IAAOtB,EAAQM",
|
|
6
6
|
"names": ["use_in_app_chat_notifications_exports", "__export", "use_in_app_chat_notifications_default", "__toCommonJS", "import_react", "import_use_dashx_provider", "textFromContent", "content", "useInAppChatNotifications", "isOpen", "enabled", "options", "onActivate", "dashX", "useDashXProvider", "isOpenRef", "enabledRef", "optionsRef", "onActivateRef", "isChatFocused", "handleInboundMessage", "message", "body", "requestPermission", "requestPermissionOnOpen"]
|
|
7
7
|
}
|
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
import type { InAppChatMessageData } from '@dashx/browser';
|
|
2
2
|
type UseInAppChatHookProps = {
|
|
3
3
|
identityId: string;
|
|
4
|
-
|
|
5
|
-
initialMessage?: string;
|
|
4
|
+
conversationId: string | null;
|
|
6
5
|
enabled?: boolean;
|
|
7
6
|
onInboundMessage?: (message: InAppChatMessageData) => void;
|
|
8
7
|
};
|
|
@@ -16,7 +15,6 @@ type InAppChatMessage = {
|
|
|
16
15
|
isPending?: boolean;
|
|
17
16
|
};
|
|
18
17
|
type UseInAppChatHookResponse = {
|
|
19
|
-
conversationId: string | null;
|
|
20
18
|
messages: InAppChatMessage[];
|
|
21
19
|
isLoading: boolean;
|
|
22
20
|
isConnected: boolean;
|
|
@@ -24,18 +22,22 @@ type UseInAppChatHookResponse = {
|
|
|
24
22
|
sendMessage: (text: string) => boolean;
|
|
25
23
|
};
|
|
26
24
|
/**
|
|
27
|
-
* Two-way InApp Chat
|
|
25
|
+
* Two-way InApp Chat within an EXISTING conversation.
|
|
26
|
+
*
|
|
27
|
+
* This hook participates; it never creates. Creating a conversation is a
|
|
28
|
+
* server-only operation — DashX rejects identity-token callers and requires an
|
|
29
|
+
* `accountUid` the browser has no authority to assert, and the conversation's
|
|
30
|
+
* metadata must be derived server-side. So the flow is: your backend creates the
|
|
31
|
+
* conversation (e.g. via `dashx-java`) and returns its id; you pass that id here.
|
|
28
32
|
*
|
|
29
33
|
* PREREQUISITE: the surrounding `<DashXProvider>` must already have a valid
|
|
30
|
-
* `identityToken` (and matching `identityUid`).
|
|
31
|
-
* identity-token auth — if
|
|
32
|
-
* are rejected and the hook surfaces an
|
|
33
|
-
* a token arrives later (its inputs are `identityId`/`
|
|
34
|
-
* visitor token), so only render the chat once `identityToken` is available —
|
|
35
|
-
*
|
|
36
|
-
* this by starting lazily when the visitor opens it, by which point the provider
|
|
37
|
-
* has applied the token.
|
|
34
|
+
* `identityToken` (and matching `identityUid`). Fetching history, sending, and
|
|
35
|
+
* subscribing all require identity-token auth — if they run before an identity is
|
|
36
|
+
* resolved they are rejected and the hook surfaces an error. It does NOT auto-retry
|
|
37
|
+
* when a token arrives later (its inputs are `identityId`/`conversationId`, not the
|
|
38
|
+
* visitor token), so only render the chat once `identityToken` is available — e.g.
|
|
39
|
+
* `{identityToken && <InAppChat … />}`.
|
|
38
40
|
*/
|
|
39
|
-
declare const useInAppChat: ({ identityId,
|
|
41
|
+
declare const useInAppChat: ({ identityId, conversationId, enabled, onInboundMessage }: UseInAppChatHookProps) => UseInAppChatHookResponse;
|
|
40
42
|
export type { UseInAppChatHookProps, UseInAppChatHookResponse, InAppChatMessage };
|
|
41
43
|
export default useInAppChat;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var E=Object.create;var C=Object.defineProperty;var _=Object.getOwnPropertyDescriptor;var q=Object.getOwnPropertyNames;var D=Object.getPrototypeOf,F=Object.prototype.hasOwnProperty;var L=(e,n)=>{for(var s in n)C(e,s,{get:n[s],enumerable:!0})},R=(e,n,s,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let t of q(n))!F.call(e,t)&&t!==s&&C(e,t,{get:()=>n[t],enumerable:!(o=_(n,t))||o.enumerable});return e};var U=(e,n,s)=>(s=e!=null?E(D(e)):{},R(n||!e||!e.__esModule?C(s,"default",{value:e,enumerable:!0}):s,e)),X=e=>R(C({},"__esModule",{value:!0}),e);var O={};L(O,{default:()=>N});module.exports=X(O);var S=U(require("uuid-random")),a=require("react"),k=U(require("./use-dashx-provider.js")),m=require("../providers/DashXProvider.js");const $="in_app_chat:conversation:",M=e=>({id:e.id,externalUid:e.externalUid??null,renderedContent:e.renderedContent,aiRole:e.aiRole??null,createdAt:e.createdAt,turnSeq:e.turnSeq}),v=(e,n)=>{const s=new Map,o=t=>t.externalUid||t.id;return[...e,...n].forEach(t=>{const i=s.get(o(t));(!i||i.isPending)&&s.set(o(t),t)}),[...s.values()].sort((t,i)=>t.createdAt!==i.createdAt?t.createdAt<i.createdAt?-1:1:(t.turnSeq??0)-(i.turnSeq??0))},K=({identityId:e,conversationId:n,enabled:s=!0,onInboundMessage:o})=>{const t=(0,k.default)(),{isConnected:i,initializeWebSocket:I}=(0,m.useWebSocket)(),[H,y]=(0,a.useState)([]),[x,f]=(0,a.useState)(!0),[P,d]=(0,a.useState)(null),p=(0,a.useRef)(0),b=(0,a.useRef)(o);b.current=o;const u=(0,a.useCallback)(c=>{y(r=>v(r,c))},[]);(0,a.useEffect)(()=>{const c=p.current+=1,r=()=>c!==p.current;if(y([]),d(null),!s||!n)return f(!1),()=>{p.current+=1};f(!0),I();let l;return(async()=>{try{const g=async()=>{const A=await t.fetchInAppChatMessages({conversationId:n});r()||u(A.map(M))},h=t.subscribeToChannel(`${$}${n}`,A=>{r()||(u([M(A)]),b.current?.(A))},{onReconnectAck:()=>{r()||(d(null),g().catch(()=>{}))}});l=h.unsubscribe;try{await h.ready}catch{r()||d("Couldn\u2019t connect to live chat. Retrying\u2026");return}if(r())return;await g()}catch{r()||d("Failed to load chat")}finally{r()||f(!1)}})(),()=>{p.current+=1,l?.()}},[t,e,n,s,I,u]);const w=(0,a.useCallback)(c=>{if(!c.trim()||!n||!s)return!1;const r=p.current,l=(0,S.default)(),g={id:l,externalUid:`in_app_chat:${l}`,renderedContent:{text:c},aiRole:"USER",createdAt:new Date().toISOString(),isPending:!0};return u([g]),(async()=>{try{const h=await t.sendInAppChatMessage({conversationId:n,identityId:e,content:{text:c},clientMessageId:l});if(r!==p.current)return;u([M(h)])}catch{r===p.current&&d("Failed to send message")}})(),!0},[t,e,n,s,u]);return{messages:H,isLoading:x,isConnected:i,error:P,sendMessage:w}};var N=K;
|
|
2
2
|
//# sourceMappingURL=use-in-app-chat.js.map
|
|
@@ -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 // 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 // `content` + `clientMessageId` travel together: `StartInAppChatConversationArgs`\n // is a union of \"empty start\" and \"start with a first message\", because the\n // backend rejects metadata with no message to attach it to. The branch must\n // therefore stay OUTSIDE the object literal \u2014 a conditional spread collapses to\n // `content?: \u2026 | undefined` and loses the correlation, matching neither arm.\n //\n // Stable client message id \u2192 the automated message is inserted once, even if the\n // conversation is reopened (the server dedups repeat sends). `-` separator\n // (client ids allow only `[A-Za-z0-9._-]`); the key is truncated so the suffixed\n // id stays within the 1-128 char limit.\n const startArgs = initialMessage\n ? {\n identityId,\n clientIdempotencyKey: idempotencyKey,\n content: { text: initialMessage },\n clientMessageId: `${idempotencyKey.slice(0, 122)}-intro`,\n }\n : { identityId, clientIdempotencyKey: idempotencyKey };\n\n const conversation = await dashX.startInAppChatConversation(startArgs);\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": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAiB,0BACjBC,EAAyD,iBAGzDC,EAA6B,sCAC7BC,EAA6B,
|
|
6
|
-
"names": ["use_in_app_chat_exports", "__export", "use_in_app_chat_default", "__toCommonJS", "import_uuid_random", "import_react", "import_use_dashx_provider", "import_DashXProvider", "CHAT_CHANNEL_PREFIX", "toUiMessage", "message", "mergeMessages", "existing", "incoming", "byKey", "keyOf", "existingForKey", "a", "b", "useInAppChat", "identityId", "
|
|
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 // The conversation to participate in. This hook does NOT create conversations:\n // creating one is server-only (DashX rejects identity-token callers), so your\n // backend creates it and hands you the id. Pass `null` while you don't have one\n // yet \u2014 the hook stays idle rather than guessing.\n conversationId: string | null;\n // When false, the hook is idle: nothing is subscribed or fetched. Lets\n // `<InAppChatButton>` defer the subscription until the visitor first opens the\n // launcher, while keeping the hook mounted afterwards so its subscription (and\n // 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 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 `conversationId`, or disabled). Synchronous so the caller can\n // clear the composer immediately on `true`; callers keep the input populated on\n // `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 within an EXISTING conversation.\n *\n * This hook participates; it never creates. Creating a conversation is a\n * server-only operation \u2014 DashX rejects identity-token callers and requires an\n * `accountUid` the browser has no authority to assert, and the conversation's\n * metadata must be derived server-side. So the flow is: your backend creates the\n * conversation (e.g. via `dashx-java`) and returns its id; you pass that id here.\n *\n * PREREQUISITE: the surrounding `<DashXProvider>` must already have a valid\n * `identityToken` (and matching `identityUid`). Fetching history, sending, and\n * subscribing all require identity-token auth \u2014 if they run before an identity is\n * resolved they are rejected and the hook surfaces an error. It does NOT auto-retry\n * when a token arrives later (its inputs are `identityId`/`conversationId`, not the\n * visitor token), so only render the chat once `identityToken` is available \u2014 e.g.\n * `{identityToken && <InAppChat \u2026 />}`.\n */\nconst useInAppChat = ({ identityId, conversationId, enabled = true, onInboundMessage }: UseInAppChatHookProps): UseInAppChatHookResponse => {\n const dashX = useDashXProvider();\n const { isConnected, initializeWebSocket } = useWebSocket();\n\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/conversation change and on unmount so stale\n // fetch/send resolutions are ignored (the classic React async race).\n const generationRef = useRef(0);\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 setMessages([]);\n setError(null);\n\n // Idle until enabled (e.g. before the launcher's first open) and until the\n // caller has a conversation to join: don't subscribe or fetch.\n if (!enabled || !conversationId) {\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 refetchHistory = async () => {\n const history = await dashX.fetchInAppChatMessages({ conversationId });\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}${conversationId}`,\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 load 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, conversationId, 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 // Not ready (no conversation supplied yet, or the hook is disabled) \u2014 report\n // back so the caller can keep the typed text instead of clearing it on a\n // no-op send.\n if (!text.trim() || !conversationId || !enabled) 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,\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, conversationId, enabled, appendMessages],\n );\n\n return { messages, isLoading, isConnected, error, sendMessage };\n};\n\nexport type { UseInAppChatHookProps, UseInAppChatHookResponse, InAppChatMessage };\n\nexport default useInAppChat;\n"],
|
|
5
|
+
"mappings": "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",
|
|
6
|
+
"names": ["use_in_app_chat_exports", "__export", "use_in_app_chat_default", "__toCommonJS", "import_uuid_random", "import_react", "import_use_dashx_provider", "import_DashXProvider", "CHAT_CHANNEL_PREFIX", "toUiMessage", "message", "mergeMessages", "existing", "incoming", "byKey", "keyOf", "existingForKey", "a", "b", "useInAppChat", "identityId", "conversationId", "enabled", "onInboundMessage", "dashX", "useDashXProvider", "isConnected", "initializeWebSocket", "messages", "setMessages", "isLoading", "setIsLoading", "error", "setError", "generationRef", "onInboundMessageRef", "appendMessages", "prev", "generation", "isStale", "unsubscribe", "refetchHistory", "history", "subscription", "event", "sendMessage", "text", "clientMessageId", "uuid", "optimistic", "serverMessage"]
|
|
7
7
|
}
|
|
@@ -10,7 +10,7 @@ declare const InAppChat: ({ messages, isLoading, error, sendMessage, withChatHea
|
|
|
10
10
|
type InAppChatWrapperProps = Omit<InAppChatProps, keyof UseInAppChatHookResponse> & Omit<UseInAppChatHookProps, 'enabled' | 'onInboundMessage'> & {
|
|
11
11
|
notifications?: boolean | InAppChatNotificationOptions;
|
|
12
12
|
};
|
|
13
|
-
declare const InAppChatWrapper: ({ identityId,
|
|
13
|
+
declare const InAppChatWrapper: ({ identityId, conversationId, notifications, ...props }: InAppChatWrapperProps) => import("react/jsx-runtime").JSX.Element;
|
|
14
14
|
export type { InAppChatProps, InAppChatWrapperProps };
|
|
15
15
|
export { InAppChat };
|
|
16
16
|
export default InAppChatWrapper;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var S=Object.create;var u=Object.defineProperty;var k=Object.getOwnPropertyDescriptor;var H=Object.getOwnPropertyNames;var R=Object.getPrototypeOf,U=Object.prototype.hasOwnProperty;var z=(t,a)=>{for(var r in a)u(t,r,{get:a[r],enumerable:!0})},
|
|
1
|
+
"use strict";var S=Object.create;var u=Object.defineProperty;var k=Object.getOwnPropertyDescriptor;var H=Object.getOwnPropertyNames;var R=Object.getPrototypeOf,U=Object.prototype.hasOwnProperty;var z=(t,a)=>{for(var r in a)u(t,r,{get:a[r],enumerable:!0})},C=(t,a,r,p)=>{if(a&&typeof a=="object"||typeof a=="function")for(let s of H(a))!U.call(t,s)&&s!==r&&u(t,s,{get:()=>a[s],enumerable:!(p=k(a,s))||p.enumerable});return t};var m=(t,a,r)=>(r=t!=null?S(R(t)):{},C(a||!t||!t.__esModule?u(r,"default",{value:t,enumerable:!0}):r,t)),M=t=>C(u({},"__esModule",{value:!0}),t);var B={};z(B,{InAppChat:()=>f,default:()=>K});module.exports=M(B);var e=require("react/jsx-runtime"),l=m(require("@radix-ui/react-scroll-area")),d=require("react"),c=require("lucide-react"),o=require("../components"),g=require("../utils/cn.js"),A=m(require("../hooks/use-auto-scroll.js")),I=m(require("../hooks/use-in-app-chat.js")),v=m(require("../hooks/use-in-app-chat-notifications.js"));const O=t=>{const a=t.renderedContent;return typeof a=="string"?a:a?.text??""},E=t=>t.aiRole?.toUpperCase()==="USER",f=({messages:t,isLoading:a,error:r,sendMessage:p,withChatHeader:s=!1,withPopoverClose:h=!1,borderless:w=!1,title:N="Chat"})=>{const[i,b]=(0,d.useState)(""),{scrollAreaRef:P,scrollToBottom:x}=(0,A.default)();(0,d.useEffect)(()=>{setTimeout(()=>x({smooth:!0}),0)},[t.length,x]);const y=()=>{i.trim()&&p(i)&&b("")},T=n=>{n.key==="Enter"&&!n.shiftKey&&(n.preventDefault(),y())};return(0,e.jsx)(o.Theme,{asChild:!0,children:(0,e.jsxs)(o.Flex,{direction:"column",className:(0,g.cn)("h-full",!w&&"border border-gray-400/40"),children:[s&&(0,e.jsxs)(o.Flex,{align:"center",justify:"between",className:"border-b border-b-gray-400/40 px-6 py-4",children:[(0,e.jsx)(o.Heading,{size:3,children:N}),h&&(0,e.jsx)(o.Popover.Close,{children:(0,e.jsx)(o.Button,{shape:"square",roundness:"full",variant:"ghost",mode:"subtle",inset:"right",children:(0,e.jsx)(c.X,{})})})]}),(0,e.jsx)(o.Flex,{direction:"column",className:"grow overflow-auto bg-gray-50",children:(0,e.jsxs)(l.Root,{ref:P,className:"h-full grow p-6",children:[(0,e.jsx)(l.Viewport,{className:"h-full",children:(0,e.jsxs)(o.Flex,{direction:"column",gap:3,children:[t.map(n=>(0,e.jsx)("div",{className:(0,g.cn)("max-w-[80%] rounded-lg py-2 px-3",E(n)?"bg-accent-600 ml-auto items-end text-white":"bg-gray-200 mr-auto items-start text-gray-900"),children:(0,e.jsx)(o.Text,{as:"p",size:2,children:O(n)})},n.externalUid||n.id)),a&&(0,e.jsx)(o.Text,{as:"p",size:2,className:"mr-auto text-gray-500",children:"Loading\u2026"}),r&&(0,e.jsx)(o.Text,{as:"p",size:2,className:"bg-negative-100 text-negative-900 mx-auto rounded-lg py-2 px-3",children:r})]})}),(0,e.jsx)(l.Scrollbar,{orientation:"vertical",className:"w-1 bg-gray-200 opacity-50",children:(0,e.jsx)(l.Thumb,{className:"flex-1 rounded-2xl bg-gray-400"})}),(0,e.jsx)(l.Corner,{})]})}),(0,e.jsx)("div",{className:"shrink-0 grow-0 border-t border-t-gray-400/40",children:(0,e.jsxs)(o.Flex,{gap:2,align:"end",className:"w-full",children:[(0,e.jsx)("div",{className:"w-full [&_textarea]:border-none! [&_textarea]:outline-none!",children:(0,e.jsx)(o.TextArea,{"aria-label":"message",size:"extralarge",placeholder:"Type a message\u2026",value:i,onKeyDown:T,onChange:n=>b(n),roundness:"none",autogrow:!0})}),(0,e.jsx)("div",{className:"mr-[7px] mb-[7px]",children:(0,e.jsx)(o.Button,{shape:"square",roundness:"full",variant:"fill",size:"medium",onPress:y,isDisabled:!i.trim(),children:(0,e.jsx)(c.Send,{size:20})})})]})})]})})},F=({identityId:t,conversationId:a,notifications:r=!0,...p})=>{const s=(0,v.default)({isOpen:!0,enabled:r!==!1,options:{requestPermissionOn:"manual",...typeof r=="object"?r:void 0}}),h=(0,I.default)({identityId:t,conversationId:a,onInboundMessage:s.handleInboundMessage});return(0,e.jsx)(f,{...h,...p})};var K=F;
|
|
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';\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,
|
|
5
|
-
"mappings": "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
|
|
6
|
-
"names": ["InAppChat_exports", "__export", "InAppChat", "InAppChat_default", "__toCommonJS", "import_jsx_runtime", "ScrollArea", "import_react", "import_lucide_react", "import_components", "import_cn", "import_use_auto_scroll", "import_use_in_app_chat", "import_use_in_app_chat_notifications", "messageText", "message", "content", "isOutgoing", "messages", "isLoading", "error", "sendMessage", "withChatHeader", "withPopoverClose", "borderless", "title", "inputValue", "setInputValue", "scrollAreaRef", "scrollToBottom", "useAutoScroll", "handleSubmit", "handleKeyDown", "e", "text", "InAppChatWrapper", "identityId", "
|
|
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\n// `conversationId` is required (inherited from the hook's props): this widget\n// participates in a conversation your BACKEND created \u2014 it cannot create one, because\n// creating a chat is server-only in DashX. Pass `null` while you're still fetching the\n// id and the widget renders its empty/loading state instead of guessing.\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, conversationId, 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 conversationId,\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": "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",
|
|
6
|
+
"names": ["InAppChat_exports", "__export", "InAppChat", "InAppChat_default", "__toCommonJS", "import_jsx_runtime", "ScrollArea", "import_react", "import_lucide_react", "import_components", "import_cn", "import_use_auto_scroll", "import_use_in_app_chat", "import_use_in_app_chat_notifications", "messageText", "message", "content", "isOutgoing", "messages", "isLoading", "error", "sendMessage", "withChatHeader", "withPopoverClose", "borderless", "title", "inputValue", "setInputValue", "scrollAreaRef", "scrollToBottom", "useAutoScroll", "handleSubmit", "handleKeyDown", "e", "text", "InAppChatWrapper", "identityId", "conversationId", "notifications", "props", "notifier", "useInAppChatNotifications", "chat", "useInAppChat"]
|
|
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,
|
|
10
|
+
declare const InAppChatButton: ({ identityId, conversationId, 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
|
-
"use strict";var
|
|
1
|
+
"use strict";var B=Object.create;var i=Object.defineProperty;var R=Object.getOwnPropertyDescriptor;var x=Object.getOwnPropertyNames;var L=Object.getPrototypeOf,S=Object.prototype.hasOwnProperty;var w=(t,e)=>{for(var o in e)i(t,o,{get:e[o],enumerable:!0})},c=(t,e,o,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of x(e))!S.call(t,r)&&r!==o&&i(t,r,{get:()=>e[r],enumerable:!(a=R(e,r))||a.enumerable});return t};var g=(t,e,o)=>(o=t!=null?B(L(t)):{},c(e||!t||!t.__esModule?i(o,"default",{value:t,enumerable:!0}):o,t)),M=t=>c(i({},"__esModule",{value:!0}),t);var F={};w(F,{default:()=>z});module.exports=M(F);var p=require("react/jsx-runtime"),s=require("react"),C=require("lucide-react"),n=require("../components"),P=require("./InAppChat.js"),d=g(require("../hooks/use-in-app-chat.js")),b=g(require("../hooks/use-in-app-chat-notifications.js"));const N={"bottom-right":"right-4 bottom-4","bottom-left":"left-4 bottom-4","top-right":"right-4 top-4","top-left":"left-4 top-4"},q=({identityId:t,conversationId:e,notifications:o=!0,position:a="bottom-right",theme:r,...I})=>{const[h,l]=(0,s.useState)(!1),u=(0,s.useRef)(!1);h&&(u.current=!0);const A=u.current,O=(0,s.useCallback)(()=>l(!0),[]),{handleInboundMessage:v,requestPermissionOnOpen:m}=(0,b.default)({isOpen:h,enabled:o!==!1,options:typeof o=="object"?o:void 0,onActivate:O}),T=(0,s.useCallback)(f=>{f&&m(),l(f)},[m]),y=(0,d.default)({identityId:t,conversationId:e,enabled:A,onInboundMessage:v});return(0,p.jsx)(n.Theme,{...r,children:(0,p.jsx)(n.Flex,{className:`fixed z-50 ${N[a]}`,children:(0,p.jsxs)(n.Popover.Root,{open:h,onOpenChange:T,children:[(0,p.jsx)(n.Popover.Trigger,{children:(0,p.jsx)(n.Button,{shape:"square",roundness:"full",variant:"fill",size:"large",children:(0,p.jsx)(C.MessageCircle,{})})}),(0,p.jsx)(n.Popover.Content,{spacing:"large",width:"350px",height:"450px",children:(0,p.jsx)(P.InAppChat,{...y,borderless:!0,withChatHeader:!0,withPopoverClose:!0,...I})})]})})})};var z=q;
|
|
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, { 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
|
|
5
|
-
"mappings": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,IAAA,eAAAC,EAAAH,GA2EQ,IAAAI,EAAA,6BA3ERC,EAAqD,iBACrDC,EAA8B,wBAE9BC,EAA8D,yBAC9DC,EAAsD,0BACtDC,EAAyB,0CACzBC,EAAsC,wDAYtC,MAAMC,EAAmD,CACvD,eAAgB,mBAChB,cAAe,kBACf,YAAa,gBACb,WAAY,cACd,EAEMC,EAAkB,CAAC,CACvB,WAAAC,EACA,eAAAC,EACA,
|
|
6
|
-
"names": ["InAppChatButton_exports", "__export", "InAppChatButton_default", "__toCommonJS", "import_jsx_runtime", "import_react", "import_lucide_react", "import_components", "import_InAppChat", "import_use_in_app_chat", "import_use_in_app_chat_notifications", "POSITION_CLASS", "InAppChatButton", "identityId", "
|
|
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 conversationId,\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 open\n // the hook is idle, so a page that never opens the launcher does no chat work\n // (no subscription, no history fetch). It never created a conversation either \u2014\n // the conversation is created by your backend and passed in as `conversationId`.\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 conversationId,\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 a launcher the visitor never opens costs nothing. */}\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": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,IAAA,eAAAC,EAAAH,GA2EQ,IAAAI,EAAA,6BA3ERC,EAAqD,iBACrDC,EAA8B,wBAE9BC,EAA8D,yBAC9DC,EAAsD,0BACtDC,EAAyB,0CACzBC,EAAsC,wDAYtC,MAAMC,EAAmD,CACvD,eAAgB,mBAChB,cAAe,kBACf,YAAa,gBACb,WAAY,cACd,EAEMC,EAAkB,CAAC,CACvB,WAAAC,EACA,eAAAC,EACA,cAAAC,EAAgB,GAChB,SAAAC,EAAW,eACX,MAAAC,EACA,GAAGC,CACL,IAA4B,CAC1B,KAAM,CAACC,EAAQC,CAAS,KAAI,YAAS,EAAK,EAQpCC,KAAe,UAAO,EAAK,EAC7BF,IAAQE,EAAa,QAAU,IACnC,MAAMC,EAAUD,EAAa,QAEvBE,KAAO,eAAY,IAAMH,EAAU,EAAI,EAAG,CAAC,CAAC,EAE5C,CAAE,qBAAAI,EAAsB,wBAAAC,CAAwB,KAAI,EAAAC,SAA0B,CAClF,OAAAP,EACA,QAASJ,IAAkB,GAC3B,QAAS,OAAOA,GAAkB,SAAWA,EAAgB,OAC7D,WAAYQ,CACd,CAAC,EAKKI,KAAmB,eACtBC,GAAsB,CACjBA,GAAUH,EAAwB,EACtCL,EAAUQ,CAAQ,CACpB,EACA,CAACH,CAAuB,CAC1B,EAEMI,KAAO,EAAAC,SAAa,CACxB,WAAAjB,EACA,eAAAC,EACA,QAAAQ,EACA,iBAAkBE,CACpB,CAAC,EAED,SACE,OAAC,SAAO,GAAGP,EACT,mBAAC,QAAK,UAAW,cAAcN,EAAeK,CAAQ,CAAC,GACrD,oBAAC,UAAQ,KAAR,CAAa,KAAMG,EAAQ,aAAcQ,EACxC,oBAAC,UAAQ,QAAR,CACC,mBAAC,UAAO,MAAM,SAAS,UAAU,OAAO,QAAQ,OAAO,KAAK,QAC1D,mBAAC,kBAAc,EACjB,EACF,KAKA,OAAC,UAAQ,QAAR,CAAgB,QAAQ,QAAQ,MAAM,QAAQ,OAAO,QACpD,mBAAC,aACE,GAAGE,EACJ,WAAU,GACV,eAAc,GACd,iBAAgB,GACf,GAAGX,EACN,EACF,GACF,EACF,EACF,CAEJ,EAIA,IAAOhB,EAAQU",
|
|
6
|
+
"names": ["InAppChatButton_exports", "__export", "InAppChatButton_default", "__toCommonJS", "import_jsx_runtime", "import_react", "import_lucide_react", "import_components", "import_InAppChat", "import_use_in_app_chat", "import_use_in_app_chat_notifications", "POSITION_CLASS", "InAppChatButton", "identityId", "conversationId", "notifications", "position", "theme", "props", "isOpen", "setIsOpen", "hasOpenedRef", "enabled", "open", "handleInboundMessage", "requestPermissionOnOpen", "useInAppChatNotifications", "handleOpenChange", "nextOpen", "chat", "useInAppChat"]
|
|
7
7
|
}
|
|
@@ -9,7 +9,7 @@ type UseInAppChatNotificationsProps = {
|
|
|
9
9
|
isOpen: boolean;
|
|
10
10
|
enabled?: boolean;
|
|
11
11
|
options?: InAppChatNotificationOptions;
|
|
12
|
-
onActivate?: () => void;
|
|
12
|
+
onActivate?: (message: InAppChatMessageData) => void;
|
|
13
13
|
};
|
|
14
14
|
/**
|
|
15
15
|
* Foreground browser notifications for incoming In-App Chat messages. Returns a
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{useCallback as s,useRef as o}from"react";import I from"./use-dashx-provider.js";const
|
|
1
|
+
import{useCallback as s,useRef as o}from"react";import I from"./use-dashx-provider.js";const A=t=>typeof t=="string"?t:t?.text??t?.body??"",y=({isOpen:t,enabled:a=!0,options:p,onActivate:c})=>{const e=I(),u=o(t);u.current=t;const i=o(a);i.current=a;const r=o(p);r.current=p;const f=o(c);f.current=c;const h=()=>!(!u.current||typeof document>"u"||document.hidden||typeof document.hasFocus=="function"&&!document.hasFocus()),l=s(n=>{if(!i.current||(n.aiRole??"").toUpperCase()==="USER"||h())return;const d=r.current?.renderBody?.(n)??A(n.renderedContent);d&&e.showInAppChatNotification?.({title:r.current?.title??"New message",body:d,icon:r.current?.icon,tag:n.conversationId?`in_app_chat:${n.conversationId}`:void 0,onClick:()=>f.current?.(n)})},[e]),C=s(()=>e.requestNotificationPermission?.()??Promise.resolve("denied"),[e]),m=s(()=>{i.current&&(r.current?.requestPermissionOn??"firstOpen")==="firstOpen"&&e.requestNotificationPermission?.().catch(()=>{})},[e]);return{handleInboundMessage:l,requestPermission:C,requestPermissionOnOpen:m}};var P=y;export{P as default};
|
|
2
2
|
//# sourceMappingURL=use-in-app-chat-notifications.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/hooks/use-in-app-chat-notifications.ts"],
|
|
4
|
-
"sourcesContent": ["import { useCallback, useRef } from 'react';\nimport type { InAppChatMessageData } from '@dashx/browser';\n\nimport useDashXProvider from './use-dashx-provider.js';\n\ntype InAppChatNotificationOptions = {\n // Notification title. Defaults to 'New message'.\n title?: string;\n // Icon URL shown in the notification.\n icon?: string;\n // Custom body text from the inbound message; defaults to the message text.\n renderBody?: (message: InAppChatMessageData) => string;\n // When to request notification permission. 'firstOpen' (the default for the\n // launcher) requests it the first time the visitor opens chat \u2014 a real user\n // gesture, which browsers require for a non-penalized prompt. 'manual' never\n // auto-requests (use for always-visible surfaces, where the embedder drives\n // the prompt via the returned `requestPermission`).\n requestPermissionOn?: 'firstOpen' | 'manual';\n};\n\ntype UseInAppChatNotificationsProps = {\n // Whether the chat surface is currently open/visible. Combined with tab\n // visibility + window focus to decide if the visitor is actively looking at\n // chat (in which case we don't notify).\n isOpen: boolean;\n // `false` disables notifications entirely.\n enabled?: boolean;\n options?: InAppChatNotificationOptions;\n // Invoked when the visitor clicks a notification \u2014 focus is handled by the\n // SDK; this opens the chat panel.\n onActivate?: () => void;\n};\n\nconst textFromContent = (content: any): string => {\n if (typeof content === 'string') return content;\n return content?.text ?? content?.body ?? '';\n};\n\n/**\n * Foreground browser notifications for incoming In-App Chat messages. Returns a\n * `handleInboundMessage` to pass as `useInAppChat`'s `onInboundMessage`; it\n * fires a notification only for agent/AI replies that arrive while the chat\n * isn't focused (panel closed, or tab hidden/unfocused) and only once the\n * visitor has granted permission.\n */\nconst useInAppChatNotifications = ({\n isOpen,\n enabled = true,\n options,\n onActivate,\n}: UseInAppChatNotificationsProps) => {\n const dashX = useDashXProvider();\n\n // Latest values for the message handler, so it stays referentially stable\n // (it's wired into the chat hook's subscription).\n const isOpenRef = useRef(isOpen);\n isOpenRef.current = isOpen;\n const enabledRef = useRef(enabled);\n enabledRef.current = enabled;\n const optionsRef = useRef(options);\n optionsRef.current = options;\n const onActivateRef = useRef(onActivate);\n onActivateRef.current = onActivate;\n\n const isChatFocused = (): boolean => {\n if (!isOpenRef.current) return false;\n if (typeof document === 'undefined') return false;\n if (document.hidden) return false;\n if (typeof document.hasFocus === 'function' && !document.hasFocus()) return false;\n return true;\n };\n\n const handleInboundMessage = useCallback(\n (message: InAppChatMessageData) => {\n if (!enabledRef.current) return;\n // Agent/AI replies only \u2014 never the visitor's own echoed message.\n if ((message.aiRole ?? '').toUpperCase() === 'USER') return;\n // Don't interrupt a visitor who's actively looking at the chat.\n if (isChatFocused()) return;\n\n const body = optionsRef.current?.renderBody?.(message) ?? textFromContent(message.renderedContent);\n if (!body) return;\n\n dashX.showInAppChatNotification?.({\n title: optionsRef.current?.title ?? 'New message',\n body,\n icon: optionsRef.current?.icon,\n tag: message.conversationId ? `in_app_chat:${message.conversationId}` : undefined,\n onClick: () => onActivateRef.current?.(),\n });\n },\n [dashX],\n );\n\n const requestPermission = useCallback(\n () => dashX.requestNotificationPermission?.() ?? Promise.resolve('denied' as const),\n [dashX],\n );\n\n // Call this SYNCHRONOUSLY from the surface's open event (a real user gesture)\n // so the permission prompt lands inside the browser's transient activation\n // window. Requesting from an effect after the click has unwound is\n // ignored/rejected by some browsers. Honors `requestPermissionOn` ('manual'\n // skips it), and is safe to call on every open (no-ops once permission is\n // decided \u2014 see Client.requestNotificationPermission).\n const requestPermissionOnOpen = useCallback(() => {\n if (!enabledRef.current) return;\n if ((optionsRef.current?.requestPermissionOn ?? 'firstOpen') !== 'firstOpen') return;\n dashX.requestNotificationPermission?.().catch(() => {});\n }, [dashX]);\n\n return { handleInboundMessage, requestPermission, requestPermissionOnOpen };\n};\n\nexport type { InAppChatNotificationOptions, UseInAppChatNotificationsProps };\n\nexport default useInAppChatNotifications;\n"],
|
|
5
|
-
"mappings": "AAAA,OAAS,eAAAA,EAAa,UAAAC,MAAc,QAGpC,OAAOC,MAAsB,
|
|
4
|
+
"sourcesContent": ["import { useCallback, useRef } from 'react';\nimport type { InAppChatMessageData } from '@dashx/browser';\n\nimport useDashXProvider from './use-dashx-provider.js';\n\ntype InAppChatNotificationOptions = {\n // Notification title. Defaults to 'New message'.\n title?: string;\n // Icon URL shown in the notification.\n icon?: string;\n // Custom body text from the inbound message; defaults to the message text.\n renderBody?: (message: InAppChatMessageData) => string;\n // When to request notification permission. 'firstOpen' (the default for the\n // launcher) requests it the first time the visitor opens chat \u2014 a real user\n // gesture, which browsers require for a non-penalized prompt. 'manual' never\n // auto-requests (use for always-visible surfaces, where the embedder drives\n // the prompt via the returned `requestPermission`).\n requestPermissionOn?: 'firstOpen' | 'manual';\n};\n\ntype UseInAppChatNotificationsProps = {\n // Whether the chat surface is currently open/visible. Combined with tab\n // visibility + window focus to decide if the visitor is actively looking at\n // chat (in which case we don't notify).\n isOpen: boolean;\n // `false` disables notifications entirely.\n enabled?: boolean;\n options?: InAppChatNotificationOptions;\n // Invoked when the visitor clicks a notification \u2014 focus is handled by the\n // SDK; this opens the chat panel. Receives the message that raised THAT\n // notification, so a surface watching several conversations can open the right\n // one: without it, every notification resolves to whichever arrived last.\n onActivate?: (message: InAppChatMessageData) => void;\n};\n\nconst textFromContent = (content: any): string => {\n if (typeof content === 'string') return content;\n return content?.text ?? content?.body ?? '';\n};\n\n/**\n * Foreground browser notifications for incoming In-App Chat messages. Returns a\n * `handleInboundMessage` to pass as `useInAppChat`'s `onInboundMessage`; it\n * fires a notification only for agent/AI replies that arrive while the chat\n * isn't focused (panel closed, or tab hidden/unfocused) and only once the\n * visitor has granted permission.\n */\nconst useInAppChatNotifications = ({\n isOpen,\n enabled = true,\n options,\n onActivate,\n}: UseInAppChatNotificationsProps) => {\n const dashX = useDashXProvider();\n\n // Latest values for the message handler, so it stays referentially stable\n // (it's wired into the chat hook's subscription).\n const isOpenRef = useRef(isOpen);\n isOpenRef.current = isOpen;\n const enabledRef = useRef(enabled);\n enabledRef.current = enabled;\n const optionsRef = useRef(options);\n optionsRef.current = options;\n const onActivateRef = useRef(onActivate);\n onActivateRef.current = onActivate;\n\n const isChatFocused = (): boolean => {\n if (!isOpenRef.current) return false;\n if (typeof document === 'undefined') return false;\n if (document.hidden) return false;\n if (typeof document.hasFocus === 'function' && !document.hasFocus()) return false;\n return true;\n };\n\n const handleInboundMessage = useCallback(\n (message: InAppChatMessageData) => {\n if (!enabledRef.current) return;\n // Agent/AI replies only \u2014 never the visitor's own echoed message.\n if ((message.aiRole ?? '').toUpperCase() === 'USER') return;\n // Don't interrupt a visitor who's actively looking at the chat.\n if (isChatFocused()) return;\n\n const body = optionsRef.current?.renderBody?.(message) ?? textFromContent(message.renderedContent);\n if (!body) return;\n\n dashX.showInAppChatNotification?.({\n title: optionsRef.current?.title ?? 'New message',\n body,\n icon: optionsRef.current?.icon,\n tag: message.conversationId ? `in_app_chat:${message.conversationId}` : undefined,\n onClick: () => onActivateRef.current?.(message),\n });\n },\n [dashX],\n );\n\n const requestPermission = useCallback(\n () => dashX.requestNotificationPermission?.() ?? Promise.resolve('denied' as const),\n [dashX],\n );\n\n // Call this SYNCHRONOUSLY from the surface's open event (a real user gesture)\n // so the permission prompt lands inside the browser's transient activation\n // window. Requesting from an effect after the click has unwound is\n // ignored/rejected by some browsers. Honors `requestPermissionOn` ('manual'\n // skips it), and is safe to call on every open (no-ops once permission is\n // decided \u2014 see Client.requestNotificationPermission).\n const requestPermissionOnOpen = useCallback(() => {\n if (!enabledRef.current) return;\n if ((optionsRef.current?.requestPermissionOn ?? 'firstOpen') !== 'firstOpen') return;\n dashX.requestNotificationPermission?.().catch(() => {});\n }, [dashX]);\n\n return { handleInboundMessage, requestPermission, requestPermissionOnOpen };\n};\n\nexport type { InAppChatNotificationOptions, UseInAppChatNotificationsProps };\n\nexport default useInAppChatNotifications;\n"],
|
|
5
|
+
"mappings": "AAAA,OAAS,eAAAA,EAAa,UAAAC,MAAc,QAGpC,OAAOC,MAAsB,0BAgC7B,MAAMC,EAAmBC,GACnB,OAAOA,GAAY,SAAiBA,EACjCA,GAAS,MAAQA,GAAS,MAAQ,GAUrCC,EAA4B,CAAC,CACjC,OAAAC,EACA,QAAAC,EAAU,GACV,QAAAC,EACA,WAAAC,CACF,IAAsC,CACpC,MAAMC,EAAQR,EAAiB,EAIzBS,EAAYV,EAAOK,CAAM,EAC/BK,EAAU,QAAUL,EACpB,MAAMM,EAAaX,EAAOM,CAAO,EACjCK,EAAW,QAAUL,EACrB,MAAMM,EAAaZ,EAAOO,CAAO,EACjCK,EAAW,QAAUL,EACrB,MAAMM,EAAgBb,EAAOQ,CAAU,EACvCK,EAAc,QAAUL,EAExB,MAAMM,EAAgB,IAChB,GAACJ,EAAU,SACX,OAAO,SAAa,KACpB,SAAS,QACT,OAAO,SAAS,UAAa,YAAc,CAAC,SAAS,SAAS,GAI9DK,EAAuBhB,EAC1BiB,GAAkC,CAKjC,GAJI,CAACL,EAAW,UAEXK,EAAQ,QAAU,IAAI,YAAY,IAAM,QAEzCF,EAAc,EAAG,OAErB,MAAMG,EAAOL,EAAW,SAAS,aAAaI,CAAO,GAAKd,EAAgBc,EAAQ,eAAe,EAC5FC,GAELR,EAAM,4BAA4B,CAChC,MAAOG,EAAW,SAAS,OAAS,cACpC,KAAAK,EACA,KAAML,EAAW,SAAS,KAC1B,IAAKI,EAAQ,eAAiB,eAAeA,EAAQ,cAAc,GAAK,OACxE,QAAS,IAAMH,EAAc,UAAUG,CAAO,CAChD,CAAC,CACH,EACA,CAACP,CAAK,CACR,EAEMS,EAAoBnB,EACxB,IAAMU,EAAM,gCAAgC,GAAK,QAAQ,QAAQ,QAAiB,EAClF,CAACA,CAAK,CACR,EAQMU,EAA0BpB,EAAY,IAAM,CAC3CY,EAAW,UACXC,EAAW,SAAS,qBAAuB,eAAiB,aACjEH,EAAM,gCAAgC,EAAE,MAAM,IAAM,CAAC,CAAC,CACxD,EAAG,CAACA,CAAK,CAAC,EAEV,MAAO,CAAE,qBAAAM,EAAsB,kBAAAG,EAAmB,wBAAAC,CAAwB,CAC5E,EAIA,IAAOC,EAAQhB",
|
|
6
6
|
"names": ["useCallback", "useRef", "useDashXProvider", "textFromContent", "content", "useInAppChatNotifications", "isOpen", "enabled", "options", "onActivate", "dashX", "isOpenRef", "enabledRef", "optionsRef", "onActivateRef", "isChatFocused", "handleInboundMessage", "message", "body", "requestPermission", "requestPermissionOnOpen", "use_in_app_chat_notifications_default"]
|
|
7
7
|
}
|
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
import type { InAppChatMessageData } from '@dashx/browser';
|
|
2
2
|
type UseInAppChatHookProps = {
|
|
3
3
|
identityId: string;
|
|
4
|
-
|
|
5
|
-
initialMessage?: string;
|
|
4
|
+
conversationId: string | null;
|
|
6
5
|
enabled?: boolean;
|
|
7
6
|
onInboundMessage?: (message: InAppChatMessageData) => void;
|
|
8
7
|
};
|
|
@@ -16,7 +15,6 @@ type InAppChatMessage = {
|
|
|
16
15
|
isPending?: boolean;
|
|
17
16
|
};
|
|
18
17
|
type UseInAppChatHookResponse = {
|
|
19
|
-
conversationId: string | null;
|
|
20
18
|
messages: InAppChatMessage[];
|
|
21
19
|
isLoading: boolean;
|
|
22
20
|
isConnected: boolean;
|
|
@@ -24,18 +22,22 @@ type UseInAppChatHookResponse = {
|
|
|
24
22
|
sendMessage: (text: string) => boolean;
|
|
25
23
|
};
|
|
26
24
|
/**
|
|
27
|
-
* Two-way InApp Chat
|
|
25
|
+
* Two-way InApp Chat within an EXISTING conversation.
|
|
26
|
+
*
|
|
27
|
+
* This hook participates; it never creates. Creating a conversation is a
|
|
28
|
+
* server-only operation — DashX rejects identity-token callers and requires an
|
|
29
|
+
* `accountUid` the browser has no authority to assert, and the conversation's
|
|
30
|
+
* metadata must be derived server-side. So the flow is: your backend creates the
|
|
31
|
+
* conversation (e.g. via `dashx-java`) and returns its id; you pass that id here.
|
|
28
32
|
*
|
|
29
33
|
* PREREQUISITE: the surrounding `<DashXProvider>` must already have a valid
|
|
30
|
-
* `identityToken` (and matching `identityUid`).
|
|
31
|
-
* identity-token auth — if
|
|
32
|
-
* are rejected and the hook surfaces an
|
|
33
|
-
* a token arrives later (its inputs are `identityId`/`
|
|
34
|
-
* visitor token), so only render the chat once `identityToken` is available —
|
|
35
|
-
*
|
|
36
|
-
* this by starting lazily when the visitor opens it, by which point the provider
|
|
37
|
-
* has applied the token.
|
|
34
|
+
* `identityToken` (and matching `identityUid`). Fetching history, sending, and
|
|
35
|
+
* subscribing all require identity-token auth — if they run before an identity is
|
|
36
|
+
* resolved they are rejected and the hook surfaces an error. It does NOT auto-retry
|
|
37
|
+
* when a token arrives later (its inputs are `identityId`/`conversationId`, not the
|
|
38
|
+
* visitor token), so only render the chat once `identityToken` is available — e.g.
|
|
39
|
+
* `{identityToken && <InAppChat … />}`.
|
|
38
40
|
*/
|
|
39
|
-
declare const useInAppChat: ({ identityId,
|
|
41
|
+
declare const useInAppChat: ({ identityId, conversationId, enabled, onInboundMessage }: UseInAppChatHookProps) => UseInAppChatHookResponse;
|
|
40
42
|
export type { UseInAppChatHookProps, UseInAppChatHookResponse, InAppChatMessage };
|
|
41
43
|
export default useInAppChat;
|