@dashx/react 0.2.2 → 0.3.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 +35 -0
- package/dist/cjs/hooks/index.d.ts +1 -0
- package/dist/cjs/hooks/index.js +1 -1
- package/dist/cjs/hooks/index.js.map +3 -3
- package/dist/cjs/hooks/use-in-app-chat.d.ts +38 -0
- package/dist/cjs/hooks/use-in-app-chat.js +2 -0
- package/dist/cjs/hooks/use-in-app-chat.js.map +7 -0
- package/dist/cjs/providers/DashXProvider.d.ts +15 -1
- package/dist/cjs/providers/DashXProvider.js +1 -1
- package/dist/cjs/providers/DashXProvider.js.map +3 -3
- package/dist/cjs/widgets/InAppChat.d.ts +13 -0
- package/dist/cjs/widgets/InAppChat.js +2 -0
- package/dist/cjs/widgets/InAppChat.js.map +7 -0
- package/dist/cjs/widgets/InAppChatButton.d.ts +12 -0
- package/dist/cjs/widgets/InAppChatButton.js +2 -0
- package/dist/cjs/widgets/InAppChatButton.js.map +7 -0
- package/dist/cjs/widgets/index.d.ts +2 -0
- package/dist/cjs/widgets/index.js +1 -1
- package/dist/cjs/widgets/index.js.map +3 -3
- package/dist/esm/hooks/index.d.ts +1 -0
- package/dist/esm/hooks/index.js +1 -1
- package/dist/esm/hooks/index.js.map +2 -2
- package/dist/esm/hooks/use-in-app-chat.d.ts +38 -0
- package/dist/esm/hooks/use-in-app-chat.js +2 -0
- package/dist/esm/hooks/use-in-app-chat.js.map +7 -0
- package/dist/esm/providers/DashXProvider.d.ts +15 -1
- package/dist/esm/providers/DashXProvider.js +1 -1
- package/dist/esm/providers/DashXProvider.js.map +3 -3
- package/dist/esm/widgets/InAppChat.d.ts +13 -0
- package/dist/esm/widgets/InAppChat.js +2 -0
- package/dist/esm/widgets/InAppChat.js.map +7 -0
- package/dist/esm/widgets/InAppChatButton.d.ts +12 -0
- package/dist/esm/widgets/InAppChatButton.js +2 -0
- package/dist/esm/widgets/InAppChatButton.js.map +7 -0
- package/dist/esm/widgets/index.d.ts +2 -0
- package/dist/esm/widgets/index.js +1 -1
- package/dist/esm/widgets/index.js.map +2 -2
- package/package.json +2 -2
- package/src/hooks/index.ts +1 -0
- package/src/hooks/use-in-app-chat.ts +254 -0
- package/src/providers/DashXProvider.tsx +80 -12
- package/src/widgets/InAppChat.tsx +165 -0
- package/src/widgets/InAppChatButton.tsx +59 -0
- package/src/widgets/index.ts +2 -0
- package/styles.css +6 -0
- package/dist/cjs/widgets/NotificationBell.d.ts +0 -2
- package/dist/cjs/widgets/NotificationBell.js +0 -2
- package/dist/cjs/widgets/NotificationBell.js.map +0 -7
- package/dist/esm/widgets/NotificationBell.d.ts +0 -2
- package/dist/esm/widgets/NotificationBell.js +0 -2
- package/dist/esm/widgets/NotificationBell.js.map +0 -7
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/providers/DashXProvider.tsx"],
|
|
4
|
-
"sourcesContent": ["import DashX from '@dashx/browser';\nimport React, { createContext, useContext, useEffect, useRef, useState, useCallback } from 'react';\nimport type { Client, ClientParams, WebSocketManager, WebsocketMessageType } from '@dashx/browser';\n\nconst DashXContext = createContext<Client | null>(null);\n\ntype WebSocketContextType = {\n isConnected: boolean;\n subscribe: (callback: (message: WebsocketMessageType) => void) => () => void;\n wsManagerRef: React.RefObject<WebSocketManager>;\n initializeWebSocket: (queryParams?: Record<string, any>) => void;\n};\n\nconst WebSocketContext = createContext<WebSocketContextType | null>(null);\n\ntype DashXProviderProps = ClientParams & {\n initializeWebSocketOnLoad?: boolean,\n webSocketQueryParams?: Record<string, any
|
|
5
|
-
"mappings": "
|
|
6
|
-
"names": ["jsx", "DashX", "React", "createContext", "useContext", "useEffect", "useRef", "useState", "useCallback", "DashXContext", "WebSocketContext", "DashXProvider", "children", "publicKey", "baseUri", "realtimeBaseUri", "targetEnvironment", "targetProduct", "targetVersion", "initializeWebSocketOnLoad", "webSocketQueryParams", "dashX", "isConnected", "setIsConnected", "wsManagerRef", "subscribersRef", "subscribe", "callback", "initializeWebSocket", "customQueryParams", "queryParams", "wsManager", "errorEvent", "closeEvent", "message", "error", "attempt", "useWebSocket", "context", "DashXProvider_default"]
|
|
4
|
+
"sourcesContent": ["import DashX from '@dashx/browser';\nimport React, { createContext, useContext, useEffect, useRef, useState, useCallback } from 'react';\nimport type { Client, ClientParams, WebSocketManager, WebsocketMessageType } from '@dashx/browser';\n\nconst DashXContext = createContext<Client | null>(null);\n\ntype WebSocketContextType = {\n isConnected: boolean;\n subscribe: (callback: (message: WebsocketMessageType) => void) => () => void;\n wsManagerRef: React.RefObject<WebSocketManager>;\n initializeWebSocket: (queryParams?: Record<string, any>) => void;\n};\n\nconst WebSocketContext = createContext<WebSocketContextType | null>(null);\n\ntype DashXProviderProps = ClientParams & {\n initializeWebSocketOnLoad?: boolean,\n webSocketQueryParams?: Record<string, any>,\n /**\n * The visitor's account uid, addressed on both transports (GraphQL + WS).\n * Pass `null` to explicitly clear it (e.g. on logout); omit (`undefined`) to\n * leave it unchanged. Pair with `identityToken` for the same identity.\n */\n identityUid?: string | null,\n /**\n * Identity token (minted with your DashX server SDK's `generateIdentityToken`,\n * or from an exchange endpoint you control). When set, the SDK uses it for both\n * GraphQL (`X-Identity-Token` header) and the WebSocket handshake \u2014 the server\n * identifies the visitor from it, which is the ownership key for InApp Chat.\n * Pass `null` to clear it on logout; omit (`undefined`) to leave it unchanged.\n */\n identityToken?: string | null,\n}\n\nfunction DashXProvider({\n children,\n publicKey,\n baseUri,\n realtimeBaseUri,\n targetEnvironment,\n targetProduct,\n targetVersion,\n initializeWebSocketOnLoad = false,\n webSocketQueryParams = {},\n identityUid,\n identityToken,\n}: React.PropsWithChildren<DashXProviderProps>) {\n const dashX = React.useMemo(\n () => {\n const client = DashX.configure({\n publicKey: publicKey,\n baseUri: baseUri,\n realtimeBaseUri: realtimeBaseUri,\n targetEnvironment: targetEnvironment,\n targetProduct,\n targetVersion,\n });\n // Apply identity synchronously at creation so a child that starts work in\n // its own mount effect (child effects run before this provider's effects)\n // sees the token already set. Later prop changes go through the effect\n // below; identity is intentionally not a useMemo dep (we don't recreate\n // the client when it changes).\n if (identityUid !== undefined || identityToken !== undefined) {\n client.setIdentity(identityUid, identityToken);\n }\n return client;\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [publicKey, baseUri, realtimeBaseUri, targetEnvironment, targetProduct, targetVersion],\n );\n\n // `webSocketQueryParams` defaults to a fresh `{}` each render and is a dep of\n // the effects below, so memoize on its content to keep the reference stable \u2014\n // otherwise those effects (setIdentity / WS init) re-run on every render.\n const webSocketQueryParamsKey = JSON.stringify(webSocketQueryParams ?? {});\n const stableWebSocketQueryParams = React.useMemo(\n () => webSocketQueryParams ?? {},\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [webSocketQueryParamsKey],\n );\n\n // WebSocket state\n const [isConnected, setIsConnected] = useState(false);\n const wsManagerRef = useRef<WebSocketManager | null>(null);\n const subscribersRef = useRef<Set<(message: WebsocketMessageType) => void>>(new Set());\n\n const subscribe = useCallback((callback: (message: WebsocketMessageType) => void) => {\n subscribersRef.current.add(callback);\n\n // Return unsubscribe function\n return () => {\n subscribersRef.current.delete(callback);\n };\n }, []);\n\n const initializeWebSocket = useCallback((customQueryParams?: Record<string, any>) => {\n if (!dashX) {\n console.error('DashX client not initialized');\n return;\n }\n\n // Reuse an existing manager \u2014 it owns its own throttled reconnect\n // lifecycle. Tearing it down and creating a new one on every call (e.g.\n // when a consumer re-invokes this as `isConnected` flips to false on each\n // close) resets the per-instance reconnect throttle and reconnects\n // immediately, defeating the backoff. Create one only if none exists.\n if (wsManagerRef.current) {\n return;\n }\n\n const queryParams = {\n publicKey: dashX.publicKey,\n ...(dashX.targetEnvironment && { targetEnvironment: dashX.targetEnvironment }),\n // Provider-level defaults apply to every provider-owned socket \u2014 including\n // when the chat hook (or any consumer) opens the socket first by calling\n // `initializeWebSocket()` with no args. Explicit call-site params override.\n ...stableWebSocketQueryParams,\n ...customQueryParams,\n };\n\n const wsManager = dashX.createWebSocketConnection({\n queryParams,\n onError: (errorEvent: Event) => console.error({ errorEvent }),\n onClose: (closeEvent: CloseEvent) => {\n console.log({ closeEvent });\n setIsConnected(false);\n },\n onMessage: (message: WebsocketMessageType) => {\n // Notify all subscribers\n subscribersRef.current.forEach((callback) => {\n try {\n callback(message);\n } catch (error) {\n console.error('Error in WebSocket subscriber callback:', error);\n }\n });\n },\n onOpen: () => {\n console.log('WebSocket connected successfully');\n setIsConnected(true);\n },\n onReconnect: (attempt: number) => {\n console.log(`WebSocket reconnecting... attempt ${attempt}`);\n },\n onReconnectFailed: () => {\n console.error('WebSocket reconnection failed');\n setIsConnected(false);\n },\n });\n\n wsManagerRef.current = wsManager;\n wsManager.connect();\n }, [dashX, stableWebSocketQueryParams]);\n\n // Forward `identityUid` + `identityToken` into the dashX client so the same\n // identity is used by GraphQL and the WS. Pass the props as-is: `setIdentity`\n // treats `undefined` as \"leave unchanged\", so setting only `identityToken`\n // won't clobber an existing account uid (and vice versa).\n const previousIdentityTokenRef = useRef(identityToken);\n useEffect(() => {\n if (!dashX || (identityUid === undefined && identityToken === undefined)) {\n return;\n }\n\n dashX.setIdentity(identityUid, identityToken);\n\n // This provider owns the socket (created via `createWebSocketConnection`,\n // not the client's internal manager that `setIdentity` reconnects), so on a\n // token change we recreate it here to put the new identity_token in the WS\n // URL. GraphQL picks up the new header on its own; tracked chat channels\n // re-subscribe on the new socket's `onOpen`.\n const tokenChanged = identityToken !== previousIdentityTokenRef.current;\n previousIdentityTokenRef.current = identityToken;\n if (tokenChanged && wsManagerRef.current) {\n wsManagerRef.current.disconnect();\n wsManagerRef.current = null;\n initializeWebSocket(stableWebSocketQueryParams);\n }\n }, [ dashX, identityUid, identityToken, initializeWebSocket, stableWebSocketQueryParams ]);\n\n useEffect(() => {\n if (initializeWebSocketOnLoad) {\n initializeWebSocket(stableWebSocketQueryParams);\n }\n }, [ initializeWebSocketOnLoad, initializeWebSocket, stableWebSocketQueryParams ]);\n\n return (\n <DashXContext.Provider value={dashX}>\n <WebSocketContext.Provider\n value={{\n isConnected,\n subscribe,\n wsManagerRef,\n initializeWebSocket\n }}\n >\n {children}\n </WebSocketContext.Provider>\n </DashXContext.Provider>\n );\n}\n\nexport function useWebSocket() {\n const context = useContext(WebSocketContext);\n if (!context) {\n throw new Error('useWebSocket must be used within a DashXProvider');\n }\n return context;\n}\n\nexport default DashXProvider;\nexport { DashXContext };\n"],
|
|
5
|
+
"mappings": "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",
|
|
6
|
+
"names": ["jsx", "DashX", "React", "createContext", "useContext", "useEffect", "useRef", "useState", "useCallback", "DashXContext", "WebSocketContext", "DashXProvider", "children", "publicKey", "baseUri", "realtimeBaseUri", "targetEnvironment", "targetProduct", "targetVersion", "initializeWebSocketOnLoad", "webSocketQueryParams", "identityUid", "identityToken", "dashX", "client", "webSocketQueryParamsKey", "stableWebSocketQueryParams", "isConnected", "setIsConnected", "wsManagerRef", "subscribersRef", "subscribe", "callback", "initializeWebSocket", "customQueryParams", "queryParams", "wsManager", "errorEvent", "closeEvent", "message", "error", "attempt", "previousIdentityTokenRef", "tokenChanged", "useWebSocket", "context", "DashXProvider_default"]
|
|
7
7
|
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type UseInAppChatHookProps, type UseInAppChatHookResponse } from '../hooks/use-in-app-chat.js';
|
|
2
|
+
type InAppChatProps = UseInAppChatHookResponse & {
|
|
3
|
+
withChatHeader?: boolean;
|
|
4
|
+
withPopoverClose?: boolean;
|
|
5
|
+
borderless?: boolean;
|
|
6
|
+
title?: string;
|
|
7
|
+
};
|
|
8
|
+
declare const InAppChat: ({ messages, isLoading, error, sendMessage, withChatHeader, withPopoverClose, borderless, title, }: InAppChatProps) => import("react/jsx-runtime").JSX.Element;
|
|
9
|
+
type InAppChatWrapperProps = Omit<InAppChatProps, keyof UseInAppChatHookResponse> & UseInAppChatHookProps;
|
|
10
|
+
declare const InAppChatWrapper: ({ identityId, idempotencyKey, initialMessage, ...props }: InAppChatWrapperProps) => import("react/jsx-runtime").JSX.Element;
|
|
11
|
+
export type { InAppChatProps, InAppChatWrapperProps };
|
|
12
|
+
export { InAppChat };
|
|
13
|
+
export default InAppChatWrapper;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{jsx as e,jsxs as n}from"react/jsx-runtime";import*as r from"@radix-ui/react-scroll-area";import{useEffect as I,useState as w}from"react";import{Send as N,X as T}from"lucide-react";import{Button as g,Flex as s,Heading as P,Popover as S,Text as u,TextArea as k,Theme as H}from"../components";import{cn as f}from"../utils/cn.js";import R from"../hooks/use-auto-scroll.js";import U from"../hooks/use-in-app-chat.js";const z=o=>{const a=o.renderedContent;return typeof a=="string"?a:a?.text??""},E=o=>o.aiRole?.toUpperCase()==="USER",x=({messages:o,isLoading:a,error:p,sendMessage:i,withChatHeader:m=!1,withPopoverClose:b=!1,borderless:y=!1,title:C="Chat"})=>{const[l,c]=w(""),{scrollAreaRef:A,scrollToBottom:d}=R();I(()=>{setTimeout(()=>d({smooth:!0}),0)},[o.length,d]);const h=()=>{l.trim()&&i(l)&&c("")},v=t=>{t.key==="Enter"&&!t.shiftKey&&(t.preventDefault(),h())};return e(H,{asChild:!0,children:n(s,{direction:"column",className:f("h-full",!y&&"border border-gray-400/40"),children:[m&&n(s,{align:"center",justify:"between",className:"border-b border-b-gray-400/40 px-6 py-4",children:[e(P,{size:3,children:C}),b&&e(S.Close,{children:e(g,{shape:"square",roundness:"full",variant:"ghost",mode:"subtle",inset:"right",children:e(T,{})})})]}),e(s,{direction:"column",className:"grow overflow-auto bg-gray-50",children:n(r.Root,{ref:A,className:"h-full grow-1 p-6",children:[e(r.Viewport,{className:"h-full",children:n(s,{direction:"column",gap:3,children:[o.map(t=>e("div",{className:f("max-w-[80%] rounded-lg py-2 px-3",E(t)?"bg-accent-600 ml-auto items-end text-white":"bg-gray-200 mr-auto items-start text-gray-900"),children:e(u,{as:"p",size:2,children:z(t)})},t.externalUid||t.id)),a&&e(u,{as:"p",size:2,className:"mr-auto text-gray-500",children:"Loading\u2026"}),p&&e(u,{as:"p",size:2,className:"bg-negative-100 text-negative-900 mx-auto rounded-lg py-2 px-3",children:p})]})}),e(r.Scrollbar,{orientation:"vertical",className:"w-1 bg-gray-200 opacity-50",children:e(r.Thumb,{className:"flex-1 rounded-2xl bg-gray-400"})}),e(r.Corner,{})]})}),e("div",{className:"shrink-0 grow-0 border-t border-t-gray-400/40",children:n(s,{gap:2,align:"end",className:"w-full",children:[e("div",{className:"w-full [&_textarea]:!border-none [&_textarea]:!outline-none",children:e(k,{"aria-label":"message",size:"extralarge",placeholder:"Type a message\u2026",value:l,onKeyDown:v,onChange:t=>c(t),roundness:"none",autogrow:!0})}),e("div",{className:"mr-[7px] mb-[7px]",children:e(g,{shape:"square",roundness:"full",variant:"fill",size:"medium",onPress:h,isDisabled:!l.trim(),children:e(N,{size:20})})})]})})]})})},F=({identityId:o,idempotencyKey:a,initialMessage:p,...i})=>{const m=U({identityId:o,idempotencyKey:a,initialMessage:p});return e(x,{...m,...i})};var L=F;export{x as InAppChat,L as default};
|
|
2
|
+
//# sourceMappingURL=InAppChat.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../src/widgets/InAppChat.tsx"],
|
|
4
|
+
"sourcesContent": ["import * as ScrollArea from '@radix-ui/react-scroll-area';\nimport React, { useEffect, useState } from 'react';\nimport { Send, X } from 'lucide-react';\nimport type { KeyboardEvent } from 'react';\n\nimport { Button, Flex, Heading, Popover, Text, TextArea, Theme } from '../components';\nimport { cn } from '../utils/cn.js';\nimport useAutoScroll from '../hooks/use-auto-scroll.js';\nimport useInAppChat, {\n type InAppChatMessage,\n type UseInAppChatHookProps,\n type UseInAppChatHookResponse,\n} from '../hooks/use-in-app-chat.js';\n\ntype InAppChatProps = UseInAppChatHookResponse & {\n withChatHeader?: boolean;\n withPopoverClose?: boolean;\n borderless?: boolean;\n title?: string;\n};\n\nconst messageText = (message: InAppChatMessage): string => {\n const content = message.renderedContent;\n if (typeof content === 'string') return content;\n return content?.text ?? '';\n};\n\nconst isOutgoing = (message: InAppChatMessage): boolean => message.aiRole?.toUpperCase() === 'USER';\n\nconst InAppChat = ({\n messages,\n isLoading,\n error,\n sendMessage,\n withChatHeader = false,\n withPopoverClose = false,\n borderless = false,\n title = 'Chat',\n}: InAppChatProps) => {\n const [inputValue, setInputValue] = useState('');\n const { scrollAreaRef, scrollToBottom } = useAutoScroll();\n\n useEffect(() => {\n setTimeout(() => scrollToBottom({ smooth: true }), 0);\n }, [messages.length, scrollToBottom]);\n\n const handleSubmit = () => {\n if (!inputValue.trim()) return;\n // `sendMessage` is synchronous: it returns true the instant the message is\n // optimistically queued (network send runs in the background). Clear the\n // composer right away on success so a fast second Enter can't re-send the same\n // text as a duplicate; on false (chat not ready) keep the visitor's text.\n if (sendMessage(inputValue)) setInputValue('');\n };\n\n const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {\n if (e.key === 'Enter' && !e.shiftKey) {\n e.preventDefault();\n handleSubmit();\n }\n };\n\n return (\n <Theme asChild>\n <Flex direction=\"column\" className={cn('h-full', !borderless && 'border border-gray-400/40')}>\n {withChatHeader && (\n <Flex align=\"center\" justify=\"between\" className=\"border-b border-b-gray-400/40 px-6 py-4\">\n <Heading size={3}>{title}</Heading>\n {withPopoverClose && (\n <Popover.Close>\n <Button shape=\"square\" roundness=\"full\" variant=\"ghost\" mode=\"subtle\" inset=\"right\">\n <X />\n </Button>\n </Popover.Close>\n )}\n </Flex>\n )}\n\n <Flex direction=\"column\" className=\"grow overflow-auto bg-gray-50\">\n <ScrollArea.Root ref={scrollAreaRef} className=\"h-full grow-1 p-6\">\n <ScrollArea.Viewport className=\"h-full\">\n <Flex direction=\"column\" gap={3}>\n {messages.map((message) => (\n <div\n key={message.externalUid || message.id}\n className={cn(\n 'max-w-[80%] rounded-lg py-2 px-3',\n isOutgoing(message)\n ? 'bg-accent-600 ml-auto items-end text-white'\n : 'bg-gray-200 mr-auto items-start text-gray-900',\n )}\n >\n <Text as=\"p\" size={2}>{messageText(message)}</Text>\n </div>\n ))}\n\n {isLoading && (\n <Text as=\"p\" size={2} className=\"mr-auto text-gray-500\">\n Loading\u2026\n </Text>\n )}\n\n {error && (\n <Text\n as=\"p\"\n size={2}\n className=\"bg-negative-100 text-negative-900 mx-auto rounded-lg py-2 px-3\"\n >\n {error}\n </Text>\n )}\n </Flex>\n </ScrollArea.Viewport>\n <ScrollArea.Scrollbar orientation=\"vertical\" className=\"w-1 bg-gray-200 opacity-50\">\n <ScrollArea.Thumb className=\"flex-1 rounded-2xl bg-gray-400\" />\n </ScrollArea.Scrollbar>\n <ScrollArea.Corner />\n </ScrollArea.Root>\n </Flex>\n\n <div className=\"shrink-0 grow-0 border-t border-t-gray-400/40\">\n <Flex gap={2} align=\"end\" className=\"w-full\">\n <div className=\"w-full [&_textarea]:!border-none [&_textarea]:!outline-none\">\n <TextArea\n aria-label=\"message\"\n size=\"extralarge\"\n placeholder=\"Type a message\u2026\"\n value={inputValue}\n onKeyDown={handleKeyDown}\n onChange={(text) => setInputValue(text)}\n roundness=\"none\"\n autogrow\n />\n </div>\n <div className=\"mr-[7px] mb-[7px]\">\n <Button\n shape=\"square\"\n roundness=\"full\"\n variant=\"fill\"\n size=\"medium\"\n onPress={handleSubmit}\n isDisabled={!inputValue.trim()}\n >\n <Send size={20} />\n </Button>\n </div>\n </Flex>\n </div>\n </Flex>\n </Theme>\n );\n};\n\ntype InAppChatWrapperProps = Omit<InAppChatProps, keyof UseInAppChatHookResponse> & UseInAppChatHookProps;\n\nconst InAppChatWrapper = ({ identityId, idempotencyKey, initialMessage, ...props }: InAppChatWrapperProps) => {\n const chat = useInAppChat({ identityId, idempotencyKey, initialMessage });\n return <InAppChat {...chat} {...props} />;\n};\n\nexport type { InAppChatProps, InAppChatWrapperProps };\n\nexport { InAppChat };\n\nexport default InAppChatWrapper;\n"],
|
|
5
|
+
"mappings": "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",
|
|
6
|
+
"names": ["jsx", "jsxs", "ScrollArea", "useEffect", "useState", "Send", "X", "Button", "Flex", "Heading", "Popover", "Text", "TextArea", "Theme", "cn", "useAutoScroll", "useInAppChat", "messageText", "message", "content", "isOutgoing", "InAppChat", "messages", "isLoading", "error", "sendMessage", "withChatHeader", "withPopoverClose", "borderless", "title", "inputValue", "setInputValue", "scrollAreaRef", "scrollToBottom", "handleSubmit", "handleKeyDown", "e", "text", "InAppChatWrapper", "identityId", "idempotencyKey", "initialMessage", "props", "chat", "InAppChat_default"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { type ThemeProps } from '../components';
|
|
2
|
+
import { type InAppChatWrapperProps } from './InAppChat.js';
|
|
3
|
+
type LauncherPosition = 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left';
|
|
4
|
+
type InAppChatButtonProps = InAppChatWrapperProps & {
|
|
5
|
+
/** Where the floating launcher sits on screen. Defaults to `bottom-right`. */
|
|
6
|
+
position?: LauncherPosition;
|
|
7
|
+
/** Theme overrides for the launcher + chat surface (accent color, mode, roundness, …). */
|
|
8
|
+
theme?: ThemeProps;
|
|
9
|
+
};
|
|
10
|
+
declare const InAppChatButton: ({ identityId, idempotencyKey, position, theme, ...props }: InAppChatButtonProps) => import("react/jsx-runtime").JSX.Element;
|
|
11
|
+
export type { InAppChatButtonProps };
|
|
12
|
+
export default InAppChatButton;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{jsx as t,jsxs as f}from"react/jsx-runtime";import"react";import{MessageCircle as h}from"lucide-react";import{Button as s,Flex as a,Popover as o,Theme as m}from"../components";import l from"./InAppChat.js";const g={"bottom-right":"right-4 bottom-4","bottom-left":"left-4 bottom-4","top-right":"right-4 top-4","top-left":"left-4 top-4"},P=({identityId:e,idempotencyKey:p,position:r="bottom-right",theme:i,...n})=>t(m,{...i,children:t(a,{className:`fixed z-50 ${g[r]}`,children:f(o.Root,{children:[t(o.Trigger,{children:t(s,{shape:"square",roundness:"full",variant:"fill",size:"large",children:t(h,{})})}),t(o.Content,{spacing:"large",width:"350px",height:"450px",children:t(l,{identityId:e,idempotencyKey:p,borderless:!0,withChatHeader:!0,withPopoverClose:!0,...n})})]})})});var b=P;export{b as default};
|
|
2
|
+
//# sourceMappingURL=InAppChatButton.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../src/widgets/InAppChatButton.tsx"],
|
|
4
|
+
"sourcesContent": ["import React from 'react';\nimport { MessageCircle } from 'lucide-react';\n\nimport { Button, Flex, Popover, Theme, type ThemeProps } from '../components';\nimport InAppChat, { type InAppChatWrapperProps } from './InAppChat.js';\n\ntype LauncherPosition = 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left';\n\ntype InAppChatButtonProps = InAppChatWrapperProps & {\n /** Where the floating launcher sits on screen. Defaults to `bottom-right`. */\n position?: LauncherPosition,\n /** Theme overrides for the launcher + chat surface (accent color, mode, roundness, \u2026). */\n theme?: ThemeProps,\n};\n\n// Full, non-interpolated class strings so Tailwind can detect them.\nconst POSITION_CLASS: Record<LauncherPosition, string> = {\n 'bottom-right': 'right-4 bottom-4',\n 'bottom-left': 'left-4 bottom-4',\n 'top-right': 'right-4 top-4',\n 'top-left': 'left-4 top-4',\n};\n\nconst InAppChatButton = ({\n identityId,\n idempotencyKey,\n position = 'bottom-right',\n theme,\n ...props\n}: InAppChatButtonProps) => (\n <Theme {...theme}>\n <Flex className={`fixed z-50 ${POSITION_CLASS[position]}`}>\n <Popover.Root>\n <Popover.Trigger>\n <Button shape=\"square\" roundness=\"full\" variant=\"fill\" size=\"large\">\n <MessageCircle />\n </Button>\n </Popover.Trigger>\n {/* Radix unmounts Content while closed, so the chat hook (start \u2192\n subscribe \u2192 fetch) runs only once the visitor opens the launcher \u2014\n no empty conversation is created on page load. */}\n <Popover.Content spacing=\"large\" width=\"350px\" height=\"450px\">\n <InAppChat\n identityId={identityId}\n idempotencyKey={idempotencyKey}\n borderless\n withChatHeader\n withPopoverClose\n {...props}\n />\n </Popover.Content>\n </Popover.Root>\n </Flex>\n </Theme>\n);\n\nexport type { InAppChatButtonProps };\n\nexport default InAppChatButton;\n"],
|
|
5
|
+
"mappings": "AAgCM,OAGM,OAAAA,EAHN,QAAAC,MAAA,oBAhCN,MAAkB,QAClB,OAAS,iBAAAC,MAAqB,eAE9B,OAAS,UAAAC,EAAQ,QAAAC,EAAM,WAAAC,EAAS,SAAAC,MAA8B,gBAC9D,OAAOC,MAA+C,iBAYtD,MAAMC,EAAmD,CACvD,eAAgB,mBAChB,cAAe,kBACf,YAAa,gBACb,WAAY,cACd,EAEMC,EAAkB,CAAC,CACvB,WAAAC,EACA,eAAAC,EACA,SAAAC,EAAW,eACX,MAAAC,EACA,GAAGC,CACL,IACEd,EAACM,EAAA,CAAO,GAAGO,EACT,SAAAb,EAACI,EAAA,CAAK,UAAW,cAAcI,EAAeI,CAAQ,CAAC,GACrD,SAAAX,EAACI,EAAQ,KAAR,CACC,UAAAL,EAACK,EAAQ,QAAR,CACC,SAAAL,EAACG,EAAA,CAAO,MAAM,SAAS,UAAU,OAAO,QAAQ,OAAO,KAAK,QAC1D,SAAAH,EAACE,EAAA,EAAc,EACjB,EACF,EAIAF,EAACK,EAAQ,QAAR,CAAgB,QAAQ,QAAQ,MAAM,QAAQ,OAAO,QACpD,SAAAL,EAACO,EAAA,CACC,WAAYG,EACZ,eAAgBC,EAChB,WAAU,GACV,eAAc,GACd,iBAAgB,GACf,GAAGG,EACN,EACF,GACF,EACF,EACF,EAKF,IAAOC,EAAQN",
|
|
6
|
+
"names": ["jsx", "jsxs", "MessageCircle", "Button", "Flex", "Popover", "Theme", "InAppChat", "POSITION_CLASS", "InAppChatButton", "identityId", "idempotencyKey", "position", "theme", "props", "InAppChatButton_default"]
|
|
7
|
+
}
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
export { default as Chat } from './Chat.js';
|
|
2
2
|
export { default as ChatPopover } from './ChatPopover.js';
|
|
3
|
+
export { default as InAppChat } from './InAppChat.js';
|
|
4
|
+
export { default as InAppChatButton } from './InAppChatButton.js';
|
|
3
5
|
export { default as MessageBell } from './MessageBell.js';
|
|
4
6
|
export { default as Preference } from './Preference.js';
|
|
5
7
|
export { default as Preferences } from './Preferences.js';
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{default as a}from"./Chat.js";import{default as o}from"./ChatPopover.js";import{default as
|
|
1
|
+
import{default as a}from"./Chat.js";import{default as o}from"./ChatPopover.js";import{default as p}from"./InAppChat.js";import{default as l}from"./InAppChatButton.js";import{default as d}from"./MessageBell.js";import{default as x}from"./Preference.js";import{default as h}from"./Preferences.js";export{a as Chat,o as ChatPopover,p as InAppChat,l as InAppChatButton,d as MessageBell,x as Preference,h as Preferences};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/widgets/index.ts"],
|
|
4
|
-
"sourcesContent": ["export { default as Chat } from './Chat.js';\nexport { default as ChatPopover } from './ChatPopover.js';\nexport { default as MessageBell } from './MessageBell.js';\nexport { default as Preference } from './Preference.js';\nexport { default as Preferences } from './Preferences.js';\n"],
|
|
5
|
-
"mappings": "AAAA,OAAoB,WAAXA,MAAuB,YAChC,OAAoB,WAAXA,MAA8B,mBACvC,OAAoB,WAAXA,MAA8B,mBACvC,OAAoB,WAAXA,MAA6B,kBACtC,OAAoB,WAAXA,MAA8B",
|
|
4
|
+
"sourcesContent": ["export { default as Chat } from './Chat.js';\nexport { default as ChatPopover } from './ChatPopover.js';\nexport { default as InAppChat } from './InAppChat.js';\nexport { default as InAppChatButton } from './InAppChatButton.js';\nexport { default as MessageBell } from './MessageBell.js';\nexport { default as Preference } from './Preference.js';\nexport { default as Preferences } from './Preferences.js';\n"],
|
|
5
|
+
"mappings": "AAAA,OAAoB,WAAXA,MAAuB,YAChC,OAAoB,WAAXA,MAA8B,mBACvC,OAAoB,WAAXA,MAA4B,iBACrC,OAAoB,WAAXA,MAAkC,uBAC3C,OAAoB,WAAXA,MAA8B,mBACvC,OAAoB,WAAXA,MAA6B,kBACtC,OAAoB,WAAXA,MAA8B",
|
|
6
6
|
"names": ["default"]
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dashx/react",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.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.8.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",
|
package/src/hooks/index.ts
CHANGED
|
@@ -2,4 +2,5 @@ export { useWebSocket } from '../providers/DashXProvider.js';
|
|
|
2
2
|
export { default as useAgent } from './use-agent.js';
|
|
3
3
|
export { default as useDashXProvider } from './use-dashx-provider.js';
|
|
4
4
|
export { default as useInApp } from './use-in-app.js';
|
|
5
|
+
export { default as useInAppChat } from './use-in-app-chat.js';
|
|
5
6
|
export { default as useProductRelease } from './use-product-release.js';
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
import uuid from 'uuid-random';
|
|
2
|
+
import { useCallback, useEffect, useRef, useState } from 'react';
|
|
3
|
+
import type { InAppChatMessageData } from '@dashx/browser';
|
|
4
|
+
|
|
5
|
+
import useDashXProvider from './use-dashx-provider.js';
|
|
6
|
+
import { useWebSocket } from '../providers/DashXProvider.js';
|
|
7
|
+
|
|
8
|
+
type UseInAppChatHookProps = {
|
|
9
|
+
// The workspace's chat-identity id (the receiving surface), created when the
|
|
10
|
+
// chat integration is installed; pasted into config alongside the public key.
|
|
11
|
+
identityId: string;
|
|
12
|
+
// Caller-supplied conversation key; the server uses it so repeat opens with
|
|
13
|
+
// the same key resolve to the same conversation thread.
|
|
14
|
+
idempotencyKey: string;
|
|
15
|
+
// Optional automated first message sent when the conversation is first
|
|
16
|
+
// created (e.g. "Help with order #123"). Sent via `startInAppChatConversation`
|
|
17
|
+
// with a stable client message id, so it lands exactly once across reopens.
|
|
18
|
+
initialMessage?: string;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
// UI-level message. `aiRole` distinguishes the visitor from agent/AI replies and
|
|
22
|
+
// drives alignment; it arrives lowercase ('user'/'assistant'), so the widget
|
|
23
|
+
// compares it case-insensitively (see `isOutgoing`).
|
|
24
|
+
type InAppChatMessage = {
|
|
25
|
+
id: string;
|
|
26
|
+
externalUid: string | null;
|
|
27
|
+
renderedContent: any;
|
|
28
|
+
aiRole: string | null;
|
|
29
|
+
createdAt: string;
|
|
30
|
+
turnSeq?: number;
|
|
31
|
+
isPending?: boolean;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
type UseInAppChatHookResponse = {
|
|
35
|
+
conversationId: string | null;
|
|
36
|
+
messages: InAppChatMessage[];
|
|
37
|
+
isLoading: boolean;
|
|
38
|
+
isConnected: boolean;
|
|
39
|
+
error: string | null;
|
|
40
|
+
// Returns `true` if the message was optimistically queued, `false` if the chat
|
|
41
|
+
// wasn't ready (no conversation yet). Synchronous so the caller can clear the
|
|
42
|
+
// composer immediately on `true`; callers keep the input populated on `false`.
|
|
43
|
+
sendMessage: (text: string) => boolean;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
const CHAT_CHANNEL_PREFIX = 'in_app_chat:conversation:';
|
|
47
|
+
|
|
48
|
+
const toUiMessage = (message: InAppChatMessageData): InAppChatMessage => ({
|
|
49
|
+
id: message.id,
|
|
50
|
+
// `externalUid` / `aiRole` are nullable in the schema, so the SDK types them as
|
|
51
|
+
// optional; normalize the absent case to null for the UI message shape.
|
|
52
|
+
externalUid: message.externalUid ?? null,
|
|
53
|
+
renderedContent: message.renderedContent,
|
|
54
|
+
aiRole: message.aiRole ?? null,
|
|
55
|
+
createdAt: message.createdAt,
|
|
56
|
+
turnSeq: message.turnSeq,
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
// Dedup by externalUid (server message replaces the optimistic pending one)
|
|
60
|
+
// then id; order by createdAt as the authoritative key. `turnSeq` isn't in the
|
|
61
|
+
// fetched message fields, so it's absent from history (which already arrives
|
|
62
|
+
// ordered, preserved by the stable sort); it only breaks same-createdAt ties
|
|
63
|
+
// among realtime WS events, which carry it.
|
|
64
|
+
const mergeMessages = (
|
|
65
|
+
existing: InAppChatMessage[],
|
|
66
|
+
incoming: InAppChatMessage[],
|
|
67
|
+
): InAppChatMessage[] => {
|
|
68
|
+
const byKey = new Map<string, InAppChatMessage>();
|
|
69
|
+
const keyOf = (message: InAppChatMessage) => message.externalUid || message.id;
|
|
70
|
+
|
|
71
|
+
[...existing, ...incoming].forEach((message) => {
|
|
72
|
+
const existingForKey = byKey.get(keyOf(message));
|
|
73
|
+
if (!existingForKey || existingForKey.isPending) {
|
|
74
|
+
byKey.set(keyOf(message), message);
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
return [...byKey.values()].sort((a, b) => {
|
|
79
|
+
if (a.createdAt !== b.createdAt) return a.createdAt < b.createdAt ? -1 : 1;
|
|
80
|
+
return (a.turnSeq ?? 0) - (b.turnSeq ?? 0);
|
|
81
|
+
});
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Two-way InApp Chat for a visitor.
|
|
86
|
+
*
|
|
87
|
+
* PREREQUISITE: the surrounding `<DashXProvider>` must already have a valid
|
|
88
|
+
* `identityToken` (and matching `identityUid`). The chat mutations require
|
|
89
|
+
* identity-token auth — if the chat starts before an identity is resolved, they
|
|
90
|
+
* are rejected and the hook surfaces an auth error. It does NOT auto-retry when
|
|
91
|
+
* a token arrives later (its inputs are `identityId`/`idempotencyKey`, not the
|
|
92
|
+
* visitor token), so only render the chat once `identityToken` is available —
|
|
93
|
+
* e.g. `{identityToken && <InAppChat … />}`. `<InAppChatButton>` largely sidesteps
|
|
94
|
+
* this by starting lazily when the visitor opens it, by which point the provider
|
|
95
|
+
* has applied the token.
|
|
96
|
+
*/
|
|
97
|
+
const useInAppChat = ({ identityId, idempotencyKey, initialMessage }: UseInAppChatHookProps): UseInAppChatHookResponse => {
|
|
98
|
+
const dashX = useDashXProvider();
|
|
99
|
+
const { isConnected, initializeWebSocket } = useWebSocket();
|
|
100
|
+
|
|
101
|
+
const [conversationId, setConversationId] = useState<string | null>(null);
|
|
102
|
+
const [messages, setMessages] = useState<InAppChatMessage[]>([]);
|
|
103
|
+
const [isLoading, setIsLoading] = useState(true);
|
|
104
|
+
const [error, setError] = useState<string | null>(null);
|
|
105
|
+
|
|
106
|
+
// Bumped on every identity/key change and on unmount so stale start/fetch/send
|
|
107
|
+
// resolutions are ignored (the classic React async race).
|
|
108
|
+
const generationRef = useRef(0);
|
|
109
|
+
const conversationIdRef = useRef<string | null>(null);
|
|
110
|
+
|
|
111
|
+
const appendMessages = useCallback((incoming: InAppChatMessage[]) => {
|
|
112
|
+
setMessages((prev) => mergeMessages(prev, incoming));
|
|
113
|
+
}, []);
|
|
114
|
+
|
|
115
|
+
useEffect(() => {
|
|
116
|
+
const generation = (generationRef.current += 1);
|
|
117
|
+
const isStale = () => generation !== generationRef.current;
|
|
118
|
+
|
|
119
|
+
setConversationId(null);
|
|
120
|
+
setMessages([]);
|
|
121
|
+
setIsLoading(true);
|
|
122
|
+
setError(null);
|
|
123
|
+
conversationIdRef.current = null;
|
|
124
|
+
|
|
125
|
+
// Ensure the WS exists (idempotent — returns early if already created).
|
|
126
|
+
initializeWebSocket();
|
|
127
|
+
|
|
128
|
+
let unsubscribe: (() => void) | undefined;
|
|
129
|
+
|
|
130
|
+
(async () => {
|
|
131
|
+
try {
|
|
132
|
+
const conversation = await dashX.startInAppChatConversation({
|
|
133
|
+
identityId,
|
|
134
|
+
clientIdempotencyKey: idempotencyKey,
|
|
135
|
+
// Stable client message id → the automated message is inserted once,
|
|
136
|
+
// even if the conversation is reopened (the server dedups repeat sends).
|
|
137
|
+
// `-` separator (client ids allow only `[A-Za-z0-9._-]`); the key is
|
|
138
|
+
// truncated so the suffixed id stays within the 1-128 char limit.
|
|
139
|
+
...(initialMessage
|
|
140
|
+
? { content: { text: initialMessage }, clientMessageId: `${idempotencyKey.slice(0, 122)}-intro` }
|
|
141
|
+
: {}),
|
|
142
|
+
});
|
|
143
|
+
if (isStale()) return;
|
|
144
|
+
|
|
145
|
+
const convId = conversation.id;
|
|
146
|
+
setConversationId(convId);
|
|
147
|
+
conversationIdRef.current = convId;
|
|
148
|
+
|
|
149
|
+
const refetchHistory = async () => {
|
|
150
|
+
const history = await dashX.fetchInAppChatMessages({ conversationId: convId });
|
|
151
|
+
if (isStale()) return;
|
|
152
|
+
appendMessages(history.map(toUiMessage));
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
// Subscribe BEFORE fetching history so a reply landing in the gap is
|
|
156
|
+
// buffered, not dropped. `onReconnectAck` fires on reconnect re-acks and
|
|
157
|
+
// on a first ack that arrives after a `ready` timeout — both mean we are
|
|
158
|
+
// (now) subscribed, so clear any connection error and (re)load history.
|
|
159
|
+
const subscription = dashX.subscribeToChannel(
|
|
160
|
+
`${CHAT_CHANNEL_PREFIX}${convId}`,
|
|
161
|
+
(event) => {
|
|
162
|
+
if (!isStale()) appendMessages([toUiMessage(event)]);
|
|
163
|
+
},
|
|
164
|
+
{
|
|
165
|
+
onReconnectAck: () => {
|
|
166
|
+
if (isStale()) return;
|
|
167
|
+
setError(null);
|
|
168
|
+
refetchHistory().catch(() => {});
|
|
169
|
+
},
|
|
170
|
+
},
|
|
171
|
+
);
|
|
172
|
+
unsubscribe = subscription.unsubscribe;
|
|
173
|
+
|
|
174
|
+
// Load history only once the subscription is acked — fetching before
|
|
175
|
+
// that would show history while silently never receiving realtime
|
|
176
|
+
// replies. On ack failure, surface an error and defer the fetch to
|
|
177
|
+
// `onReconnectAck` (fires if/when the channel finally acks).
|
|
178
|
+
try {
|
|
179
|
+
await subscription.ready;
|
|
180
|
+
} catch {
|
|
181
|
+
if (!isStale()) setError('Couldn’t connect to live chat. Retrying…');
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
if (isStale()) return;
|
|
185
|
+
await refetchHistory();
|
|
186
|
+
} catch {
|
|
187
|
+
if (!isStale()) setError('Failed to start chat');
|
|
188
|
+
} finally {
|
|
189
|
+
if (!isStale()) setIsLoading(false);
|
|
190
|
+
}
|
|
191
|
+
})();
|
|
192
|
+
|
|
193
|
+
return () => {
|
|
194
|
+
// Invalidate in-flight async and drop the old channel before the next
|
|
195
|
+
// conversation binds.
|
|
196
|
+
generationRef.current += 1;
|
|
197
|
+
unsubscribe?.();
|
|
198
|
+
};
|
|
199
|
+
}, [dashX, identityId, idempotencyKey, initialMessage, initializeWebSocket, appendMessages]);
|
|
200
|
+
|
|
201
|
+
// Synchronous on purpose: it returns `true` the moment the message is optimistically
|
|
202
|
+
// queued and runs the network send in the background. The caller clears the composer
|
|
203
|
+
// on `true` immediately — if it instead awaited the round-trip, a fast second Enter
|
|
204
|
+
// would re-send the still-present text as a new message (fresh clientMessageId, so the
|
|
205
|
+
// backend won't dedupe it) and create a duplicate.
|
|
206
|
+
const sendMessage = useCallback(
|
|
207
|
+
(text: string): boolean => {
|
|
208
|
+
const convId = conversationIdRef.current;
|
|
209
|
+
// Not ready (conversation still starting, or start failed) — report back so
|
|
210
|
+
// the caller can keep the typed text instead of clearing it on a no-op send.
|
|
211
|
+
if (!text.trim() || !convId) return false;
|
|
212
|
+
|
|
213
|
+
// Pin the generation so a response that resolves after the identity/key
|
|
214
|
+
// changed (or unmount) can't contaminate the new conversation's state.
|
|
215
|
+
const generation = generationRef.current;
|
|
216
|
+
const clientMessageId = uuid();
|
|
217
|
+
const optimistic: InAppChatMessage = {
|
|
218
|
+
id: clientMessageId,
|
|
219
|
+
externalUid: `in_app_chat:${clientMessageId}`,
|
|
220
|
+
renderedContent: { text },
|
|
221
|
+
aiRole: 'USER',
|
|
222
|
+
createdAt: new Date().toISOString(),
|
|
223
|
+
isPending: true,
|
|
224
|
+
};
|
|
225
|
+
appendMessages([optimistic]);
|
|
226
|
+
|
|
227
|
+
void (async () => {
|
|
228
|
+
try {
|
|
229
|
+
const serverMessage = await dashX.sendInAppChatMessage({
|
|
230
|
+
conversationId: convId,
|
|
231
|
+
identityId,
|
|
232
|
+
content: { text },
|
|
233
|
+
clientMessageId,
|
|
234
|
+
});
|
|
235
|
+
if (generation !== generationRef.current) return;
|
|
236
|
+
// Reconcile by externalUid (the WS echo reconciles too — both idempotent).
|
|
237
|
+
appendMessages([toUiMessage(serverMessage)]);
|
|
238
|
+
} catch {
|
|
239
|
+
if (generation === generationRef.current) setError('Failed to send message');
|
|
240
|
+
}
|
|
241
|
+
})();
|
|
242
|
+
|
|
243
|
+
// Queued (optimistically appended) — the background send reconciles/errors later.
|
|
244
|
+
return true;
|
|
245
|
+
},
|
|
246
|
+
[dashX, identityId, appendMessages],
|
|
247
|
+
);
|
|
248
|
+
|
|
249
|
+
return { conversationId, messages, isLoading, isConnected, error, sendMessage };
|
|
250
|
+
};
|
|
251
|
+
|
|
252
|
+
export type { UseInAppChatHookProps, UseInAppChatHookResponse, InAppChatMessage };
|
|
253
|
+
|
|
254
|
+
export default useInAppChat;
|
|
@@ -15,7 +15,21 @@ const WebSocketContext = createContext<WebSocketContextType | null>(null);
|
|
|
15
15
|
|
|
16
16
|
type DashXProviderProps = ClientParams & {
|
|
17
17
|
initializeWebSocketOnLoad?: boolean,
|
|
18
|
-
webSocketQueryParams?: Record<string, any
|
|
18
|
+
webSocketQueryParams?: Record<string, any>,
|
|
19
|
+
/**
|
|
20
|
+
* The visitor's account uid, addressed on both transports (GraphQL + WS).
|
|
21
|
+
* Pass `null` to explicitly clear it (e.g. on logout); omit (`undefined`) to
|
|
22
|
+
* leave it unchanged. Pair with `identityToken` for the same identity.
|
|
23
|
+
*/
|
|
24
|
+
identityUid?: string | null,
|
|
25
|
+
/**
|
|
26
|
+
* Identity token (minted with your DashX server SDK's `generateIdentityToken`,
|
|
27
|
+
* or from an exchange endpoint you control). When set, the SDK uses it for both
|
|
28
|
+
* GraphQL (`X-Identity-Token` header) and the WebSocket handshake — the server
|
|
29
|
+
* identifies the visitor from it, which is the ownership key for InApp Chat.
|
|
30
|
+
* Pass `null` to clear it on logout; omit (`undefined`) to leave it unchanged.
|
|
31
|
+
*/
|
|
32
|
+
identityToken?: string | null,
|
|
19
33
|
}
|
|
20
34
|
|
|
21
35
|
function DashXProvider({
|
|
@@ -28,20 +42,43 @@ function DashXProvider({
|
|
|
28
42
|
targetVersion,
|
|
29
43
|
initializeWebSocketOnLoad = false,
|
|
30
44
|
webSocketQueryParams = {},
|
|
45
|
+
identityUid,
|
|
46
|
+
identityToken,
|
|
31
47
|
}: React.PropsWithChildren<DashXProviderProps>) {
|
|
32
48
|
const dashX = React.useMemo(
|
|
33
|
-
() =>
|
|
34
|
-
DashX.configure({
|
|
49
|
+
() => {
|
|
50
|
+
const client = DashX.configure({
|
|
35
51
|
publicKey: publicKey,
|
|
36
52
|
baseUri: baseUri,
|
|
37
53
|
realtimeBaseUri: realtimeBaseUri,
|
|
38
54
|
targetEnvironment: targetEnvironment,
|
|
39
55
|
targetProduct,
|
|
40
56
|
targetVersion,
|
|
41
|
-
})
|
|
57
|
+
});
|
|
58
|
+
// Apply identity synchronously at creation so a child that starts work in
|
|
59
|
+
// its own mount effect (child effects run before this provider's effects)
|
|
60
|
+
// sees the token already set. Later prop changes go through the effect
|
|
61
|
+
// below; identity is intentionally not a useMemo dep (we don't recreate
|
|
62
|
+
// the client when it changes).
|
|
63
|
+
if (identityUid !== undefined || identityToken !== undefined) {
|
|
64
|
+
client.setIdentity(identityUid, identityToken);
|
|
65
|
+
}
|
|
66
|
+
return client;
|
|
67
|
+
},
|
|
68
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
42
69
|
[publicKey, baseUri, realtimeBaseUri, targetEnvironment, targetProduct, targetVersion],
|
|
43
70
|
);
|
|
44
71
|
|
|
72
|
+
// `webSocketQueryParams` defaults to a fresh `{}` each render and is a dep of
|
|
73
|
+
// the effects below, so memoize on its content to keep the reference stable —
|
|
74
|
+
// otherwise those effects (setIdentity / WS init) re-run on every render.
|
|
75
|
+
const webSocketQueryParamsKey = JSON.stringify(webSocketQueryParams ?? {});
|
|
76
|
+
const stableWebSocketQueryParams = React.useMemo(
|
|
77
|
+
() => webSocketQueryParams ?? {},
|
|
78
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
79
|
+
[webSocketQueryParamsKey],
|
|
80
|
+
);
|
|
81
|
+
|
|
45
82
|
// WebSocket state
|
|
46
83
|
const [isConnected, setIsConnected] = useState(false);
|
|
47
84
|
const wsManagerRef = useRef<WebSocketManager | null>(null);
|
|
@@ -62,17 +99,22 @@ function DashXProvider({
|
|
|
62
99
|
return;
|
|
63
100
|
}
|
|
64
101
|
|
|
65
|
-
//
|
|
102
|
+
// Reuse an existing manager — it owns its own throttled reconnect
|
|
103
|
+
// lifecycle. Tearing it down and creating a new one on every call (e.g.
|
|
104
|
+
// when a consumer re-invokes this as `isConnected` flips to false on each
|
|
105
|
+
// close) resets the per-instance reconnect throttle and reconnects
|
|
106
|
+
// immediately, defeating the backoff. Create one only if none exists.
|
|
66
107
|
if (wsManagerRef.current) {
|
|
67
|
-
|
|
68
|
-
wsManagerRef.current.disconnect();
|
|
69
|
-
wsManagerRef.current = null;
|
|
70
|
-
setIsConnected(false);
|
|
108
|
+
return;
|
|
71
109
|
}
|
|
72
110
|
|
|
73
111
|
const queryParams = {
|
|
74
112
|
publicKey: dashX.publicKey,
|
|
75
113
|
...(dashX.targetEnvironment && { targetEnvironment: dashX.targetEnvironment }),
|
|
114
|
+
// Provider-level defaults apply to every provider-owned socket — including
|
|
115
|
+
// when the chat hook (or any consumer) opens the socket first by calling
|
|
116
|
+
// `initializeWebSocket()` with no args. Explicit call-site params override.
|
|
117
|
+
...stableWebSocketQueryParams,
|
|
76
118
|
...customQueryParams,
|
|
77
119
|
};
|
|
78
120
|
|
|
@@ -108,13 +150,39 @@ function DashXProvider({
|
|
|
108
150
|
|
|
109
151
|
wsManagerRef.current = wsManager;
|
|
110
152
|
wsManager.connect();
|
|
111
|
-
}, [dashX]);
|
|
153
|
+
}, [dashX, stableWebSocketQueryParams]);
|
|
154
|
+
|
|
155
|
+
// Forward `identityUid` + `identityToken` into the dashX client so the same
|
|
156
|
+
// identity is used by GraphQL and the WS. Pass the props as-is: `setIdentity`
|
|
157
|
+
// treats `undefined` as "leave unchanged", so setting only `identityToken`
|
|
158
|
+
// won't clobber an existing account uid (and vice versa).
|
|
159
|
+
const previousIdentityTokenRef = useRef(identityToken);
|
|
160
|
+
useEffect(() => {
|
|
161
|
+
if (!dashX || (identityUid === undefined && identityToken === undefined)) {
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
dashX.setIdentity(identityUid, identityToken);
|
|
166
|
+
|
|
167
|
+
// This provider owns the socket (created via `createWebSocketConnection`,
|
|
168
|
+
// not the client's internal manager that `setIdentity` reconnects), so on a
|
|
169
|
+
// token change we recreate it here to put the new identity_token in the WS
|
|
170
|
+
// URL. GraphQL picks up the new header on its own; tracked chat channels
|
|
171
|
+
// re-subscribe on the new socket's `onOpen`.
|
|
172
|
+
const tokenChanged = identityToken !== previousIdentityTokenRef.current;
|
|
173
|
+
previousIdentityTokenRef.current = identityToken;
|
|
174
|
+
if (tokenChanged && wsManagerRef.current) {
|
|
175
|
+
wsManagerRef.current.disconnect();
|
|
176
|
+
wsManagerRef.current = null;
|
|
177
|
+
initializeWebSocket(stableWebSocketQueryParams);
|
|
178
|
+
}
|
|
179
|
+
}, [ dashX, identityUid, identityToken, initializeWebSocket, stableWebSocketQueryParams ]);
|
|
112
180
|
|
|
113
181
|
useEffect(() => {
|
|
114
182
|
if (initializeWebSocketOnLoad) {
|
|
115
|
-
initializeWebSocket(
|
|
183
|
+
initializeWebSocket(stableWebSocketQueryParams);
|
|
116
184
|
}
|
|
117
|
-
}, [ initializeWebSocketOnLoad,
|
|
185
|
+
}, [ initializeWebSocketOnLoad, initializeWebSocket, stableWebSocketQueryParams ]);
|
|
118
186
|
|
|
119
187
|
return (
|
|
120
188
|
<DashXContext.Provider value={dashX}>
|