@dashx/react 0.3.7 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +31 -0
- 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.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.ts +42 -70
- package/src/widgets/InAppChat.tsx +6 -3
- package/src/widgets/InAppChatButton.tsx +7 -7
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,37 @@
|
|
|
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.0] — 2026-07-29
|
|
6
|
+
|
|
7
|
+
### Changed
|
|
8
|
+
|
|
9
|
+
- **BREAKING — In-App Chat no longer creates conversations; the caller supplies one.** `useInAppChat` and both widgets participate in an EXISTING conversation:
|
|
10
|
+
|
|
11
|
+
```diff
|
|
12
|
+
- useInAppChat({ identityId, idempotencyKey, initialMessage? })
|
|
13
|
+
+ useInAppChat({ identityId, conversationId })
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
`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`.
|
|
17
|
+
|
|
18
|
+
**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.
|
|
19
|
+
|
|
20
|
+
**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:
|
|
21
|
+
|
|
22
|
+
```tsx
|
|
23
|
+
const { conversationId } = useMyBackendChatSession(); // your endpoint
|
|
24
|
+
<InAppChatButton identityId="<chat-identity-id>" conversationId={conversationId} />
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
`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.
|
|
28
|
+
- **`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`.
|
|
29
|
+
- `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.
|
|
30
|
+
- **`@dashx/browser` dependency raised to `^0.10.0`** (a regular `dependencies` entry, as before), which is the release that removes the creation method.
|
|
31
|
+
|
|
32
|
+
### Unchanged
|
|
33
|
+
|
|
34
|
+
- 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.
|
|
35
|
+
|
|
5
36
|
## [0.3.0] — 2026-06-18
|
|
6
37
|
|
|
7
38
|
### Added
|
|
@@ -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": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,E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I,CAACA,EAAK,KAAK,GAAK,CAACzB,GAAkB,CAACC,EAAS,MAAO,GAIxD,MAAMgB,EAAaJ,EAAc,QAC3Ba,KAAkB,EAAAC,SAAK,EACvBC,EAA+B,CACnC,GAAIF,EACJ,YAAa,eAAeA,CAAe,GAC3C,gBAAiB,CAAE,KAAAD,CAAK,EACxB,OAAQ,OACR,UAAW,IAAI,KAAK,EAAE,YAAY,EAClC,UAAW,EACb,EACA,OAAAV,EAAe,CAACa,CAAU,CAAC,GAErB,SAAY,CAChB,GAAI,CACF,MAAMC,EAAgB,MAAM1B,EAAM,qBAAqB,CACrD,eAAAH,EACA,WAAAD,EACA,QAAS,CAAE,KAAA0B,CAAK,EAChB,gBAAAC,CACF,CAAC,EACD,GAAIT,IAAeJ,EAAc,QAAS,OAE1CE,EAAe,CAAC3B,EAAYyC,CAAa,CAAC,CAAC,CAC7C,MAAQ,CACFZ,IAAeJ,EAAc,SAASD,EAAS,wBAAwB,CAC7E,CACF,GAAG,EAGI,EACT,EACA,CAACT,EAAOJ,EAAYC,EAAgBC,EAASc,CAAc,CAC7D,EAEA,MAAO,CAAE,SAAAR,EAAU,UAAAE,EAAW,YAAAJ,EAAa,MAAAM,EAAO,YAAAa,CAAY,CAChE,EAIA,IAAO3C,EAAQiB",
|
|
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": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,eAAAE,EAAA,YAAAC,IAAA,eAAAC,EAAAJ,GAqEU,IAAAK,EAAA,6BArEVC,EAA4B,0CAC5BC,EAA2C,iBAC3CC,EAAwB,wBAGxBC,EAAsE,yBACtEC,EAAmB,0BACnBC,EAA0B,0CAC1BC,EAIO,0CACPC,EAEO,wDASP,MAAMC,EAAeC,GAAsC,CACzD,MAAMC,EAAUD,EAAQ,gBACxB,OAAI,OAAOC,GAAY,SAAiBA,EACjCA,GAAS,MAAQ,EAC1B,EAEMC,EAAcF,GAAuCA,EAAQ,QAAQ,YAAY,IAAM,OAEvFb,EAAY,CAAC,CACjB,SAAAgB,EACA,UAAAC,EACA,MAAAC,EACA,YAAAC,EACA,eAAAC,EAAiB,GACjB,iBAAAC,EAAmB,GACnB,WAAAC,EAAa,GACb,MAAAC,EAAQ,MACV,IAAsB,CACpB,KAAM,CAACC,EAAYC,CAAa,KAAI,YAAS,EAAE,EACzC,CAAE,cAAAC,EAAe,eAAAC,CAAe,KAAI,EAAAC,SAAc,KAExD,aAAU,IAAM,CACd,WAAW,IAAMD,EAAe,CAAE,OAAQ,EAAK,CAAC,EAAG,CAAC,CACtD,EAAG,CAACX,EAAS,OAAQW,CAAc,CAAC,EAEpC,MAAME,EAAe,IAAM,CACpBL,EAAW,KAAK,GAKjBL,EAAYK,CAAU,GAAGC,EAAc,EAAE,CAC/C,EAEMK,EAAiBC,GAA0C,CAC3DA,EAAE,MAAQ,SAAW,CAACA,EAAE,WAC1BA,EAAE,eAAe,EACjBF,EAAa,EAEjB,EAEA,SACE,OAAC,SAAM,QAAO,G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OAAC,OAAI,UAAU,oBACb,mBAAC,UACC,MAAM,SACN,UAAU,OACV,QAAQ,OACR,KAAK,SACL,QAASH,EACT,WAAY,CAACL,EAAW,KAAK,EAE7B,mBAAC,QAAK,KAAM,GAAI,EAClB,EACF,GACF,EACF,GACF,EACF,CAEJ,
|
|
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": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,eAAAE,EAAA,YAAAC,IAAA,eAAAC,EAAAJ,GAqEU,IAAAK,EAAA,6BArEVC,EAA4B,0CAC5BC,EAA2C,iBAC3CC,EAAwB,wBAGxBC,EAAsE,yBACtEC,EAAmB,0BACnBC,EAA0B,0CAC1BC,EAIO,0CACPC,EAEO,wDASP,MAAMC,EAAeC,GAAsC,CACzD,MAAMC,EAAUD,EAAQ,gBACxB,OAAI,OAAOC,GAAY,SAAiBA,EACjCA,GAAS,MAAQ,EAC1B,EAEMC,EAAcF,GAAuCA,EAAQ,QAAQ,YAAY,IAAM,OAEvFb,EAAY,CAAC,CACjB,SAAAgB,EACA,UAAAC,EACA,MAAAC,EACA,YAAAC,EACA,eAAAC,EAAiB,GACjB,iBAAAC,EAAmB,GACnB,WAAAC,EAAa,GACb,MAAAC,EAAQ,MACV,IAAsB,CACpB,KAAM,CAACC,EAAYC,CAAa,KAAI,YAAS,EAAE,EACzC,CAAE,cAAAC,EAAe,eAAAC,CAAe,KAAI,EAAAC,SAAc,KAExD,aAAU,IAAM,CACd,WAAW,IAAMD,EAAe,CAAE,OAAQ,EAAK,CAAC,EAAG,CAAC,CACtD,EAAG,CAACX,EAAS,OAAQW,CAAc,CAAC,EAEpC,MAAME,EAAe,IAAM,CACpBL,EAAW,KAAK,GAKjBL,EAAYK,CAAU,G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AC,OAAI,UAAU,8DACb,mBAAC,YACC,aAAW,UACX,KAAK,aACL,YAAY,uBACZ,MAAOoB,EACP,UAAWM,EACX,SAAWE,GAASP,EAAcO,CAAI,EACtC,UAAU,OACV,SAAQ,GACV,EACF,KACA,OAAC,OAAI,UAAU,oBACb,mBAAC,UACC,MAAM,SACN,UAAU,OACV,QAAQ,OACR,KAAK,SACL,QAASH,EACT,WAAY,CAACL,EAAW,KAAK,EAE7B,mBAAC,QAAK,KAAM,GAAI,EAClB,EACF,GACF,EACF,GACF,EACF,CAEJ,EAiBMS,EAAmB,CAAC,CAAE,WAAAC,EAAY,eAAAC,EAAgB,cAAAC,EAAgB,GAAM,GAAGC,CAAM,IAA6B,CAIlH,MAAMC,KAAW,EAAAC,SAA0B,CACzC,OAAQ,GACR,QAASH,IAAkB,GAC3B,QAAS,CACP,oBAAqB,SACrB,GAAI,OAAOA,GAAkB,SAAWA,EAAgB,MAC1D,CACF,CAAC,EACKI,KAAO,EAAAC,SAAa,CACxB,WAAAP,EACA,eAAAC,EACA,iBAAkBG,EAAS,oBAC7B,CAAC,EACD,SAAO,OAACtC,EAAA,CAAW,GAAGwC,EAAO,GAAGH,EAAO,CACzC,EAMA,IAAOpC,EAAQgC",
|
|
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,I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AGE,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
|
}
|
|
@@ -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
|
-
import
|
|
1
|
+
import H from"uuid-random";import{useCallback as b,useEffect as x,useRef as R,useState as C}from"react";import P from"./use-dashx-provider.js";import{useWebSocket as w}from"../providers/DashXProvider.js";const E="in_app_chat:conversation:",f=t=>({id:t.id,externalUid:t.externalUid??null,renderedContent:t.renderedContent,aiRole:t.aiRole??null,createdAt:t.createdAt,turnSeq:t.turnSeq}),_=(t,s)=>{const r=new Map,u=e=>e.externalUid||e.id;return[...t,...s].forEach(e=>{const a=r.get(u(e));(!a||a.isPending)&&r.set(u(e),e)}),[...r.values()].sort((e,a)=>e.createdAt!==a.createdAt?e.createdAt<a.createdAt?-1:1:(e.turnSeq??0)-(a.turnSeq??0))},q=({identityId:t,conversationId:s,enabled:r=!0,onInboundMessage:u})=>{const e=P(),{isConnected:a,initializeWebSocket:M}=w(),[U,I]=C([]),[S,A]=C(!0),[k,l]=C(null),o=R(0),y=R(u);y.current=u;const p=b(i=>{I(n=>_(n,i))},[]);x(()=>{const i=o.current+=1,n=()=>i!==o.current;if(I([]),l(null),!r||!s)return A(!1),()=>{o.current+=1};A(!0),M();let c;return(async()=>{try{const d=async()=>{const h=await e.fetchInAppChatMessages({conversationId:s});n()||p(h.map(f))},g=e.subscribeToChannel(`${E}${s}`,h=>{n()||(p([f(h)]),y.current?.(h))},{onReconnectAck:()=>{n()||(l(null),d().catch(()=>{}))}});c=g.unsubscribe;try{await g.ready}catch{n()||l("Couldn\u2019t connect to live chat. Retrying\u2026");return}if(n())return;await d()}catch{n()||l("Failed to load chat")}finally{n()||A(!1)}})(),()=>{o.current+=1,c?.()}},[e,t,s,r,M,p]);const m=b(i=>{if(!i.trim()||!s||!r)return!1;const n=o.current,c=H(),d={id:c,externalUid:`in_app_chat:${c}`,renderedContent:{text:i},aiRole:"USER",createdAt:new Date().toISOString(),isPending:!0};return p([d]),(async()=>{try{const g=await e.sendInAppChatMessage({conversationId:s,identityId:t,content:{text:i},clientMessageId:c});if(n!==o.current)return;p([f(g)])}catch{n===o.current&&l("Failed to send message")}})(),!0},[e,t,s,r,p]);return{messages:U,isLoading:S,isConnected:a,error:k,sendMessage:m}};var $=q;export{$ as default};
|
|
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": "AAAA,OAAOA,MAAU,cACjB,OAAS,eAAAC,EAAa,aAAAC,EAAW,UAAAC,EAAQ,YAAAC,MAAgB,QAGzD,OAAOC,MAAsB,0BAC7B,OAAS,gBAAAC,MAAoB,
|
|
6
|
-
"names": ["uuid", "useCallback", "useEffect", "useRef", "useState", "useDashXProvider", "useWebSocket", "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": "AAAA,OAAOA,MAAU,cACjB,OAAS,eAAAC,EAAa,aAAAC,EAAW,UAAAC,EAAQ,YAAAC,MAAgB,QAGzD,OAAOC,MAAsB,0BAC7B,OAAS,gBAAAC,MAAoB,gCA+C7B,MAAMC,EAAsB,4BAEtBC,EAAeC,IAAqD,CACxE,GAAIA,EAAQ,GAGZ,YAAaA,EA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,gBAAiB,CAAE,KAAAD,CAAK,EACxB,OAAQ,OACR,UAAW,IAAI,KAAK,EAAE,YAAY,EAClC,UAAW,EACb,EACA,OAAAV,EAAe,CAACY,CAAU,CAAC,GAErB,SAAY,CAChB,GAAI,CACF,MAAMC,EAAgB,MAAMxB,EAAM,qBAAqB,CACrD,eAAAH,EACA,WAAAD,EACA,QAAS,CAAE,KAAAyB,CAAK,EAChB,gBAAAC,CACF,CAAC,EACD,GAAIT,IAAeJ,EAAc,QAAS,OAE1CE,EAAe,CAAC1B,EAAYuC,CAAa,CAAC,CAAC,CAC7C,MAAQ,CACFX,IAAeJ,EAAc,SAASD,EAAS,wBAAwB,CAC7E,CACF,GAAG,EAGI,EACT,EACA,CAACR,EAAOJ,EAAYC,EAAgBC,EAASa,CAAc,CAC7D,EAEA,MAAO,CAAE,SAAAR,EAAU,UAAAE,EAAW,YAAAJ,EAAa,MAAAM,EAAO,YAAAa,CAAY,CAChE,EAIA,IAAOK,EAAQ9B",
|
|
6
|
+
"names": ["uuid", "useCallback", "useEffect", "useRef", "useState", "useDashXProvider", "useWebSocket", "CHAT_CHANNEL_PREFIX", "toUiMessage", "message", "mergeMessages", "existing", "incoming", "byKey", "keyOf", "existingForKey", "a", "b", "useInAppChat", "identityId", "conversationId", "enabled", "onInboundMessage", "dashX", "isConnected", "initializeWebSocket", "messages", "setMessages", "isLoading", "setIsLoading", "error", "setError", "generationRef", "onInboundMessageRef", "appendMessages", "prev", "generation", "isStale", "unsubscribe", "refetchHistory", "history", "subscription", "event", "sendMessage", "text", "clientMessageId", "optimistic", "serverMessage", "use_in_app_chat_default"]
|
|
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
|
-
import{jsx as e,jsxs as p}from"react/jsx-runtime";import*as n from"@radix-ui/react-scroll-area";import{useEffect as v,useState as w}from"react";import{Send as N,X as P}from"lucide-react";import{Button as
|
|
1
|
+
import{jsx as e,jsxs as p}from"react/jsx-runtime";import*as n from"@radix-ui/react-scroll-area";import{useEffect as v,useState as w}from"react";import{Send as N,X as P}from"lucide-react";import{Button as f,Flex as s,Heading as T,Popover as S,Text as d,TextArea as k,Theme as H}from"../components";import{cn as b}from"../utils/cn.js";import R from"../hooks/use-auto-scroll.js";import U from"../hooks/use-in-app-chat.js";import z from"../hooks/use-in-app-chat-notifications.js";const M=o=>{const a=o.renderedContent;return typeof a=="string"?a:a?.text??""},O=o=>o.aiRole?.toUpperCase()==="USER",x=({messages:o,isLoading:a,error:r,sendMessage:i,withChatHeader:u=!1,withPopoverClose:m=!1,borderless:y=!1,title:C="Chat"})=>{const[l,c]=w(""),{scrollAreaRef:A,scrollToBottom:h}=R();v(()=>{setTimeout(()=>h({smooth:!0}),0)},[o.length,h]);const g=()=>{l.trim()&&i(l)&&c("")},I=t=>{t.key==="Enter"&&!t.shiftKey&&(t.preventDefault(),g())};return e(H,{asChild:!0,children:p(s,{direction:"column",className:b("h-full",!y&&"border border-gray-400/40"),children:[u&&p(s,{align:"center",justify:"between",className:"border-b border-b-gray-400/40 px-6 py-4",children:[e(T,{size:3,children:C}),m&&e(S.Close,{children:e(f,{shape:"square",roundness:"full",variant:"ghost",mode:"subtle",inset:"right",children:e(P,{})})})]}),e(s,{direction:"column",className:"grow overflow-auto bg-gray-50",children:p(n.Root,{ref:A,className:"h-full grow p-6",children:[e(n.Viewport,{className:"h-full",children:p(s,{direction:"column",gap:3,children:[o.map(t=>e("div",{className:b("max-w-[80%] rounded-lg py-2 px-3",O(t)?"bg-accent-600 ml-auto items-end text-white":"bg-gray-200 mr-auto items-start text-gray-900"),children:e(d,{as:"p",size:2,children:M(t)})},t.externalUid||t.id)),a&&e(d,{as:"p",size:2,className:"mr-auto text-gray-500",children:"Loading\u2026"}),r&&e(d,{as:"p",size:2,className:"bg-negative-100 text-negative-900 mx-auto rounded-lg py-2 px-3",children:r})]})}),e(n.Scrollbar,{orientation:"vertical",className:"w-1 bg-gray-200 opacity-50",children:e(n.Thumb,{className:"flex-1 rounded-2xl bg-gray-400"})}),e(n.Corner,{})]})}),e("div",{className:"shrink-0 grow-0 border-t border-t-gray-400/40",children:p(s,{gap:2,align:"end",className:"w-full",children:[e("div",{className:"w-full [&_textarea]:border-none! [&_textarea]:outline-none!",children:e(k,{"aria-label":"message",size:"extralarge",placeholder:"Type a message\u2026",value:l,onKeyDown:I,onChange:t=>c(t),roundness:"none",autogrow:!0})}),e("div",{className:"mr-[7px] mb-[7px]",children:e(f,{shape:"square",roundness:"full",variant:"fill",size:"medium",onPress:g,isDisabled:!l.trim(),children:e(N,{size:20})})})]})})]})})},E=({identityId:o,conversationId:a,notifications:r=!0,...i})=>{const u=z({isOpen:!0,enabled:r!==!1,options:{requestPermissionOn:"manual",...typeof r=="object"?r:void 0}}),m=U({identityId:o,conversationId:a,onInboundMessage:u.handleInboundMessage});return e(x,{...m,...i})};var _=E;export{x as InAppChat,_ as default};
|
|
2
2
|
//# sourceMappingURL=InAppChat.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/widgets/InAppChat.tsx"],
|
|
4
|
-
"sourcesContent": ["import * as ScrollArea from '@radix-ui/react-scroll-area';\nimport React, { useEffect, useState } from 'react';\nimport { Send, X } from 'lucide-react';\nimport type { KeyboardEvent } from 'react';\n\nimport { Button, Flex, Heading, Popover, Text, TextArea, Theme } from '../components';\nimport { cn } from '../utils/cn.js';\nimport useAutoScroll from '../hooks/use-auto-scroll.js';\nimport useInAppChat, {\n type InAppChatMessage,\n type UseInAppChatHookProps,\n type UseInAppChatHookResponse,\n} from '../hooks/use-in-app-chat.js';\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": "AAqEU,OACE,OAAAA,EADF,QAAAC,MAAA,oBArEV,UAAYC,MAAgB,8BAC5B,OAAgB,aAAAC,EAAW,YAAAC,MAAgB,QAC3C,OAAS,QAAAC,EAAM,KAAAC,MAAS,eAGxB,OAAS,UAAAC,EAAQ,QAAAC,EAAM,WAAAC,EAAS,WAAAC,EAAS,QAAAC,EAAM,YAAAC,EAAU,SAAAC,MAAa,gBACtE,OAAS,MAAAC,MAAU,iBACnB,OAAOC,MAAmB,8BAC1B,OAAOC,MAIA,8BACP,OAAOC,MAEA,4CASP,MAAMC,EAAeC,GAAsC,CACzD,MAAMC,EAAUD,EAAQ,gBACxB,OAAI,OAAOC,GAAY,SAAiBA,EACjCA,GAAS,MAAQ,EAC1B,EAEMC,EAAcF,GAAuCA,EAAQ,QAAQ,YAAY,IAAM,OAEvFG,EAAY,CAAC,CACjB,SAAAC,EACA,UAAAC,EACA,MAAAC,EACA,YAAAC,EACA,eAAAC,EAAiB,GACjB,iBAAAC,EAAmB,GACnB,WAAAC,EAAa,GACb,MAAAC,EAAQ,MACV,IAAsB,CACpB,KAAM,CAACC,EAAYC,CAAa,EAAI5B,EAAS,EAAE,EACzC,CAAE,cAAA6B,EAAe,eAAAC,CAAe,EAAInB,EAAc,EAExDZ,EAAU,IAAM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GDc,GACCzB,EAACW,EAAA,CACC,GAAG,IACH,KAAM,EACN,UAAU,iEAET,SAAAc,EACH,GAEJ,EACF,EACAzB,EAACE,EAAW,UAAX,CAAqB,YAAY,WAAW,UAAU,6BACrD,SAAAF,EAACE,EAAW,MAAX,CAAiB,UAAU,iCAAiC,EAC/D,EACAF,EAACE,EAAW,OAAX,EAAkB,GACrB,EACF,EAEAF,EAAC,OAAI,UAAU,gDACb,SAAAC,EAACO,EAAA,CAAK,IAAK,EAAG,MAAM,MAAM,UAAU,SAClC,UAAAR,EAAC,OAAI,UAAU,8DACb,SAAAA,EAACY,EAAA,CACC,aAAW,UACX,KAAK,aACL,YAAY,uBACZ,MAAOmB,EACP,UAAWK,EACX,SAAWE,GAASN,EAAcM,CAAI,EACtC,UAAU,OACV,SAAQ,GACV,EACF,EACAtC,EAAC,OAAI,UAAU,oBACb,SAAAA,EAACO,EAAA,CACC,MAAM,SACN,UAAU,OACV,QAAQ,OACR,KAAK,SACL,QAAS4B,EACT,WAAY,CAACJ,EAAW,KAAK,EAE7B,SAAA/B,EAACK,EAAA,CAAK,KAAM,GAAI,EAClB,EACF,GACF,EACF,GACF,EACF,CAEJ,
|
|
6
|
-
"names": ["jsx", "jsxs", "ScrollArea", "useEffect", "useState", "Send", "X", "Button", "Flex", "Heading", "Popover", "Text", "TextArea", "Theme", "cn", "useAutoScroll", "useInAppChat", "useInAppChatNotifications", "messageText", "message", "content", "isOutgoing", "InAppChat", "messages", "isLoading", "error", "sendMessage", "withChatHeader", "withPopoverClose", "borderless", "title", "inputValue", "setInputValue", "scrollAreaRef", "scrollToBottom", "handleSubmit", "handleKeyDown", "e", "text", "InAppChatWrapper", "identityId", "
|
|
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": "AAqEU,OACE,OAAAA,EADF,QAAAC,MAAA,oBArEV,UAAYC,MAAgB,8BAC5B,OAAgB,aAAAC,EAAW,YAAAC,MAAgB,QAC3C,OAAS,QAAAC,EAAM,KAAAC,MAAS,eAGxB,OAAS,UAAAC,EAAQ,QAAAC,EAAM,WAAAC,EAAS,WAAAC,EAAS,QAAAC,EAAM,YAAAC,EAAU,SAAAC,MAAa,gBACtE,OAAS,MAAAC,MAAU,iBACnB,OAAOC,MAAmB,8BAC1B,OAAOC,MAIA,8BACP,OAAOC,MAEA,4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AAgB,cAAAC,EAAgB,GAAM,GAAGC,CAAM,IAA6B,CAIlH,MAAMC,EAAW3B,EAA0B,CACzC,OAAQ,GACR,QAASyB,IAAkB,GAC3B,QAAS,CACP,oBAAqB,SACrB,GAAI,OAAOA,GAAkB,SAAWA,EAAgB,MAC1D,CACF,CAAC,EACKG,EAAO7B,EAAa,CACxB,WAAAwB,EACA,eAAAC,EACA,iBAAkBG,EAAS,oBAC7B,CAAC,EACD,OAAO5C,EAACsB,EAAA,CAAW,GAAGuB,EAAO,GAAGF,EAAO,CACzC,EAMA,IAAOG,EAAQP",
|
|
6
|
+
"names": ["jsx", "jsxs", "ScrollArea", "useEffect", "useState", "Send", "X", "Button", "Flex", "Heading", "Popover", "Text", "TextArea", "Theme", "cn", "useAutoScroll", "useInAppChat", "useInAppChatNotifications", "messageText", "message", "content", "isOutgoing", "InAppChat", "messages", "isLoading", "error", "sendMessage", "withChatHeader", "withPopoverClose", "borderless", "title", "inputValue", "setInputValue", "scrollAreaRef", "scrollToBottom", "handleSubmit", "handleKeyDown", "e", "text", "InAppChatWrapper", "identityId", "conversationId", "notifications", "props", "notifier", "chat", "InAppChat_default"]
|
|
7
7
|
}
|
|
@@ -7,6 +7,6 @@ type InAppChatButtonProps = InAppChatWrapperProps & {
|
|
|
7
7
|
/** Theme overrides for the launcher + chat surface (accent color, mode, roundness, …). */
|
|
8
8
|
theme?: ThemeProps;
|
|
9
9
|
};
|
|
10
|
-
declare const InAppChatButton: ({ identityId,
|
|
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
|
-
import{jsx as t,jsxs as
|
|
1
|
+
import{jsx as t,jsxs as S}from"react/jsx-runtime";import{useCallback as i,useRef as b,useState as I}from"react";import{MessageCircle as A}from"lucide-react";import{Button as O,Flex as v,Popover as p,Theme as T}from"../components";import{InAppChat as y}from"./InAppChat.js";import B from"../hooks/use-in-app-chat.js";import R from"../hooks/use-in-app-chat-notifications.js";const x={"bottom-right":"right-4 bottom-4","bottom-left":"left-4 bottom-4","top-right":"right-4 top-4","top-left":"left-4 top-4"},L=({identityId:h,conversationId:l,notifications:e=!0,position:u="bottom-right",theme:m,...f})=>{const[o,n]=I(!1),r=b(!1);o&&(r.current=!0);const c=r.current,g=i(()=>n(!0),[]),{handleInboundMessage:C,requestPermissionOnOpen:s}=R({isOpen:o,enabled:e!==!1,options:typeof e=="object"?e:void 0,onActivate:g}),P=i(a=>{a&&s(),n(a)},[s]),d=B({identityId:h,conversationId:l,enabled:c,onInboundMessage:C});return t(T,{...m,children:t(v,{className:`fixed z-50 ${x[u]}`,children:S(p.Root,{open:o,onOpenChange:P,children:[t(p.Trigger,{children:t(O,{shape:"square",roundness:"full",variant:"fill",size:"large",children:t(A,{})})}),t(p.Content,{spacing:"large",width:"350px",height:"450px",children:t(y,{...d,borderless:!0,withChatHeader:!0,withPopoverClose:!0,...f})})]})})})};var k=L;export{k as default};
|
|
2
2
|
//# sourceMappingURL=InAppChatButton.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/widgets/InAppChatButton.tsx"],
|
|
4
|
-
"sourcesContent": ["import React, { 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": "AA2EQ,OAGM,OAAAA,EAHN,QAAAC,MAAA,oBA3ER,OAAgB,eAAAC,EAAa,UAAAC,EAAQ,YAAAC,MAAgB,QACrD,OAAS,iBAAAC,MAAqB,eAE9B,OAAS,UAAAC,EAAQ,QAAAC,EAAM,WAAAC,EAAS,SAAAC,MAA8B,gBAC9D,OAAS,aAAAC,MAA6C,iBACtD,OAAOC,MAAkB,8BACzB,OAAOC,MAA+B,4CAYtC,MAAMC,EAAmD,CACvD,eAAgB,mBAChB,cAAe,kBACf,YAAa,gBACb,WAAY,cACd,EAEMC,EAAkB,CAAC,CACvB,WAAAC,EACA,eAAAC,EACA,
|
|
6
|
-
"names": ["jsx", "jsxs", "useCallback", "useRef", "useState", "MessageCircle", "Button", "Flex", "Popover", "Theme", "InAppChat", "useInAppChat", "useInAppChatNotifications", "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": "AA2EQ,OAGM,OAAAA,EAHN,QAAAC,MAAA,oBA3ER,OAAgB,eAAAC,EAAa,UAAAC,EAAQ,YAAAC,MAAgB,QACrD,OAAS,iBAAAC,MAAqB,eAE9B,OAAS,UAAAC,EAAQ,QAAAC,EAAM,WAAAC,EAAS,SAAAC,MAA8B,gBAC9D,OAAS,aAAAC,MAA6C,iBACtD,OAAOC,MAAkB,8BACzB,OAAOC,MAA+B,4CAYtC,MAAMC,EAAmD,CACvD,eAAgB,mBAChB,cAAe,kBACf,YAAa,gBACb,WAAY,cACd,EAEMC,EAAkB,CAAC,CACvB,WAAAC,EACA,eAAAC,EACA,cAAAC,EAAgB,GAChB,SAAAC,EAAW,eACX,MAAAC,EACA,GAAGC,CACL,IAA4B,CAC1B,KAAM,CAACC,EAAQC,CAAS,EAAIlB,EAAS,EAAK,EAQpCmB,EAAepB,EAAO,EAAK,EAC7BkB,IAAQE,EAAa,QAAU,IACnC,MAAMC,EAAUD,EAAa,QAEvBE,EAAOvB,EAAY,IAAMoB,EAAU,EAAI,EAAG,CAAC,CAAC,EAE5C,CAAE,qBAAAI,EAAsB,wBAAAC,CAAwB,EAAIf,EAA0B,CAClF,OAAAS,EACA,QAASJ,IAAkB,GAC3B,QAAS,OAAOA,GAAkB,SAAWA,EAAgB,OAC7D,WAAYQ,CACd,CAAC,EAKKG,EAAmB1B,EACtB2B,GAAsB,CACjBA,GAAUF,EAAwB,EACtCL,EAAUO,CAAQ,CACpB,EACA,CAACF,CAAuB,CAC1B,EAEMG,EAAOnB,EAAa,CACxB,WAAAI,EACA,eAAAC,EACA,QAAAQ,EACA,iBAAkBE,CACpB,CAAC,EAED,OACE1B,EAACS,EAAA,CAAO,GAAGU,EACT,SAAAnB,EAACO,EAAA,CAAK,UAAW,cAAcM,EAAeK,CAAQ,CAAC,GACrD,SAAAjB,EAACO,EAAQ,KAAR,CAAa,KAAMa,EAAQ,aAAcO,EACxC,UAAA5B,EAACQ,EAAQ,QAAR,CACC,SAAAR,EAACM,EAAA,CAAO,MAAM,SAAS,UAAU,OAAO,QAAQ,OAAO,KAAK,QAC1D,SAAAN,EAACK,EAAA,EAAc,EACjB,EACF,EAKAL,EAACQ,EAAQ,QAAR,CAAgB,QAAQ,QAAQ,MAAM,QAAQ,OAAO,QACpD,SAAAR,EAACU,EAAA,CACE,GAAGoB,EACJ,WAAU,GACV,eAAc,GACd,iBAAgB,GACf,GAAGV,EACN,EACF,GACF,EACF,EACF,CAEJ,EAIA,IAAOW,EAAQjB",
|
|
6
|
+
"names": ["jsx", "jsxs", "useCallback", "useRef", "useState", "MessageCircle", "Button", "Flex", "Popover", "Theme", "InAppChat", "useInAppChat", "useInAppChatNotifications", "POSITION_CLASS", "InAppChatButton", "identityId", "conversationId", "notifications", "position", "theme", "props", "isOpen", "setIsOpen", "hasOpenedRef", "enabled", "open", "handleInboundMessage", "requestPermissionOnOpen", "handleOpenChange", "nextOpen", "chat", "InAppChatButton_default"]
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dashx/react",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"license": "UNLICENSED",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"main": "./dist/cjs/index.js",
|
|
@@ -75,7 +75,7 @@
|
|
|
75
75
|
"clean": "rm -rf .turbo node_modules dist tokens layout *.css"
|
|
76
76
|
},
|
|
77
77
|
"dependencies": {
|
|
78
|
-
"@dashx/browser": "^0.
|
|
78
|
+
"@dashx/browser": "^0.10.0",
|
|
79
79
|
"@radix-ui/colors": "^3.0.0",
|
|
80
80
|
"@radix-ui/primitive": "^1.1.3",
|
|
81
81
|
"@radix-ui/react-accessible-icon": "^1.1.8",
|
|
@@ -9,17 +9,15 @@ type UseInAppChatHookProps = {
|
|
|
9
9
|
// The workspace's chat-identity id (the receiving surface), created when the
|
|
10
10
|
// chat integration is installed; pasted into config alongside the public key.
|
|
11
11
|
identityId: string;
|
|
12
|
-
//
|
|
13
|
-
//
|
|
14
|
-
|
|
15
|
-
//
|
|
16
|
-
|
|
17
|
-
//
|
|
18
|
-
|
|
19
|
-
//
|
|
20
|
-
//
|
|
21
|
-
// first opens the launcher, while keeping the hook mounted afterwards so its
|
|
22
|
-
// subscription (and thus notifications) survive the panel being closed.
|
|
12
|
+
// The conversation to participate in. This hook does NOT create conversations:
|
|
13
|
+
// creating one is server-only (DashX rejects identity-token callers), so your
|
|
14
|
+
// backend creates it and hands you the id. Pass `null` while you don't have one
|
|
15
|
+
// yet — the hook stays idle rather than guessing.
|
|
16
|
+
conversationId: string | null;
|
|
17
|
+
// When false, the hook is idle: nothing is subscribed or fetched. Lets
|
|
18
|
+
// `<InAppChatButton>` defer the subscription until the visitor first opens the
|
|
19
|
+
// launcher, while keeping the hook mounted afterwards so its subscription (and
|
|
20
|
+
// thus notifications) survive the panel being closed.
|
|
23
21
|
enabled?: boolean;
|
|
24
22
|
// Invoked once per LIVE inbound message (not for history load / reconnect
|
|
25
23
|
// refetch). Drives browser notifications without having to diff backfilled
|
|
@@ -41,14 +39,14 @@ type InAppChatMessage = {
|
|
|
41
39
|
};
|
|
42
40
|
|
|
43
41
|
type UseInAppChatHookResponse = {
|
|
44
|
-
conversationId: string | null;
|
|
45
42
|
messages: InAppChatMessage[];
|
|
46
43
|
isLoading: boolean;
|
|
47
44
|
isConnected: boolean;
|
|
48
45
|
error: string | null;
|
|
49
46
|
// Returns `true` if the message was optimistically queued, `false` if the chat
|
|
50
|
-
// wasn't ready (no
|
|
51
|
-
// composer immediately on `true`; callers keep the input populated on
|
|
47
|
+
// wasn't ready (no `conversationId`, or disabled). Synchronous so the caller can
|
|
48
|
+
// clear the composer immediately on `true`; callers keep the input populated on
|
|
49
|
+
// `false`.
|
|
52
50
|
sendMessage: (text: string) => boolean;
|
|
53
51
|
};
|
|
54
52
|
|
|
@@ -91,31 +89,33 @@ const mergeMessages = (
|
|
|
91
89
|
};
|
|
92
90
|
|
|
93
91
|
/**
|
|
94
|
-
* Two-way InApp Chat
|
|
92
|
+
* Two-way InApp Chat within an EXISTING conversation.
|
|
93
|
+
*
|
|
94
|
+
* This hook participates; it never creates. Creating a conversation is a
|
|
95
|
+
* server-only operation — DashX rejects identity-token callers and requires an
|
|
96
|
+
* `accountUid` the browser has no authority to assert, and the conversation's
|
|
97
|
+
* metadata must be derived server-side. So the flow is: your backend creates the
|
|
98
|
+
* conversation (e.g. via `dashx-java`) and returns its id; you pass that id here.
|
|
95
99
|
*
|
|
96
100
|
* PREREQUISITE: the surrounding `<DashXProvider>` must already have a valid
|
|
97
|
-
* `identityToken` (and matching `identityUid`).
|
|
98
|
-
* identity-token auth — if
|
|
99
|
-
* are rejected and the hook surfaces an
|
|
100
|
-
* a token arrives later (its inputs are `identityId`/`
|
|
101
|
-
* visitor token), so only render the chat once `identityToken` is available —
|
|
102
|
-
*
|
|
103
|
-
* this by starting lazily when the visitor opens it, by which point the provider
|
|
104
|
-
* has applied the token.
|
|
101
|
+
* `identityToken` (and matching `identityUid`). Fetching history, sending, and
|
|
102
|
+
* subscribing all require identity-token auth — if they run before an identity is
|
|
103
|
+
* resolved they are rejected and the hook surfaces an error. It does NOT auto-retry
|
|
104
|
+
* when a token arrives later (its inputs are `identityId`/`conversationId`, not the
|
|
105
|
+
* visitor token), so only render the chat once `identityToken` is available — e.g.
|
|
106
|
+
* `{identityToken && <InAppChat … />}`.
|
|
105
107
|
*/
|
|
106
|
-
const useInAppChat = ({ identityId,
|
|
108
|
+
const useInAppChat = ({ identityId, conversationId, enabled = true, onInboundMessage }: UseInAppChatHookProps): UseInAppChatHookResponse => {
|
|
107
109
|
const dashX = useDashXProvider();
|
|
108
110
|
const { isConnected, initializeWebSocket } = useWebSocket();
|
|
109
111
|
|
|
110
|
-
const [conversationId, setConversationId] = useState<string | null>(null);
|
|
111
112
|
const [messages, setMessages] = useState<InAppChatMessage[]>([]);
|
|
112
113
|
const [isLoading, setIsLoading] = useState(true);
|
|
113
114
|
const [error, setError] = useState<string | null>(null);
|
|
114
115
|
|
|
115
|
-
// Bumped on every identity/
|
|
116
|
-
// resolutions are ignored (the classic React async race).
|
|
116
|
+
// Bumped on every identity/conversation change and on unmount so stale
|
|
117
|
+
// fetch/send resolutions are ignored (the classic React async race).
|
|
117
118
|
const generationRef = useRef(0);
|
|
118
|
-
const conversationIdRef = useRef<string | null>(null);
|
|
119
119
|
|
|
120
120
|
// Latest live-message callback, kept in a ref so changing its identity doesn't
|
|
121
121
|
// tear down and re-create the channel subscription.
|
|
@@ -130,14 +130,12 @@ const useInAppChat = ({ identityId, idempotencyKey, initialMessage, enabled = tr
|
|
|
130
130
|
const generation = (generationRef.current += 1);
|
|
131
131
|
const isStale = () => generation !== generationRef.current;
|
|
132
132
|
|
|
133
|
-
setConversationId(null);
|
|
134
133
|
setMessages([]);
|
|
135
134
|
setError(null);
|
|
136
|
-
conversationIdRef.current = null;
|
|
137
135
|
|
|
138
|
-
// Idle until enabled (e.g. before the launcher's first open)
|
|
139
|
-
// conversation
|
|
140
|
-
if (!enabled) {
|
|
136
|
+
// Idle until enabled (e.g. before the launcher's first open) and until the
|
|
137
|
+
// caller has a conversation to join: don't subscribe or fetch.
|
|
138
|
+
if (!enabled || !conversationId) {
|
|
141
139
|
setIsLoading(false);
|
|
142
140
|
return () => { generationRef.current += 1; };
|
|
143
141
|
}
|
|
@@ -151,34 +149,8 @@ const useInAppChat = ({ identityId, idempotencyKey, initialMessage, enabled = tr
|
|
|
151
149
|
|
|
152
150
|
(async () => {
|
|
153
151
|
try {
|
|
154
|
-
// `content` + `clientMessageId` travel together: `StartInAppChatConversationArgs`
|
|
155
|
-
// is a union of "empty start" and "start with a first message", because the
|
|
156
|
-
// backend rejects metadata with no message to attach it to. The branch must
|
|
157
|
-
// therefore stay OUTSIDE the object literal — a conditional spread collapses to
|
|
158
|
-
// `content?: … | undefined` and loses the correlation, matching neither arm.
|
|
159
|
-
//
|
|
160
|
-
// Stable client message id → the automated message is inserted once, even if the
|
|
161
|
-
// conversation is reopened (the server dedups repeat sends). `-` separator
|
|
162
|
-
// (client ids allow only `[A-Za-z0-9._-]`); the key is truncated so the suffixed
|
|
163
|
-
// id stays within the 1-128 char limit.
|
|
164
|
-
const startArgs = initialMessage
|
|
165
|
-
? {
|
|
166
|
-
identityId,
|
|
167
|
-
clientIdempotencyKey: idempotencyKey,
|
|
168
|
-
content: { text: initialMessage },
|
|
169
|
-
clientMessageId: `${idempotencyKey.slice(0, 122)}-intro`,
|
|
170
|
-
}
|
|
171
|
-
: { identityId, clientIdempotencyKey: idempotencyKey };
|
|
172
|
-
|
|
173
|
-
const conversation = await dashX.startInAppChatConversation(startArgs);
|
|
174
|
-
if (isStale()) return;
|
|
175
|
-
|
|
176
|
-
const convId = conversation.id;
|
|
177
|
-
setConversationId(convId);
|
|
178
|
-
conversationIdRef.current = convId;
|
|
179
|
-
|
|
180
152
|
const refetchHistory = async () => {
|
|
181
|
-
const history = await dashX.fetchInAppChatMessages({ conversationId
|
|
153
|
+
const history = await dashX.fetchInAppChatMessages({ conversationId });
|
|
182
154
|
if (isStale()) return;
|
|
183
155
|
appendMessages(history.map(toUiMessage));
|
|
184
156
|
};
|
|
@@ -188,7 +160,7 @@ const useInAppChat = ({ identityId, idempotencyKey, initialMessage, enabled = tr
|
|
|
188
160
|
// on a first ack that arrives after a `ready` timeout — both mean we are
|
|
189
161
|
// (now) subscribed, so clear any connection error and (re)load history.
|
|
190
162
|
const subscription = dashX.subscribeToChannel(
|
|
191
|
-
`${CHAT_CHANNEL_PREFIX}${
|
|
163
|
+
`${CHAT_CHANNEL_PREFIX}${conversationId}`,
|
|
192
164
|
(event) => {
|
|
193
165
|
if (isStale()) return;
|
|
194
166
|
appendMessages([toUiMessage(event)]);
|
|
@@ -220,7 +192,7 @@ const useInAppChat = ({ identityId, idempotencyKey, initialMessage, enabled = tr
|
|
|
220
192
|
if (isStale()) return;
|
|
221
193
|
await refetchHistory();
|
|
222
194
|
} catch {
|
|
223
|
-
if (!isStale()) setError('Failed to
|
|
195
|
+
if (!isStale()) setError('Failed to load chat');
|
|
224
196
|
} finally {
|
|
225
197
|
if (!isStale()) setIsLoading(false);
|
|
226
198
|
}
|
|
@@ -232,7 +204,7 @@ const useInAppChat = ({ identityId, idempotencyKey, initialMessage, enabled = tr
|
|
|
232
204
|
generationRef.current += 1;
|
|
233
205
|
unsubscribe?.();
|
|
234
206
|
};
|
|
235
|
-
}, [dashX, identityId,
|
|
207
|
+
}, [dashX, identityId, conversationId, enabled, initializeWebSocket, appendMessages]);
|
|
236
208
|
|
|
237
209
|
// Synchronous on purpose: it returns `true` the moment the message is optimistically
|
|
238
210
|
// queued and runs the network send in the background. The caller clears the composer
|
|
@@ -241,10 +213,10 @@ const useInAppChat = ({ identityId, idempotencyKey, initialMessage, enabled = tr
|
|
|
241
213
|
// backend won't dedupe it) and create a duplicate.
|
|
242
214
|
const sendMessage = useCallback(
|
|
243
215
|
(text: string): boolean => {
|
|
244
|
-
|
|
245
|
-
//
|
|
246
|
-
//
|
|
247
|
-
if (!text.trim() || !
|
|
216
|
+
// Not ready (no conversation supplied yet, or the hook is disabled) — report
|
|
217
|
+
// back so the caller can keep the typed text instead of clearing it on a
|
|
218
|
+
// no-op send.
|
|
219
|
+
if (!text.trim() || !conversationId || !enabled) return false;
|
|
248
220
|
|
|
249
221
|
// Pin the generation so a response that resolves after the identity/key
|
|
250
222
|
// changed (or unmount) can't contaminate the new conversation's state.
|
|
@@ -263,7 +235,7 @@ const useInAppChat = ({ identityId, idempotencyKey, initialMessage, enabled = tr
|
|
|
263
235
|
void (async () => {
|
|
264
236
|
try {
|
|
265
237
|
const serverMessage = await dashX.sendInAppChatMessage({
|
|
266
|
-
conversationId
|
|
238
|
+
conversationId,
|
|
267
239
|
identityId,
|
|
268
240
|
content: { text },
|
|
269
241
|
clientMessageId,
|
|
@@ -279,10 +251,10 @@ const useInAppChat = ({ identityId, idempotencyKey, initialMessage, enabled = tr
|
|
|
279
251
|
// Queued (optimistically appended) — the background send reconciles/errors later.
|
|
280
252
|
return true;
|
|
281
253
|
},
|
|
282
|
-
[dashX, identityId, appendMessages],
|
|
254
|
+
[dashX, identityId, conversationId, enabled, appendMessages],
|
|
283
255
|
);
|
|
284
256
|
|
|
285
|
-
return {
|
|
257
|
+
return { messages, isLoading, isConnected, error, sendMessage };
|
|
286
258
|
};
|
|
287
259
|
|
|
288
260
|
export type { UseInAppChatHookProps, UseInAppChatHookResponse, InAppChatMessage };
|
|
@@ -154,6 +154,10 @@ const InAppChat = ({
|
|
|
154
154
|
);
|
|
155
155
|
};
|
|
156
156
|
|
|
157
|
+
// `conversationId` is required (inherited from the hook's props): this widget
|
|
158
|
+
// participates in a conversation your BACKEND created — it cannot create one, because
|
|
159
|
+
// creating a chat is server-only in DashX. Pass `null` while you're still fetching the
|
|
160
|
+
// id and the widget renders its empty/loading state instead of guessing.
|
|
157
161
|
type InAppChatWrapperProps = Omit<InAppChatProps, keyof UseInAppChatHookResponse>
|
|
158
162
|
& Omit<UseInAppChatHookProps, 'enabled' | 'onInboundMessage'>
|
|
159
163
|
& {
|
|
@@ -165,7 +169,7 @@ type InAppChatWrapperProps = Omit<InAppChatProps, keyof UseInAppChatHookResponse
|
|
|
165
169
|
notifications?: boolean | InAppChatNotificationOptions;
|
|
166
170
|
};
|
|
167
171
|
|
|
168
|
-
const InAppChatWrapper = ({ identityId,
|
|
172
|
+
const InAppChatWrapper = ({ identityId, conversationId, notifications = true, ...props }: InAppChatWrapperProps) => {
|
|
169
173
|
// Always-visible surface: treat as "open" and gate notifications on tab
|
|
170
174
|
// visibility/focus only. No launcher gesture exists here, so default to
|
|
171
175
|
// 'manual' permission (auto-requesting would prompt on mount).
|
|
@@ -179,8 +183,7 @@ const InAppChatWrapper = ({ identityId, idempotencyKey, initialMessage, notifica
|
|
|
179
183
|
});
|
|
180
184
|
const chat = useInAppChat({
|
|
181
185
|
identityId,
|
|
182
|
-
|
|
183
|
-
initialMessage,
|
|
186
|
+
conversationId,
|
|
184
187
|
onInboundMessage: notifier.handleInboundMessage,
|
|
185
188
|
});
|
|
186
189
|
return <InAppChat {...chat} {...props} />;
|
|
@@ -25,8 +25,7 @@ const POSITION_CLASS: Record<LauncherPosition, string> = {
|
|
|
25
25
|
|
|
26
26
|
const InAppChatButton = ({
|
|
27
27
|
identityId,
|
|
28
|
-
|
|
29
|
-
initialMessage,
|
|
28
|
+
conversationId,
|
|
30
29
|
notifications = true,
|
|
31
30
|
position = 'bottom-right',
|
|
32
31
|
theme,
|
|
@@ -36,8 +35,10 @@ const InAppChatButton = ({
|
|
|
36
35
|
|
|
37
36
|
// Latch: once the launcher has been opened, keep the chat hook active so its
|
|
38
37
|
// channel subscription persists while the panel is closed — that's what lets
|
|
39
|
-
// us notify on replies that land while the panel is shut. Before the first
|
|
40
|
-
//
|
|
38
|
+
// us notify on replies that land while the panel is shut. Before the first open
|
|
39
|
+
// the hook is idle, so a page that never opens the launcher does no chat work
|
|
40
|
+
// (no subscription, no history fetch). It never created a conversation either —
|
|
41
|
+
// the conversation is created by your backend and passed in as `conversationId`.
|
|
41
42
|
const hasOpenedRef = useRef(false);
|
|
42
43
|
if (isOpen) hasOpenedRef.current = true;
|
|
43
44
|
const enabled = hasOpenedRef.current;
|
|
@@ -64,8 +65,7 @@ const InAppChatButton = ({
|
|
|
64
65
|
|
|
65
66
|
const chat = useInAppChat({
|
|
66
67
|
identityId,
|
|
67
|
-
|
|
68
|
-
initialMessage,
|
|
68
|
+
conversationId,
|
|
69
69
|
enabled,
|
|
70
70
|
onInboundMessage: handleInboundMessage,
|
|
71
71
|
});
|
|
@@ -82,7 +82,7 @@ const InAppChatButton = ({
|
|
|
82
82
|
{/* The chat hook lives at the launcher level (above the popover) so its
|
|
83
83
|
subscription survives the panel closing — required to notify on
|
|
84
84
|
replies that arrive while the panel is shut. It activates lazily on
|
|
85
|
-
first open, so
|
|
85
|
+
first open, so a launcher the visitor never opens costs nothing. */}
|
|
86
86
|
<Popover.Content spacing="large" width="350px" height="450px">
|
|
87
87
|
<InAppChat
|
|
88
88
|
{...chat}
|