@dashx/react 0.3.5 → 0.3.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/hooks/use-in-app-chat.js +1 -1
- package/dist/cjs/hooks/use-in-app-chat.js.map +3 -3
- package/dist/cjs/hooks/use-in-app.js +1 -1
- package/dist/cjs/hooks/use-in-app.js.map +3 -3
- 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/hooks/use-in-app.js +1 -1
- package/dist/esm/hooks/use-in-app.js.map +3 -3
- package/package.json +2 -2
- package/src/hooks/use-in-app-chat.ts +20 -11
- package/src/hooks/use-in-app.ts +17 -10
- 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,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var $=Object.create;var I=Object.defineProperty;var X=Object.getOwnPropertyDescriptor;var K=Object.getOwnPropertyNames;var N=Object.getPrototypeOf,O=Object.prototype.hasOwnProperty;var T=(e,n)=>{for(var s in n)I(e,s,{get:n[s],enumerable:!0})},m=(e,n,s,i)=>{if(n&&typeof n=="object"||typeof n=="function")for(let t of K(n))!O.call(e,t)&&t!==s&&I(e,t,{get:()=>n[t],enumerable:!(i=X(n,t))||i.enumerable});return e};var x=(e,n,s)=>(s=e!=null?$(N(e)):{},m(n||!e||!e.__esModule?I(s,"default",{value:e,enumerable:!0}):s,e)),W=e=>m(I({},"__esModule",{value:!0}),e);var J={};T(J,{default:()=>G});module.exports=W(J);var H=x(require("uuid-random")),r=require("react"),w=x(require("./use-dashx-provider.js")),P=require("../providers/DashXProvider.js");const z="in_app_chat:conversation:",b=e=>({id:e.id,externalUid:e.externalUid??null,renderedContent:e.renderedContent,aiRole:e.aiRole??null,createdAt:e.createdAt,turnSeq:e.turnSeq}),j=(e,n)=>{const s=new Map,i=t=>t.externalUid||t.id;return[...e,...n].forEach(t=>{const o=s.get(i(t));(!o||o.isPending)&&s.set(i(t),t)}),[...s.values()].sort((t,o)=>t.createdAt!==o.createdAt?t.createdAt<o.createdAt?-1:1:(t.turnSeq??0)-(o.turnSeq??0))},B=({identityId:e,idempotencyKey:n,initialMessage:s,enabled:i=!0,onInboundMessage:t})=>{const o=(0,w.default)(),{isConnected:E,initializeWebSocket:y}=(0,P.useWebSocket)(),[_,v]=(0,r.useState)(null),[q,R]=(0,r.useState)([]),[D,A]=(0,r.useState)(!0),[F,d]=(0,r.useState)(null),c=(0,r.useRef)(0),f=(0,r.useRef)(null),U=(0,r.useRef)(t);U.current=t;const u=(0,r.useCallback)(p=>{R(a=>j(a,p))},[]);(0,r.useEffect)(()=>{const p=c.current+=1,a=()=>p!==c.current;if(v(null),R([]),d(null),f.current=null,!i)return A(!1),()=>{c.current+=1};A(!0),y();let g;return(async()=>{try{const h=s?{identityId:e,clientIdempotencyKey:n,content:{text:s},clientMessageId:`${n.slice(0,122)}-intro`}:{identityId:e,clientIdempotencyKey:n},M=await o.startInAppChatConversation(h);if(a())return;const l=M.id;v(l),f.current=l;const S=async()=>{const C=await o.fetchInAppChatMessages({conversationId:l});a()||u(C.map(b))},k=o.subscribeToChannel(`${z}${l}`,C=>{a()||(u([b(C)]),U.current?.(C))},{onReconnectAck:()=>{a()||(d(null),S().catch(()=>{}))}});g=k.unsubscribe;try{await k.ready}catch{a()||d("Couldn\u2019t connect to live chat. Retrying\u2026");return}if(a())return;await S()}catch{a()||d("Failed to start chat")}finally{a()||A(!1)}})(),()=>{c.current+=1,g?.()}},[o,e,n,s,i,y,u]);const L=(0,r.useCallback)(p=>{const a=f.current;if(!p.trim()||!a)return!1;const g=c.current,h=(0,H.default)(),M={id:h,externalUid:`in_app_chat:${h}`,renderedContent:{text:p},aiRole:"USER",createdAt:new Date().toISOString(),isPending:!0};return u([M]),(async()=>{try{const l=await o.sendInAppChatMessage({conversationId:a,identityId:e,content:{text:p},clientMessageId:h});if(g!==c.current)return;u([b(l)])}catch{g===c.current&&d("Failed to send message")}})(),!0},[o,e,u]);return{conversationId:_,messages:q,isLoading:D,isConnected:E,error:F,sendMessage:L}};var G=B;
|
|
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 const conversation = await dashX.startInAppChatConversation({\n identityId,\n clientIdempotencyKey: idempotencyKey,\n // Stable client message id \u2192 the automated message is inserted once,\n // even if the conversation is reopened (the server dedups repeat sends).\n // `-` separator (client ids allow only `[A-Za-z0-9._-]`); the key is\n // truncated so the suffixed id stays within the 1-128 char limit.\n ...(initialMessage\n ? { content: { text: initialMessage }, clientMessageId: `${idempotencyKey.slice(0, 122)}-intro` }\n : {}),\n });\n if (isStale()) return;\n\n const convId = conversation.id;\n setConversationId(convId);\n conversationIdRef.current = convId;\n\n const refetchHistory = async () => {\n const history = await dashX.fetchInAppChatMessages({ conversationId: convId });\n if (isStale()) return;\n appendMessages(history.map(toUiMessage));\n };\n\n // Subscribe BEFORE fetching history so a reply landing in the gap is\n // buffered, not dropped. `onReconnectAck` fires on reconnect re-acks and\n // on a first ack that arrives after a `ready` timeout \u2014 both mean we are\n // (now) subscribed, so clear any connection error and (re)load history.\n const subscription = dashX.subscribeToChannel(\n `${CHAT_CHANNEL_PREFIX}${convId}`,\n (event) => {\n if (isStale()) return;\n appendMessages([toUiMessage(event)]);\n // LIVE messages only \u2014 history load / reconnect refetch go through\n // `refetchHistory`, so notification consumers never fire for\n // backfilled messages.\n onInboundMessageRef.current?.(event);\n },\n {\n onReconnectAck: () => {\n if (isStale()) return;\n setError(null);\n refetchHistory().catch(() => {});\n },\n },\n );\n unsubscribe = subscription.unsubscribe;\n\n // Load history only once the subscription is acked \u2014 fetching before\n // that would show history while silently never receiving realtime\n // replies. On ack failure, surface an error and defer the fetch to\n // `onReconnectAck` (fires if/when the channel finally acks).\n try {\n await subscription.ready;\n } catch {\n if (!isStale()) setError('Couldn\u2019t connect to live chat. Retrying\u2026');\n return;\n }\n if (isStale()) return;\n await refetchHistory();\n } catch {\n if (!isStale()) setError('Failed to start chat');\n } finally {\n if (!isStale()) setIsLoading(false);\n }\n })();\n\n return () => {\n // Invalidate in-flight async and drop the old channel before the next\n // conversation binds.\n generationRef.current += 1;\n unsubscribe?.();\n };\n }, [dashX, identityId, idempotencyKey, initialMessage, enabled, initializeWebSocket, appendMessages]);\n\n // Synchronous on purpose: it returns `true` the moment the message is optimistically\n // queued and runs the network send in the background. The caller clears the composer\n // on `true` immediately \u2014 if it instead awaited the round-trip, a fast second Enter\n // would re-send the still-present text as a new message (fresh clientMessageId, so the\n // backend won't dedupe it) and create a duplicate.\n const sendMessage = useCallback(\n (text: string): boolean => {\n const convId = conversationIdRef.current;\n // Not ready (conversation still starting, or start failed) \u2014 report back so\n // the caller can keep the typed text instead of clearing it on a no-op send.\n if (!text.trim() || !convId) return false;\n\n // Pin the generation so a response that resolves after the identity/key\n // changed (or unmount) can't contaminate the new conversation's state.\n const generation = generationRef.current;\n const clientMessageId = uuid();\n const optimistic: InAppChatMessage = {\n id: clientMessageId,\n externalUid: `in_app_chat:${clientMessageId}`,\n renderedContent: { text },\n aiRole: 'USER',\n createdAt: new Date().toISOString(),\n isPending: true,\n };\n appendMessages([optimistic]);\n\n void (async () => {\n try {\n const serverMessage = await dashX.sendInAppChatMessage({\n conversationId: convId,\n identityId,\n content: { text },\n clientMessageId,\n });\n if (generation !== generationRef.current) return;\n // Reconcile by externalUid (the WS echo reconciles too \u2014 both idempotent).\n appendMessages([toUiMessage(serverMessage)]);\n } catch {\n if (generation === generationRef.current) setError('Failed to send message');\n }\n })();\n\n // Queued (optimistically appended) \u2014 the background send reconciles/errors later.\n return true;\n },\n [dashX, identityId, appendMessages],\n );\n\n return { conversationId, messages, isLoading, isConnected, error, sendMessage };\n};\n\nexport type { UseInAppChatHookProps, UseInAppChatHookResponse, InAppChatMessage };\n\nexport default useInAppChat;\n"],
|
|
5
|
-
"mappings": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAiB,0BACjBC,EAAyD,iBAGzDC,EAA6B,sCAC7BC,EAA6B,yCAiD7B,MAAMC,EAAsB,4BAEtBC,EAAeC,IAAqD,CACxE,GAAIA,EAAQ,GAGZ,YAAaA,EAAQ,aAAe,KACpC,gBAAiBA,EAAQ,gBACzB,OAAQA,EAAQ,QAAU,KAC1B,UAAWA,EAAQ,UACnB,QAASA,EAAQ,OACnB,GAOMC,EAAgB,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bE,EAAkB,QAAU,KAIxB,CAACf,EACH,OAAAW,EAAa,EAAK,EACX,IAAM,CAAEG,EAAc,SAAW,CAAG,EAG7CH,EAAa,EAAI,EAGjBN,EAAoB,EAEpB,IAAIgB,EAEJ,OAAC,SAAY,CACX,GAAI,
|
|
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", "idempotencyKey", "initialMessage", "enabled", "onInboundMessage", "dashX", "useDashXProvider", "isConnected", "initializeWebSocket", "conversationId", "setConversationId", "messages", "setMessages", "isLoading", "setIsLoading", "error", "setError", "generationRef", "conversationIdRef", "onInboundMessageRef", "appendMessages", "prev", "generation", "isStale", "unsubscribe", "conversation", "convId", "refetchHistory", "history", "subscription", "event", "sendMessage", "text", "clientMessageId", "uuid", "optimistic", "serverMessage"]
|
|
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,yCAiD7B,MAAMC,EAAsB,4BAEtBC,EAAeC,IAAqD,CACxE,GAAIA,EAAQ,GAGZ,YAAaA,EAAQ,aAAe,KACpC,gBAAiBA,EAAQ,gBACzB,OAAQA,EAAQ,QAAU,KAC1B,UAAWA,EAAQ,UACnB,QAASA,EAAQ,OACnB,GAOMC,EAAgB,CACpBC,EACAC,IACuB,CACvB,MAAMC,EAAQ,IAAI,IACZC,EAASL,GAA8BA,EAAQ,aAAeA,EAAQ,GAE5E,OAAC,GAAGE,EAAU,GAAGC,CAAQ,EAAE,QAASH,GAAY,CAC9C,MAAMM,EAAiBF,EAAM,IAAIC,EAAML,CAAO,CAAC,GAC3C,CAACM,GAAkBA,EAAe,YACpCF,EAAM,IAAIC,EAAML,CAAO,EAAGA,CAAO,CAErC,CAAC,EAEM,CAAC,GAAGI,EAAM,OAAO,CAAC,EAAE,KAAK,CAACG,EAAGC,IAC9BD,EAAE,YAAcC,EAAE,UAAkBD,EAAE,UAAYC,EAAE,UAAY,GAAK,GACjED,EAAE,SAAW,IAAMC,EAAE,SAAW,EACzC,CACH,EAeMC,EAAe,CAAC,CAAE,WAAAC,EAAY,eAAAC,EAAgB,eAAAC,EAAgB,QAAAC,EAAU,GAAM,iBAAAC,CAAiB,IAAuD,CAC1J,MAAMC,KAAQ,EAAAC,SAAiB,EACzB,CAAE,YAAAC,EAAa,oBAAAC,CAAoB,KAAI,gBAAa,EAEpD,CAACC,EAAgBC,CAAiB,KAAI,YAAwB,IAAI,EAClE,CAACC,EAAUC,CAAW,KAAI,YAA6B,CAAC,CAAC,EACzD,CAACC,EA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ACT,EACA,CAACX,EAAOL,EAAYoB,CAAc,CACpC,EAEA,MAAO,CAAE,eAAAX,EAAgB,SAAAE,EAAU,UAAAE,EAAW,YAAAN,EAAa,MAAAQ,EAAO,YAAAiB,CAAY,CAChF,EAIA,IAAOlD,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", "idempotencyKey", "initialMessage", "enabled", "onInboundMessage", "dashX", "useDashXProvider", "isConnected", "initializeWebSocket", "conversationId", "setConversationId", "messages", "setMessages", "isLoading", "setIsLoading", "error", "setError", "generationRef", "conversationIdRef", "onInboundMessageRef", "appendMessages", "prev", "generation", "isStale", "unsubscribe", "startArgs", "conversation", "convId", "refetchHistory", "history", "subscription", "event", "sendMessage", "text", "clientMessageId", "uuid", "optimistic", "serverMessage"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var E=Object.create;var
|
|
1
|
+
"use strict";var E=Object.create;var i=Object.defineProperty;var R=Object.getOwnPropertyDescriptor;var S=Object.getOwnPropertyNames;var w=Object.getPrototypeOf,D=Object.prototype.hasOwnProperty;var U=(e,s)=>{for(var o in s)i(e,o,{get:s[o],enumerable:!0})},M=(e,s,o,p)=>{if(s&&typeof s=="object"||typeof s=="function")for(let n of S(s))!D.call(e,n)&&n!==o&&i(e,n,{get:()=>s[n],enumerable:!(p=R(s,n))||p.enumerable});return e};var u=(e,s,o)=>(o=e!=null?E(w(e)):{},M(s||!e||!e.__esModule?i(o,"default",{value:e,enumerable:!0}):o,e)),X=e=>M(i({},"__esModule",{value:!0}),e);var W={};U(W,{default:()=>C});module.exports=X(W);var A=u(require("react-hot-toast")),r=require("react"),c=require("@dashx/browser"),f=u(require("./use-dashx-provider.js")),h=require("../providers/DashXProvider.js");const _=()=>{let e=(0,f.default)();const{subscribe:s}=(0,h.useWebSocket)(),[o,p]=(0,r.useState)([]),[n,k]=(0,r.useState)(null),[g,l]=(0,r.useState)(!1),[m,d]=(0,r.useState)(!1),b=a=>e.trackMessage({id:a,status:"READ"}).catch(t=>{console.error("DashX: failed to mark in-app message as read",t)}),I=a=>e.trackMessage({id:a,status:"UNREAD"}).catch(t=>{console.error("DashX: failed to mark in-app message as unread",t)}),y=()=>e.trackAllMessages().catch(a=>{console.error("DashX: failed to mark all in-app messages as read",a)}),P=async()=>{if(!(m||!g)){d(!0);try{const{hasMore:a}=await e.fetchMoreInAppMessages();l(a)}catch(a){console.error("DashX: failed to fetch more in-app messages",a)}finally{d(!1)}}};return(0,r.useEffect)(()=>{e.watchFetchInAppMessages(a=>{p(a),a.length<=c.IN_APP_MESSAGES_PAGE_SIZE&&l(a.length===c.IN_APP_MESSAGES_PAGE_SIZE)}),e.watchFetchInAppMessagesAggregate(k)},[e]),(0,r.useEffect)(()=>s(t=>{t?.type===c.WebsocketMessage.IN_APP_MESSAGE&&(0,A.default)(t.data.renderedContent.body)}),[s]),{messages:o,unreadMessagesCount:n,hasMore:g,isLoadingMore:m,loadMore:P,markMessageAsRead:b,markMessageAsUnread:I,markAllMessagesAsRead:y}};var C=_;
|
|
2
2
|
//# sourceMappingURL=use-in-app.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/hooks/use-in-app.ts"],
|
|
4
|
-
"sourcesContent": ["import toast from 'react-hot-toast';\nimport { useEffect, useState } from 'react';\nimport { WebsocketMessage, IN_APP_MESSAGES_PAGE_SIZE } from '@dashx/browser';\nimport type { InAppMessages, WebsocketMessageType } from '@dashx/browser';\n\nimport useDashXProvider from './use-dashx-provider.js';\nimport { useWebSocket } from '../providers/DashXProvider.js';\n\ntype UseInAppHookResponse = {\n messages: InAppMessages;\n unreadMessagesCount: number | null;\n hasMore: boolean;\n isLoadingMore: boolean;\n loadMore: () => Promise<void>;\n markMessageAsRead: (id: string) => Promise<any>;\n markMessageAsUnread: (id: string) => Promise<any>;\n markAllMessagesAsRead: () => Promise<any>;\n};\n\nconst useInApp = (): UseInAppHookResponse => {\n let dashX = useDashXProvider();\n const { subscribe } = useWebSocket();\n const [messages, setMessages] = useState<InAppMessages>([]);\n const [unreadMessagesCount, setUnreadMessagesCount] = useState<number | null>(null);\n const [hasMore, setHasMore] = useState(false);\n const [isLoadingMore, setIsLoadingMore] = useState(false);\n\n const markMessageAsRead = (id: string)
|
|
5
|
-
"mappings": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAkB,8BAClBC,EAAoC,iBACpCC,EAA4D,0BAG5DC,EAA6B,sCAC7BC,EAA6B,yCAa7B,MAAMC,EAAW,IAA4B,CAC3C,IAAIC,KAAQ,EAAAC,SAAiB,EAC7B,KAAM,CAAE,UAAAC,CAAU,KAAI,gBAAa,EAC7B,CAACC,EAAUC,CAAW,KAAI,YAAwB,CAAC,CAAC,EACpD,CAACC,EAAqBC,CAAsB,KAAI,YAAwB,IAAI,EAC5E,CAACC,EAASC,CAAU,KAAI,YAAS,EAAK,EACtC,CAACC,EAAeC,CAAgB,KAAI,YAAS,EAAK,EAElDC,EAAqBC,
|
|
6
|
-
"names": ["use_in_app_exports", "__export", "use_in_app_default", "__toCommonJS", "import_react_hot_toast", "import_react", "import_browser", "import_use_dashx_provider", "import_DashXProvider", "useInApp", "dashX", "useDashXProvider", "subscribe", "messages", "setMessages", "unreadMessagesCount", "setUnreadMessagesCount", "hasMore", "setHasMore", "isLoadingMore", "setIsLoadingMore", "markMessageAsRead", "id", "markMessageAsUnread", "markAllMessagesAsRead", "loadMore", "more", "nextMessages", "message", "toast"]
|
|
4
|
+
"sourcesContent": ["import toast from 'react-hot-toast';\nimport { useEffect, useState } from 'react';\nimport { WebsocketMessage, IN_APP_MESSAGES_PAGE_SIZE } from '@dashx/browser';\nimport type { InAppMessages, WebsocketMessageType } from '@dashx/browser';\n\nimport useDashXProvider from './use-dashx-provider.js';\nimport { useWebSocket } from '../providers/DashXProvider.js';\n\ntype UseInAppHookResponse = {\n messages: InAppMessages;\n unreadMessagesCount: number | null;\n hasMore: boolean;\n isLoadingMore: boolean;\n loadMore: () => Promise<void>;\n markMessageAsRead: (id: string) => Promise<any>;\n markMessageAsUnread: (id: string) => Promise<any>;\n markAllMessagesAsRead: () => Promise<any>;\n};\n\nconst useInApp = (): UseInAppHookResponse => {\n let dashX = useDashXProvider();\n const { subscribe } = useWebSocket();\n const [messages, setMessages] = useState<InAppMessages>([]);\n const [unreadMessagesCount, setUnreadMessagesCount] = useState<number | null>(null);\n const [hasMore, setHasMore] = useState(false);\n const [isLoadingMore, setIsLoadingMore] = useState(false);\n\n const markMessageAsRead = (id: string) =>\n dashX.trackMessage({ id, status: 'READ' }).catch((error: unknown) => {\n console.error('DashX: failed to mark in-app message as read', error);\n });\n\n const markMessageAsUnread = (id: string) =>\n dashX.trackMessage({ id, status: 'UNREAD' }).catch((error: unknown) => {\n console.error('DashX: failed to mark in-app message as unread', error);\n });\n\n const markAllMessagesAsRead = () =>\n dashX.trackAllMessages().catch((error: unknown) => {\n console.error('DashX: failed to mark all in-app messages as read', error);\n });\n\n const loadMore = async () => {\n if (isLoadingMore || !hasMore) return;\n setIsLoadingMore(true);\n try {\n const { hasMore: more } = await dashX.fetchMoreInAppMessages();\n setHasMore(more);\n } catch (error) {\n // hasMore stays true so a later scroll retries the page.\n console.error('DashX: failed to fetch more in-app messages', error);\n } finally {\n setIsLoadingMore(false);\n }\n };\n\n useEffect(() => {\n // Set up in-app message watchers (automatically refetch on WebSocket reconnection)\n dashX.watchFetchInAppMessages((nextMessages) => {\n setMessages(nextMessages);\n // While the list is a single page (initial load, empty inbox, or a reconnect\n // refetch of page 1), a full page implies more; past that, loadMore owns hasMore.\n if (nextMessages.length <= IN_APP_MESSAGES_PAGE_SIZE) {\n setHasMore(nextMessages.length === IN_APP_MESSAGES_PAGE_SIZE);\n }\n });\n dashX.watchFetchInAppMessagesAggregate(setUnreadMessagesCount);\n }, [dashX]);\n\n useEffect(() => {\n // Subscribe to WebSocket messages for in-app messages\n const unsubscribe = subscribe((message: WebsocketMessageType) => {\n // Handle only IN_APP_MESSAGE for toast display\n // The client handles all other message processing internally\n if (message?.type === WebsocketMessage.IN_APP_MESSAGE) {\n toast(message.data.renderedContent.body);\n }\n });\n\n return unsubscribe;\n }, [subscribe]);\n\n return {\n messages,\n unreadMessagesCount,\n hasMore,\n isLoadingMore,\n loadMore,\n markMessageAsRead,\n markMessageAsUnread,\n markAllMessagesAsRead,\n };\n};\n\nexport default useInApp;\n"],
|
|
5
|
+
"mappings": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAkB,8BAClBC,EAAoC,iBACpCC,EAA4D,0BAG5DC,EAA6B,sCAC7BC,EAA6B,yCAa7B,MAAMC,EAAW,IAA4B,CAC3C,IAAIC,KAAQ,EAAAC,SAAiB,EAC7B,KAAM,CAAE,UAAAC,CAAU,KAAI,gBAAa,EAC7B,CAACC,EAAUC,CAAW,KAAI,YAAwB,CAAC,CAAC,EACpD,CAACC,EAAqBC,CAAsB,KAAI,YAAwB,IAAI,EAC5E,CAACC,EAASC,CAAU,KAAI,YAAS,EAAK,EACtC,CAACC,EAAeC,CAAgB,KAAI,YAAS,EAAK,EAElDC,EAAqBC,GACzBZ,EAAM,aAAa,CAAE,GAAAY,EAAI,OAAQ,MAAO,CAAC,EAAE,MAAOC,GAAmB,CACnE,QAAQ,MAAM,+CAAgDA,CAAK,CACrE,CAAC,EAEGC,EAAuBF,GAC3BZ,EAAM,aAAa,CAAE,GAAAY,EAAI,OAAQ,QAAS,CAAC,EAAE,MAAOC,GAAmB,CACrE,QAAQ,MAAM,iDAAkDA,CAAK,CACvE,CAAC,EAEGE,EAAwB,IAC5Bf,EAAM,iBAAiB,EAAE,MAAOa,GAAmB,CACjD,QAAQ,MAAM,oDAAqDA,CAAK,CAC1E,CAAC,EAEGG,EAAW,SAAY,CAC3B,GAAI,EAAAP,GAAiB,CAACF,GACtB,CAAAG,EAAiB,EAAI,EACrB,GAAI,CACF,KAAM,CAAE,QAASO,CAAK,EAAI,MAAMjB,EAAM,uBAAuB,EAC7DQ,EAAWS,CAAI,CACjB,OAASJ,EAAO,CAEd,QAAQ,MAAM,8CAA+CA,CAAK,CACpE,QAAE,CACAH,EAAiB,EAAK,CACxB,EACF,EAEA,sBAAU,IAAM,CAEdV,EAAM,wBAAyBkB,GAAiB,CAC9Cd,EAAYc,CAAY,EAGpBA,EAAa,QAAU,6BACzBV,EAAWU,EAAa,SAAW,2BAAyB,CAEhE,CAAC,EACDlB,EAAM,iCAAiCM,CAAsB,CAC/D,EAAG,CAACN,CAAK,CAAC,KAEV,aAAU,IAEYE,EAAWiB,GAAkC,CAG3DA,GAAS,OAAS,mBAAiB,mBACrC,EAAAC,SAAMD,EAAQ,KAAK,gBAAgB,IAAI,CAE3C,CAAC,EAGA,CAACjB,CAAS,CAAC,EAEP,CACL,SAAAC,EACA,oBAAAE,EACA,QAAAE,EACA,cAAAE,EACA,SAAAO,EACA,kBAAAL,EACA,oBAAAG,EACA,sBAAAC,CACF,CACF,EAEA,IAAOvB,EAAQO",
|
|
6
|
+
"names": ["use_in_app_exports", "__export", "use_in_app_default", "__toCommonJS", "import_react_hot_toast", "import_react", "import_browser", "import_use_dashx_provider", "import_DashXProvider", "useInApp", "dashX", "useDashXProvider", "subscribe", "messages", "setMessages", "unreadMessagesCount", "setUnreadMessagesCount", "hasMore", "setHasMore", "isLoadingMore", "setIsLoadingMore", "markMessageAsRead", "id", "error", "markMessageAsUnread", "markAllMessagesAsRead", "loadMore", "more", "nextMessages", "message", "toast"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import
|
|
1
|
+
import q from"uuid-random";import{useCallback as m,useEffect as D,useRef as M,useState as C}from"react";import F from"./use-dashx-provider.js";import{useWebSocket as L}from"../providers/DashXProvider.js";const $="in_app_chat:conversation:",b=e=>({id:e.id,externalUid:e.externalUid??null,renderedContent:e.renderedContent,aiRole:e.aiRole??null,createdAt:e.createdAt,turnSeq:e.turnSeq}),X=(e,i)=>{const r=new Map,u=t=>t.externalUid||t.id;return[...e,...i].forEach(t=>{const n=r.get(u(t));(!n||n.isPending)&&r.set(u(t),t)}),[...r.values()].sort((t,n)=>t.createdAt!==n.createdAt?t.createdAt<n.createdAt?-1:1:(t.turnSeq??0)-(n.turnSeq??0))},K=({identityId:e,idempotencyKey:i,initialMessage:r,enabled:u=!0,onInboundMessage:t})=>{const n=F(),{isConnected:x,initializeWebSocket:y}=L(),[H,v]=C(null),[w,R]=C([]),[P,I]=C(!0),[E,l]=C(null),o=M(0),A=M(null),U=M(t);U.current=t;const c=m(a=>{R(s=>X(s,a))},[]);D(()=>{const a=o.current+=1,s=()=>a!==o.current;if(v(null),R([]),l(null),A.current=null,!u)return I(!1),()=>{o.current+=1};I(!0),y();let d;return(async()=>{try{const g=r?{identityId:e,clientIdempotencyKey:i,content:{text:r},clientMessageId:`${i.slice(0,122)}-intro`}:{identityId:e,clientIdempotencyKey:i},f=await n.startInAppChatConversation(g);if(s())return;const p=f.id;v(p),A.current=p;const S=async()=>{const h=await n.fetchInAppChatMessages({conversationId:p});s()||c(h.map(b))},k=n.subscribeToChannel(`${$}${p}`,h=>{s()||(c([b(h)]),U.current?.(h))},{onReconnectAck:()=>{s()||(l(null),S().catch(()=>{}))}});d=k.unsubscribe;try{await k.ready}catch{s()||l("Couldn\u2019t connect to live chat. Retrying\u2026");return}if(s())return;await S()}catch{s()||l("Failed to start chat")}finally{s()||I(!1)}})(),()=>{o.current+=1,d?.()}},[n,e,i,r,u,y,c]);const _=m(a=>{const s=A.current;if(!a.trim()||!s)return!1;const d=o.current,g=q(),f={id:g,externalUid:`in_app_chat:${g}`,renderedContent:{text:a},aiRole:"USER",createdAt:new Date().toISOString(),isPending:!0};return c([f]),(async()=>{try{const p=await n.sendInAppChatMessage({conversationId:s,identityId:e,content:{text:a},clientMessageId:g});if(d!==o.current)return;c([b(p)])}catch{d===o.current&&l("Failed to send message")}})(),!0},[n,e,c]);return{conversationId:H,messages:w,isLoading:P,isConnected:x,error:E,sendMessage:_}};var z=K;export{z 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 const conversation = await dashX.startInAppChatConversation({\n identityId,\n clientIdempotencyKey: idempotencyKey,\n // Stable client message id \u2192 the automated message is inserted once,\n // even if the conversation is reopened (the server dedups repeat sends).\n // `-` separator (client ids allow only `[A-Za-z0-9._-]`); the key is\n // truncated so the suffixed id stays within the 1-128 char limit.\n ...(initialMessage\n ? { content: { text: initialMessage }, clientMessageId: `${idempotencyKey.slice(0, 122)}-intro` }\n : {}),\n });\n if (isStale()) return;\n\n const convId = conversation.id;\n setConversationId(convId);\n conversationIdRef.current = convId;\n\n const refetchHistory = async () => {\n const history = await dashX.fetchInAppChatMessages({ conversationId: convId });\n if (isStale()) return;\n appendMessages(history.map(toUiMessage));\n };\n\n // Subscribe BEFORE fetching history so a reply landing in the gap is\n // buffered, not dropped. `onReconnectAck` fires on reconnect re-acks and\n // on a first ack that arrives after a `ready` timeout \u2014 both mean we are\n // (now) subscribed, so clear any connection error and (re)load history.\n const subscription = dashX.subscribeToChannel(\n `${CHAT_CHANNEL_PREFIX}${convId}`,\n (event) => {\n if (isStale()) return;\n appendMessages([toUiMessage(event)]);\n // LIVE messages only \u2014 history load / reconnect refetch go through\n // `refetchHistory`, so notification consumers never fire for\n // backfilled messages.\n onInboundMessageRef.current?.(event);\n },\n {\n onReconnectAck: () => {\n if (isStale()) return;\n setError(null);\n refetchHistory().catch(() => {});\n },\n },\n );\n unsubscribe = subscription.unsubscribe;\n\n // Load history only once the subscription is acked \u2014 fetching before\n // that would show history while silently never receiving realtime\n // replies. On ack failure, surface an error and defer the fetch to\n // `onReconnectAck` (fires if/when the channel finally acks).\n try {\n await subscription.ready;\n } catch {\n if (!isStale()) setError('Couldn\u2019t connect to live chat. Retrying\u2026');\n return;\n }\n if (isStale()) return;\n await refetchHistory();\n } catch {\n if (!isStale()) setError('Failed to start chat');\n } finally {\n if (!isStale()) setIsLoading(false);\n }\n })();\n\n return () => {\n // Invalidate in-flight async and drop the old channel before the next\n // conversation binds.\n generationRef.current += 1;\n unsubscribe?.();\n };\n }, [dashX, identityId, idempotencyKey, initialMessage, enabled, initializeWebSocket, appendMessages]);\n\n // Synchronous on purpose: it returns `true` the moment the message is optimistically\n // queued and runs the network send in the background. The caller clears the composer\n // on `true` immediately \u2014 if it instead awaited the round-trip, a fast second Enter\n // would re-send the still-present text as a new message (fresh clientMessageId, so the\n // backend won't dedupe it) and create a duplicate.\n const sendMessage = useCallback(\n (text: string): boolean => {\n const convId = conversationIdRef.current;\n // Not ready (conversation still starting, or start failed) \u2014 report back so\n // the caller can keep the typed text instead of clearing it on a no-op send.\n if (!text.trim() || !convId) return false;\n\n // Pin the generation so a response that resolves after the identity/key\n // changed (or unmount) can't contaminate the new conversation's state.\n const generation = generationRef.current;\n const clientMessageId = uuid();\n const optimistic: InAppChatMessage = {\n id: clientMessageId,\n externalUid: `in_app_chat:${clientMessageId}`,\n renderedContent: { text },\n aiRole: 'USER',\n createdAt: new Date().toISOString(),\n isPending: true,\n };\n appendMessages([optimistic]);\n\n void (async () => {\n try {\n const serverMessage = await dashX.sendInAppChatMessage({\n conversationId: convId,\n identityId,\n content: { text },\n clientMessageId,\n });\n if (generation !== generationRef.current) return;\n // Reconcile by externalUid (the WS echo reconciles too \u2014 both idempotent).\n appendMessages([toUiMessage(serverMessage)]);\n } catch {\n if (generation === generationRef.current) setError('Failed to send message');\n }\n })();\n\n // Queued (optimistically appended) \u2014 the background send reconciles/errors later.\n return true;\n },\n [dashX, identityId, appendMessages],\n );\n\n return { conversationId, messages, isLoading, isConnected, error, sendMessage };\n};\n\nexport type { UseInAppChatHookProps, UseInAppChatHookResponse, InAppChatMessage };\n\nexport default useInAppChat;\n"],
|
|
5
|
-
"mappings": "AAAA,OAAOA,MAAU,cACjB,OAAS,eAAAC,EAAa,aAAAC,EAAW,UAAAC,EAAQ,YAAAC,MAAgB,QAGzD,OAAOC,MAAsB,0BAC7B,OAAS,gBAAAC,MAAoB,gCAiD7B,MAAMC,EAAsB,4BAEtBC,EAAeC,IAAqD,CACxE,GAAIA,EAAQ,GAGZ,YAAaA,EAAQ,aAAe,KACpC,gBAAiBA,EAAQ,gBACzB,OAAQA,EAAQ,QAAU,KAC1B,UAAWA,EAAQ,UACnB,QAASA,EAAQ,OACnB,GAOMC,EAAgB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CAAC,EACdI,EAAS,IAAI,EACbE,EAAkB,QAAU,KAIxB,CAACd,EACH,OAAAU,EAAa,EAAK,EACX,IAAM,CAAEG,EAAc,SAAW,CAAG,EAG7CH,EAAa,EAAI,EAGjBN,EAAoB,EAEpB,IAAIgB,EAEJ,OAAC,SAAY,CACX,GAAI,
|
|
6
|
-
"names": ["uuid", "useCallback", "useEffect", "useRef", "useState", "useDashXProvider", "useWebSocket", "CHAT_CHANNEL_PREFIX", "toUiMessage", "message", "mergeMessages", "existing", "incoming", "byKey", "keyOf", "existingForKey", "a", "b", "useInAppChat", "identityId", "idempotencyKey", "initialMessage", "enabled", "onInboundMessage", "dashX", "isConnected", "initializeWebSocket", "conversationId", "setConversationId", "messages", "setMessages", "isLoading", "setIsLoading", "error", "setError", "generationRef", "conversationIdRef", "onInboundMessageRef", "appendMessages", "prev", "generation", "isStale", "unsubscribe", "conversation", "convId", "refetchHistory", "history", "subscription", "event", "sendMessage", "text", "clientMessageId", "optimistic", "serverMessage", "use_in_app_chat_default"]
|
|
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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,EAGI,EACT,EACA,CAACV,EAAOL,EAAYmB,CAAc,CACpC,EAEA,MAAO,CAAE,eAAAX,EAAgB,SAAAE,EAAU,UAAAE,EAAW,YAAAN,EAAa,MAAAQ,EAAO,YAAAiB,CAAY,CAChF,EAIA,IAAOK,EAAQrC",
|
|
6
|
+
"names": ["uuid", "useCallback", "useEffect", "useRef", "useState", "useDashXProvider", "useWebSocket", "CHAT_CHANNEL_PREFIX", "toUiMessage", "message", "mergeMessages", "existing", "incoming", "byKey", "keyOf", "existingForKey", "a", "b", "useInAppChat", "identityId", "idempotencyKey", "initialMessage", "enabled", "onInboundMessage", "dashX", "isConnected", "initializeWebSocket", "conversationId", "setConversationId", "messages", "setMessages", "isLoading", "setIsLoading", "error", "setError", "generationRef", "conversationIdRef", "onInboundMessageRef", "appendMessages", "prev", "generation", "isStale", "unsubscribe", "startArgs", "conversation", "convId", "refetchHistory", "history", "subscription", "event", "sendMessage", "text", "clientMessageId", "optimistic", "serverMessage", "use_in_app_chat_default"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import k from"react-hot-toast";import{useEffect as
|
|
1
|
+
import k from"react-hot-toast";import{useEffect as i,useState as o}from"react";import{WebsocketMessage as b,IN_APP_MESSAGES_PAGE_SIZE as g}from"@dashx/browser";import I from"./use-dashx-provider.js";import{useWebSocket as y}from"../providers/DashXProvider.js";const P=()=>{let s=I();const{subscribe:r}=y(),[l,m]=o([]),[d,M]=o(null),[n,t]=o(!1),[c,p]=o(!1),u=e=>s.trackMessage({id:e,status:"READ"}).catch(a=>{console.error("DashX: failed to mark in-app message as read",a)}),A=e=>s.trackMessage({id:e,status:"UNREAD"}).catch(a=>{console.error("DashX: failed to mark in-app message as unread",a)}),f=()=>s.trackAllMessages().catch(e=>{console.error("DashX: failed to mark all in-app messages as read",e)}),h=async()=>{if(!(c||!n)){p(!0);try{const{hasMore:e}=await s.fetchMoreInAppMessages();t(e)}catch(e){console.error("DashX: failed to fetch more in-app messages",e)}finally{p(!1)}}};return i(()=>{s.watchFetchInAppMessages(e=>{m(e),e.length<=g&&t(e.length===g)}),s.watchFetchInAppMessagesAggregate(M)},[s]),i(()=>r(a=>{a?.type===b.IN_APP_MESSAGE&&k(a.data.renderedContent.body)}),[r]),{messages:l,unreadMessagesCount:d,hasMore:n,isLoadingMore:c,loadMore:h,markMessageAsRead:u,markMessageAsUnread:A,markAllMessagesAsRead:f}};var U=P;export{U as default};
|
|
2
2
|
//# sourceMappingURL=use-in-app.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/hooks/use-in-app.ts"],
|
|
4
|
-
"sourcesContent": ["import toast from 'react-hot-toast';\nimport { useEffect, useState } from 'react';\nimport { WebsocketMessage, IN_APP_MESSAGES_PAGE_SIZE } from '@dashx/browser';\nimport type { InAppMessages, WebsocketMessageType } from '@dashx/browser';\n\nimport useDashXProvider from './use-dashx-provider.js';\nimport { useWebSocket } from '../providers/DashXProvider.js';\n\ntype UseInAppHookResponse = {\n messages: InAppMessages;\n unreadMessagesCount: number | null;\n hasMore: boolean;\n isLoadingMore: boolean;\n loadMore: () => Promise<void>;\n markMessageAsRead: (id: string) => Promise<any>;\n markMessageAsUnread: (id: string) => Promise<any>;\n markAllMessagesAsRead: () => Promise<any>;\n};\n\nconst useInApp = (): UseInAppHookResponse => {\n let dashX = useDashXProvider();\n const { subscribe } = useWebSocket();\n const [messages, setMessages] = useState<InAppMessages>([]);\n const [unreadMessagesCount, setUnreadMessagesCount] = useState<number | null>(null);\n const [hasMore, setHasMore] = useState(false);\n const [isLoadingMore, setIsLoadingMore] = useState(false);\n\n const markMessageAsRead = (id: string)
|
|
5
|
-
"mappings": "AAAA,OAAOA,MAAW,kBAClB,OAAS,aAAAC,EAAW,YAAAC,MAAgB,QACpC,OAAS,oBAAAC,EAAkB,6BAAAC,MAAiC,iBAG5D,OAAOC,MAAsB,0BAC7B,OAAS,gBAAAC,MAAoB,gCAa7B,MAAMC,EAAW,IAA4B,CAC3C,IAAIC,EAAQH,EAAiB,EAC7B,KAAM,CAAE,UAAAI,CAAU,EAAIH,EAAa,EAC7B,CAACI,EAAUC,CAAW,EAAIT,EAAwB,CAAC,CAAC,EACpD,CAACU,EAAqBC,CAAsB,EAAIX,EAAwB,IAAI,EAC5E,CAACY,EAASC,CAAU,EAAIb,EAAS,EAAK,EACtC,CAACc,EAAeC,CAAgB,EAAIf,EAAS,EAAK,EAElDgB,EAAqBC,
|
|
6
|
-
"names": ["toast", "useEffect", "useState", "WebsocketMessage", "IN_APP_MESSAGES_PAGE_SIZE", "useDashXProvider", "useWebSocket", "useInApp", "dashX", "subscribe", "messages", "setMessages", "unreadMessagesCount", "setUnreadMessagesCount", "hasMore", "setHasMore", "isLoadingMore", "setIsLoadingMore", "markMessageAsRead", "id", "markMessageAsUnread", "markAllMessagesAsRead", "loadMore", "more", "nextMessages", "message", "use_in_app_default"]
|
|
4
|
+
"sourcesContent": ["import toast from 'react-hot-toast';\nimport { useEffect, useState } from 'react';\nimport { WebsocketMessage, IN_APP_MESSAGES_PAGE_SIZE } from '@dashx/browser';\nimport type { InAppMessages, WebsocketMessageType } from '@dashx/browser';\n\nimport useDashXProvider from './use-dashx-provider.js';\nimport { useWebSocket } from '../providers/DashXProvider.js';\n\ntype UseInAppHookResponse = {\n messages: InAppMessages;\n unreadMessagesCount: number | null;\n hasMore: boolean;\n isLoadingMore: boolean;\n loadMore: () => Promise<void>;\n markMessageAsRead: (id: string) => Promise<any>;\n markMessageAsUnread: (id: string) => Promise<any>;\n markAllMessagesAsRead: () => Promise<any>;\n};\n\nconst useInApp = (): UseInAppHookResponse => {\n let dashX = useDashXProvider();\n const { subscribe } = useWebSocket();\n const [messages, setMessages] = useState<InAppMessages>([]);\n const [unreadMessagesCount, setUnreadMessagesCount] = useState<number | null>(null);\n const [hasMore, setHasMore] = useState(false);\n const [isLoadingMore, setIsLoadingMore] = useState(false);\n\n const markMessageAsRead = (id: string) =>\n dashX.trackMessage({ id, status: 'READ' }).catch((error: unknown) => {\n console.error('DashX: failed to mark in-app message as read', error);\n });\n\n const markMessageAsUnread = (id: string) =>\n dashX.trackMessage({ id, status: 'UNREAD' }).catch((error: unknown) => {\n console.error('DashX: failed to mark in-app message as unread', error);\n });\n\n const markAllMessagesAsRead = () =>\n dashX.trackAllMessages().catch((error: unknown) => {\n console.error('DashX: failed to mark all in-app messages as read', error);\n });\n\n const loadMore = async () => {\n if (isLoadingMore || !hasMore) return;\n setIsLoadingMore(true);\n try {\n const { hasMore: more } = await dashX.fetchMoreInAppMessages();\n setHasMore(more);\n } catch (error) {\n // hasMore stays true so a later scroll retries the page.\n console.error('DashX: failed to fetch more in-app messages', error);\n } finally {\n setIsLoadingMore(false);\n }\n };\n\n useEffect(() => {\n // Set up in-app message watchers (automatically refetch on WebSocket reconnection)\n dashX.watchFetchInAppMessages((nextMessages) => {\n setMessages(nextMessages);\n // While the list is a single page (initial load, empty inbox, or a reconnect\n // refetch of page 1), a full page implies more; past that, loadMore owns hasMore.\n if (nextMessages.length <= IN_APP_MESSAGES_PAGE_SIZE) {\n setHasMore(nextMessages.length === IN_APP_MESSAGES_PAGE_SIZE);\n }\n });\n dashX.watchFetchInAppMessagesAggregate(setUnreadMessagesCount);\n }, [dashX]);\n\n useEffect(() => {\n // Subscribe to WebSocket messages for in-app messages\n const unsubscribe = subscribe((message: WebsocketMessageType) => {\n // Handle only IN_APP_MESSAGE for toast display\n // The client handles all other message processing internally\n if (message?.type === WebsocketMessage.IN_APP_MESSAGE) {\n toast(message.data.renderedContent.body);\n }\n });\n\n return unsubscribe;\n }, [subscribe]);\n\n return {\n messages,\n unreadMessagesCount,\n hasMore,\n isLoadingMore,\n loadMore,\n markMessageAsRead,\n markMessageAsUnread,\n markAllMessagesAsRead,\n };\n};\n\nexport default useInApp;\n"],
|
|
5
|
+
"mappings": "AAAA,OAAOA,MAAW,kBAClB,OAAS,aAAAC,EAAW,YAAAC,MAA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B,CAC/D,EAAG,CAACL,CAAK,CAAC,EAEVP,EAAU,IAEYQ,EAAWiB,GAAkC,CAG3DA,GAAS,OAASvB,EAAiB,gBACrCH,EAAM0B,EAAQ,KAAK,gBAAgB,IAAI,CAE3C,CAAC,EAGA,CAACjB,CAAS,CAAC,EAEP,CACL,SAAAC,EACA,oBAAAE,EACA,QAAAE,EACA,cAAAE,EACA,SAAAO,EACA,kBAAAL,EACA,oBAAAG,EACA,sBAAAC,CACF,CACF,EAEA,IAAOK,EAAQpB",
|
|
6
|
+
"names": ["toast", "useEffect", "useState", "WebsocketMessage", "IN_APP_MESSAGES_PAGE_SIZE", "useDashXProvider", "useWebSocket", "useInApp", "dashX", "subscribe", "messages", "setMessages", "unreadMessagesCount", "setUnreadMessagesCount", "hasMore", "setHasMore", "isLoadingMore", "setIsLoadingMore", "markMessageAsRead", "id", "error", "markMessageAsUnread", "markAllMessagesAsRead", "loadMore", "more", "nextMessages", "message", "use_in_app_default"]
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dashx/react",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.7",
|
|
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.9.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",
|
|
@@ -151,17 +151,26 @@ const useInAppChat = ({ identityId, idempotencyKey, initialMessage, enabled = tr
|
|
|
151
151
|
|
|
152
152
|
(async () => {
|
|
153
153
|
try {
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
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);
|
|
165
174
|
if (isStale()) return;
|
|
166
175
|
|
|
167
176
|
const convId = conversation.id;
|
package/src/hooks/use-in-app.ts
CHANGED
|
@@ -25,14 +25,20 @@ const useInApp = (): UseInAppHookResponse => {
|
|
|
25
25
|
const [hasMore, setHasMore] = useState(false);
|
|
26
26
|
const [isLoadingMore, setIsLoadingMore] = useState(false);
|
|
27
27
|
|
|
28
|
-
const markMessageAsRead = (id: string) =>
|
|
28
|
+
const markMessageAsRead = (id: string) =>
|
|
29
|
+
dashX.trackMessage({ id, status: 'READ' }).catch((error: unknown) => {
|
|
30
|
+
console.error('DashX: failed to mark in-app message as read', error);
|
|
31
|
+
});
|
|
29
32
|
|
|
30
|
-
const markMessageAsUnread =
|
|
31
|
-
dashX.trackMessage({ id, status: 'UNREAD' })
|
|
33
|
+
const markMessageAsUnread = (id: string) =>
|
|
34
|
+
dashX.trackMessage({ id, status: 'UNREAD' }).catch((error: unknown) => {
|
|
35
|
+
console.error('DashX: failed to mark in-app message as unread', error);
|
|
36
|
+
});
|
|
32
37
|
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
38
|
+
const markAllMessagesAsRead = () =>
|
|
39
|
+
dashX.trackAllMessages().catch((error: unknown) => {
|
|
40
|
+
console.error('DashX: failed to mark all in-app messages as read', error);
|
|
41
|
+
});
|
|
36
42
|
|
|
37
43
|
const loadMore = async () => {
|
|
38
44
|
if (isLoadingMore || !hasMore) return;
|
|
@@ -40,6 +46,9 @@ const useInApp = (): UseInAppHookResponse => {
|
|
|
40
46
|
try {
|
|
41
47
|
const { hasMore: more } = await dashX.fetchMoreInAppMessages();
|
|
42
48
|
setHasMore(more);
|
|
49
|
+
} catch (error) {
|
|
50
|
+
// hasMore stays true so a later scroll retries the page.
|
|
51
|
+
console.error('DashX: failed to fetch more in-app messages', error);
|
|
43
52
|
} finally {
|
|
44
53
|
setIsLoadingMore(false);
|
|
45
54
|
}
|
|
@@ -49,10 +58,8 @@ const useInApp = (): UseInAppHookResponse => {
|
|
|
49
58
|
// Set up in-app message watchers (automatically refetch on WebSocket reconnection)
|
|
50
59
|
dashX.watchFetchInAppMessages((nextMessages) => {
|
|
51
60
|
setMessages(nextMessages);
|
|
52
|
-
//
|
|
53
|
-
//
|
|
54
|
-
// reconnect (which resets the cache). A full first page implies more; a short or
|
|
55
|
-
// empty one doesn't. Once paged past the first page, fetchMoreInAppMessages owns it.
|
|
61
|
+
// While the list is a single page (initial load, empty inbox, or a reconnect
|
|
62
|
+
// refetch of page 1), a full page implies more; past that, loadMore owns hasMore.
|
|
56
63
|
if (nextMessages.length <= IN_APP_MESSAGES_PAGE_SIZE) {
|
|
57
64
|
setHasMore(nextMessages.length === IN_APP_MESSAGES_PAGE_SIZE);
|
|
58
65
|
}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";var l=Object.defineProperty;var g=Object.getOwnPropertyDescriptor;var u=Object.getOwnPropertyNames;var c=Object.prototype.hasOwnProperty;var m=(a,r)=>{for(var n in r)l(a,n,{get:r[n],enumerable:!0})},T=(a,r,n,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of u(r))!c.call(a,o)&&o!==n&&l(a,o,{get:()=>r[o],enumerable:!(s=g(r,o))||s.enumerable});return a};var h=a=>T(l({},"__esModule",{value:!0}),a);var f={};m(f,{default:()=>x});module.exports=h(f);var t=require("react/jsx-runtime"),d=require("date-fns"),p=require("../hooks/index.js"),e=require("../components"),i=require("../icons/index.js");const v=()=>{let{markNotificationAsRead:a,markNotificationAsUnread:r,notifications:n,unreadNotificationsCount:s}=(0,p.useInApp)();return(0,t.jsx)(e.Theme,{children:(0,t.jsxs)(e.Popover.Root,{children:[(0,t.jsxs)(e.Tooltip.Root,{children:[(0,t.jsx)(e.Tooltip.Trigger,{children:(0,t.jsx)(e.Popover.Trigger,{children:(0,t.jsx)(e.Button,{shape:"square",roundness:"full",variant:s?"fill":"ghost",children:(0,t.jsx)(i.Inbox,{})})})}),(0,t.jsx)(e.Tooltip.Content,{content:"Notification"})]}),(0,t.jsxs)(e.Popover.Content,{spacing:"large",width:"350px",height:"450px",children:[(0,t.jsx)(e.Popover.Header,{asChild:!0,children:(0,t.jsxs)(e.Flex,{justify:"between",align:"center",children:[(0,t.jsx)(e.Heading,{size:3,children:"Notifications"}),(0,t.jsx)(e.Popover.Close,{children:(0,t.jsx)(e.Button,{shape:"square",roundness:"full",variant:"ghost",mode:"subtle",inset:"right",children:(0,t.jsx)(i.X,{})})})]})}),(0,t.jsx)(e.Popover.Body,{children:(0,t.jsxs)(e.Flex,{direction:"column",gap:1,children:[n.length===0&&(0,t.jsx)(e.Flex,{justify:"center",align:"center",children:(0,t.jsx)(e.Text,{variant:"tertiary",size:2,children:"No notifications yet."})}),n.map(o=>(0,t.jsx)(e.Card,{children:(0,t.jsxs)(e.Flex,{align:"center",gap:4,justify:"between",children:[(0,t.jsxs)(e.Flex,{direction:"column",gap:1,children:[(0,t.jsx)(e.Text,{as:"p",variant:"secondary",weight:"semibold",size:2,children:o.renderedContent.body}),(0,t.jsx)(e.Text,{size:1,variant:"tertiary",children:(0,d.intlFormatDistance)(o.sentAt,new Date)})]}),(0,t.jsxs)(e.Tooltip.Root,{children:[(0,t.jsx)(e.Tooltip.Trigger,{children:(0,t.jsx)(e.Button,{shape:"square",variant:"ghost",roundness:"full",mode:o.readAt?"subtle":"distinct",onPress:()=>{o.readAt?r(o.id):a(o.id)},children:o.readAt?(0,t.jsx)(i.MailOpen,{}):(0,t.jsx)(i.Mail,{})})}),(0,t.jsx)(e.Tooltip.Content,{content:o.readAt?"Mark as unread":"Mark as read"})]})]})},o.id))]})}),(0,t.jsx)(e.Popover.Footer,{asChild:!0,children:(0,t.jsx)(e.Text,{as:"p",align:"center",color:"accent",variant:"tertiary",size:1,children:"Powered by DashX"})})]})]})})};var x=v;
|
|
2
|
-
//# sourceMappingURL=NotificationBell.js.map
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../../../src/widgets/NotificationBell.tsx"],
|
|
4
|
-
"sourcesContent": ["import { intlFormatDistance } from 'date-fns';\n\nimport { useInApp } from '../hooks/index.js';\nimport { Button, Card, Flex, Heading, Popover, Text, Theme, Tooltip } from '../components';\nimport { Inbox, Mail, MailOpen, X } from '../icons/index.js';\n\nconst NotificationBell = () => {\n let {\n markNotificationAsRead,\n markNotificationAsUnread,\n notifications,\n unreadNotificationsCount,\n } = useInApp();\n\n return (\n <Theme>\n <Popover.Root>\n <Tooltip.Root>\n <Tooltip.Trigger>\n <Popover.Trigger>\n <Button\n shape=\"square\"\n roundness=\"full\"\n variant={unreadNotificationsCount ? 'fill' : 'ghost'}\n >\n <Inbox />\n </Button>\n </Popover.Trigger>\n </Tooltip.Trigger>\n <Tooltip.Content content=\"Notification\" />\n </Tooltip.Root>\n <Popover.Content spacing=\"large\" width=\"350px\" height=\"450px\">\n <Popover.Header asChild>\n <Flex justify=\"between\" align=\"center\">\n <Heading size={3}>Notifications</Heading>\n <Popover.Close>\n <Button shape=\"square\" roundness=\"full\" variant=\"ghost\" mode=\"subtle\" inset=\"right\">\n <X />\n </Button>\n </Popover.Close>\n </Flex>\n </Popover.Header>\n <Popover.Body>\n <Flex direction=\"column\" gap={1}>\n {notifications.length === 0 && (\n <Flex justify=\"center\" align=\"center\">\n <Text variant=\"tertiary\" size={2}>\n No notifications yet.\n </Text>\n </Flex>\n )}\n {notifications.map((notification) => (\n <Card key={notification.id}>\n <Flex align=\"center\" gap={4} justify=\"between\">\n <Flex direction=\"column\" gap={1}>\n <Text as=\"p\" variant=\"secondary\" weight=\"semibold\" size={2}>\n {notification.renderedContent.body}\n </Text>\n <Text size={1} variant=\"tertiary\">\n {intlFormatDistance(notification.sentAt, new Date())}\n </Text>\n </Flex>\n <Tooltip.Root>\n <Tooltip.Trigger>\n <Button\n shape=\"square\"\n variant=\"ghost\"\n roundness=\"full\"\n mode={notification.readAt ? 'subtle' : 'distinct'}\n onPress={() => {\n if (notification.readAt) {\n markNotificationAsUnread(notification.id);\n } else {\n markNotificationAsRead(notification.id);\n }\n }}\n >\n {notification.readAt ? <MailOpen /> : <Mail />}\n </Button>\n </Tooltip.Trigger>\n <Tooltip.Content\n content={notification.readAt ? 'Mark as unread' : 'Mark as read'}\n />\n </Tooltip.Root>\n </Flex>\n </Card>\n ))}\n </Flex>\n </Popover.Body>\n <Popover.Footer asChild>\n <Text as=\"p\" align=\"center\" color=\"accent\" variant=\"tertiary\" size={1}>\n Powered by DashX\n </Text>\n </Popover.Footer>\n </Popover.Content>\n </Popover.Root>\n </Theme>\n );\n};\n\nexport default NotificationBell;\n"],
|
|
5
|
-
"mappings":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EAAa,gBAAgB,KAChC,KACA,OAAC,QAAK,KAAM,EAAG,QAAQ,WACpB,kCAAmBA,EAAa,OAAQ,IAAI,IAAM,EACrD,GACF,KACA,QAAC,UAAQ,KAAR,CACC,oBAAC,UAAQ,QAAR,CACC,mBAAC,UACC,MAAM,SACN,QAAQ,QACR,UAAU,OACV,KAAMA,EAAa,OAAS,SAAW,WACvC,QAAS,IAAM,CACTA,EAAa,OACfH,EAAyBG,EAAa,EAAE,EAExCJ,EAAuBI,EAAa,EAAE,CAE1C,EAEC,SAAAA,EAAa,UAAS,OAAC,aAAS,KAAK,OAAC,SAAK,EAC9C,EACF,KACA,OAAC,UAAQ,QAAR,CACC,QAASA,EAAa,OAAS,iBAAmB,eACpD,GACF,GACF,GAhCSA,EAAa,EAiCxB,CACD,GACH,EACF,KACA,OAAC,UAAQ,OAAR,CAAe,QAAO,GACrB,mBAAC,QAAK,GAAG,IAAI,MAAM,SAAS,MAAM,SAAS,QAAQ,WAAW,KAAM,EAAG,4BAEvE,EACF,GACF,GACF,EACF,CAEJ,EAEA,IAAOZ,EAAQO",
|
|
6
|
-
"names": ["NotificationBell_exports", "__export", "NotificationBell_default", "__toCommonJS", "import_jsx_runtime", "import_date_fns", "import_hooks", "import_components", "import_icons", "NotificationBell", "markNotificationAsRead", "markNotificationAsUnread", "notifications", "unreadNotificationsCount", "notification"]
|
|
7
|
-
}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{jsx as e,jsxs as o}from"react/jsx-runtime";import{intlFormatDistance as u}from"date-fns";import{useInApp as c}from"../hooks/index.js";import{Button as s,Card as m,Flex as i,Heading as T,Popover as r,Text as n,Theme as h,Tooltip as a}from"../components";import{Inbox as v,Mail as x,MailOpen as f,X as y}from"../icons/index.js";const C=()=>{let{markNotificationAsRead:d,markNotificationAsUnread:p,notifications:l,unreadNotificationsCount:g}=c();return e(h,{children:o(r.Root,{children:[o(a.Root,{children:[e(a.Trigger,{children:e(r.Trigger,{children:e(s,{shape:"square",roundness:"full",variant:g?"fill":"ghost",children:e(v,{})})})}),e(a.Content,{content:"Notification"})]}),o(r.Content,{spacing:"large",width:"350px",height:"450px",children:[e(r.Header,{asChild:!0,children:o(i,{justify:"between",align:"center",children:[e(T,{size:3,children:"Notifications"}),e(r.Close,{children:e(s,{shape:"square",roundness:"full",variant:"ghost",mode:"subtle",inset:"right",children:e(y,{})})})]})}),e(r.Body,{children:o(i,{direction:"column",gap:1,children:[l.length===0&&e(i,{justify:"center",align:"center",children:e(n,{variant:"tertiary",size:2,children:"No notifications yet."})}),l.map(t=>e(m,{children:o(i,{align:"center",gap:4,justify:"between",children:[o(i,{direction:"column",gap:1,children:[e(n,{as:"p",variant:"secondary",weight:"semibold",size:2,children:t.renderedContent.body}),e(n,{size:1,variant:"tertiary",children:u(t.sentAt,new Date)})]}),o(a.Root,{children:[e(a.Trigger,{children:e(s,{shape:"square",variant:"ghost",roundness:"full",mode:t.readAt?"subtle":"distinct",onPress:()=>{t.readAt?p(t.id):d(t.id)},children:t.readAt?e(f,{}):e(x,{})})}),e(a.Content,{content:t.readAt?"Mark as unread":"Mark as read"})]})]})},t.id))]})}),e(r.Footer,{asChild:!0,children:e(n,{as:"p",align:"center",color:"accent",variant:"tertiary",size:1,children:"Powered by DashX"})})]})]})})};var B=C;export{B as default};
|
|
2
|
-
//# sourceMappingURL=NotificationBell.js.map
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../../../src/widgets/NotificationBell.tsx"],
|
|
4
|
-
"sourcesContent": ["import { intlFormatDistance } from 'date-fns';\n\nimport { useInApp } from '../hooks/index.js';\nimport { Button, Card, Flex, Heading, Popover, Text, Theme, Tooltip } from '../components';\nimport { Inbox, Mail, MailOpen, X } from '../icons/index.js';\n\nconst NotificationBell = () => {\n let {\n markNotificationAsRead,\n markNotificationAsUnread,\n notifications,\n unreadNotificationsCount,\n } = useInApp();\n\n return (\n <Theme>\n <Popover.Root>\n <Tooltip.Root>\n <Tooltip.Trigger>\n <Popover.Trigger>\n <Button\n shape=\"square\"\n roundness=\"full\"\n variant={unreadNotificationsCount ? 'fill' : 'ghost'}\n >\n <Inbox />\n </Button>\n </Popover.Trigger>\n </Tooltip.Trigger>\n <Tooltip.Content content=\"Notification\" />\n </Tooltip.Root>\n <Popover.Content spacing=\"large\" width=\"350px\" height=\"450px\">\n <Popover.Header asChild>\n <Flex justify=\"between\" align=\"center\">\n <Heading size={3}>Notifications</Heading>\n <Popover.Close>\n <Button shape=\"square\" roundness=\"full\" variant=\"ghost\" mode=\"subtle\" inset=\"right\">\n <X />\n </Button>\n </Popover.Close>\n </Flex>\n </Popover.Header>\n <Popover.Body>\n <Flex direction=\"column\" gap={1}>\n {notifications.length === 0 && (\n <Flex justify=\"center\" align=\"center\">\n <Text variant=\"tertiary\" size={2}>\n No notifications yet.\n </Text>\n </Flex>\n )}\n {notifications.map((notification) => (\n <Card key={notification.id}>\n <Flex align=\"center\" gap={4} justify=\"between\">\n <Flex direction=\"column\" gap={1}>\n <Text as=\"p\" variant=\"secondary\" weight=\"semibold\" size={2}>\n {notification.renderedContent.body}\n </Text>\n <Text size={1} variant=\"tertiary\">\n {intlFormatDistance(notification.sentAt, new Date())}\n </Text>\n </Flex>\n <Tooltip.Root>\n <Tooltip.Trigger>\n <Button\n shape=\"square\"\n variant=\"ghost\"\n roundness=\"full\"\n mode={notification.readAt ? 'subtle' : 'distinct'}\n onPress={() => {\n if (notification.readAt) {\n markNotificationAsUnread(notification.id);\n } else {\n markNotificationAsRead(notification.id);\n }\n }}\n >\n {notification.readAt ? <MailOpen /> : <Mail />}\n </Button>\n </Tooltip.Trigger>\n <Tooltip.Content\n content={notification.readAt ? 'Mark as unread' : 'Mark as read'}\n />\n </Tooltip.Root>\n </Flex>\n </Card>\n ))}\n </Flex>\n </Popover.Body>\n <Popover.Footer asChild>\n <Text as=\"p\" align=\"center\" color=\"accent\" variant=\"tertiary\" size={1}>\n Powered by DashX\n </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ex", "Heading", "Popover", "Text", "Theme", "Tooltip", "Inbox", "Mail", "MailOpen", "X", "NotificationBell", "markNotificationAsRead", "markNotificationAsUnread", "notifications", "unreadNotificationsCount", "notification", "NotificationBell_default"]
|
|
7
|
-
}
|