feat: add support chat widget demo and state management
- Implemented SupportWidgetDemo component for configuring and mounting the support chat widget. - Introduced Zustand store for managing support chat state, including message handling and socket connection. - Created support host bridge for communication between the widget and parent window. - Added utility functions for JWT token generation and local storage management. - Enhanced user experience with notifications for new messages and chat status updates.
This commit is contained in:
@@ -0,0 +1,489 @@
|
||||
"use client"
|
||||
|
||||
import {
|
||||
HeadphonesIcon,
|
||||
Maximize2Icon,
|
||||
Minimize2Icon,
|
||||
MoreHorizontalIcon,
|
||||
MinusIcon,
|
||||
RotateCwIcon,
|
||||
XIcon,
|
||||
} from "lucide-react"
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useRef,
|
||||
useState,
|
||||
type ComponentProps,
|
||||
type CSSProperties,
|
||||
} from "react"
|
||||
import { useShallow } from "zustand/react/shallow"
|
||||
|
||||
import { SupportChatConnectionStatus } from "@/components/support-chat/connection-status"
|
||||
import { getStandaloneClosedUrl } from "@/components/support-chat/close-navigation"
|
||||
import { CustomerMessageEditor } from "@/components/support-chat/customer-message-editor"
|
||||
import {
|
||||
SupportChatMessageList,
|
||||
type SupportChatMessageListHandle,
|
||||
} from "@/components/support-chat/message-list"
|
||||
import {
|
||||
bindSupportHostBridge,
|
||||
requestSupportHostClose,
|
||||
requestSupportHostMinimize,
|
||||
requestSupportHostToggleMaximize,
|
||||
} from "@/lib/support-host-bridge"
|
||||
import { useSupportChatStore } from "@/lib/stores/support-chat"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { useI18n } from "@/i18n/provider"
|
||||
|
||||
const windowActionButtonClass =
|
||||
"size-8 rounded-md border-0 bg-transparent text-muted-foreground shadow-none hover:bg-foreground/[0.06] hover:text-foreground focus-visible:ring-primary/20 dark:hover:bg-white/10"
|
||||
|
||||
function WindowActionButton({
|
||||
className,
|
||||
...props
|
||||
}: ComponentProps<typeof Button>) {
|
||||
return (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className={cn(windowActionButtonClass, className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function getMobileStatusDotClass(status: string) {
|
||||
if (status === "connected") {
|
||||
return "bg-emerald-500 shadow-[0_0_0_3px_rgba(16,185,129,0.14)]"
|
||||
}
|
||||
if (status === "connecting") {
|
||||
return "bg-amber-500 shadow-[0_0_0_3px_rgba(245,158,11,0.16)]"
|
||||
}
|
||||
return "bg-muted-foreground shadow-[0_0_0_3px_rgba(148,163,184,0.14)]"
|
||||
}
|
||||
|
||||
function useSupportChatSystemTheme() {
|
||||
useLayoutEffect(() => {
|
||||
if (typeof window === "undefined") {
|
||||
return
|
||||
}
|
||||
const root = document.documentElement
|
||||
const query = window.matchMedia("(prefers-color-scheme: dark)")
|
||||
const previousDarkClass = root.classList.contains("dark")
|
||||
const previousColorScheme = root.style.colorScheme
|
||||
|
||||
const syncTheme = () => {
|
||||
const isDark = query.matches
|
||||
root.classList.toggle("dark", isDark)
|
||||
root.style.colorScheme = isDark ? "dark" : "light"
|
||||
}
|
||||
|
||||
syncTheme()
|
||||
query.addEventListener("change", syncTheme)
|
||||
|
||||
return () => {
|
||||
query.removeEventListener("change", syncTheme)
|
||||
root.classList.toggle("dark", previousDarkClass)
|
||||
root.style.colorScheme = previousColorScheme
|
||||
}
|
||||
}, [])
|
||||
}
|
||||
|
||||
function isEmbeddedInHost() {
|
||||
if (typeof window === "undefined") {
|
||||
return false
|
||||
}
|
||||
|
||||
try {
|
||||
return window.parent !== window
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export function SupportChatShell() {
|
||||
const t = useI18n()
|
||||
useSupportChatSystemTheme()
|
||||
|
||||
const messageListRef = useRef<SupportChatMessageListHandle | null>(null)
|
||||
const [isEmbedded, setIsEmbedded] = useState(false)
|
||||
const [isMaximized, setIsMaximized] = useState(false)
|
||||
const [isCloseDialogOpen, setIsCloseDialogOpen] = useState(false)
|
||||
const [isClosingConversation, setIsClosingConversation] = useState(false)
|
||||
|
||||
const {
|
||||
title,
|
||||
subtitle,
|
||||
themeColor,
|
||||
conversation,
|
||||
messages,
|
||||
messagesHasMore,
|
||||
messagesLoadingMore,
|
||||
loadOlderMessages,
|
||||
status,
|
||||
error,
|
||||
isOpen,
|
||||
isVisible,
|
||||
setIsOpen,
|
||||
setIsVisible,
|
||||
bootstrap,
|
||||
handleSendMessage,
|
||||
uploadMessageImage,
|
||||
sendAttachment,
|
||||
retry,
|
||||
disconnectSocket,
|
||||
markConversationRead,
|
||||
closeConversation,
|
||||
} = useSupportChatStore(
|
||||
useShallow((state) => ({
|
||||
title: state.title,
|
||||
subtitle: state.subtitle,
|
||||
themeColor: state.themeColor,
|
||||
conversation: state.conversation,
|
||||
messages: state.messages,
|
||||
messagesHasMore: state.messagesHasMore,
|
||||
messagesLoadingMore: state.messagesLoadingMore,
|
||||
loadOlderMessages: state.loadOlderMessages,
|
||||
status: state.status,
|
||||
error: state.error,
|
||||
isOpen: state.isOpen,
|
||||
isVisible: state.isVisible,
|
||||
setIsOpen: state.setIsOpen,
|
||||
setIsVisible: state.setIsVisible,
|
||||
bootstrap: state.bootstrap,
|
||||
handleSendMessage: state.handleSendMessage,
|
||||
uploadMessageImage: state.uploadMessageImage,
|
||||
sendAttachment: state.sendAttachment,
|
||||
retry: state.retry,
|
||||
disconnectSocket: state.disconnectSocket,
|
||||
markConversationRead: state.markConversationRead,
|
||||
closeConversation: state.closeConversation,
|
||||
}))
|
||||
)
|
||||
const safeMessages = Array.isArray(messages) ? messages : []
|
||||
|
||||
useEffect(() => {
|
||||
setIsEmbedded(isEmbeddedInHost())
|
||||
}, [])
|
||||
|
||||
const maybeMarkConversationRead = useCallback(() => {
|
||||
if (!isVisible || !conversation || typeof document === "undefined") {
|
||||
return
|
||||
}
|
||||
if (document.visibilityState !== "visible") {
|
||||
return
|
||||
}
|
||||
void markConversationRead().catch((readError) => {
|
||||
console.error("Failed to mark support chat conversation read", readError)
|
||||
})
|
||||
}, [conversation?.id, isVisible, markConversationRead])
|
||||
|
||||
useEffect(() => {
|
||||
return bindSupportHostBridge({
|
||||
onOpen: () => {
|
||||
setIsOpen(true)
|
||||
setIsVisible(true)
|
||||
},
|
||||
onMinimize: () => {
|
||||
setIsVisible(false)
|
||||
},
|
||||
onMaximizedChange: (nextIsMaximized) => {
|
||||
setIsMaximized(nextIsMaximized)
|
||||
},
|
||||
})
|
||||
}, [setIsOpen, setIsVisible])
|
||||
|
||||
useEffect(() => {
|
||||
bootstrap()
|
||||
|
||||
return () => {
|
||||
if (!isOpen) {
|
||||
disconnectSocket()
|
||||
}
|
||||
}
|
||||
}, [isOpen, bootstrap, disconnectSocket])
|
||||
|
||||
useEffect(() => {
|
||||
maybeMarkConversationRead()
|
||||
}, [maybeMarkConversationRead, safeMessages.length])
|
||||
|
||||
useEffect(() => {
|
||||
const handleVisibilityChange = () => {
|
||||
if (document.visibilityState === "visible") {
|
||||
maybeMarkConversationRead()
|
||||
}
|
||||
}
|
||||
const handleFocus = () => {
|
||||
maybeMarkConversationRead()
|
||||
}
|
||||
|
||||
document.addEventListener("visibilitychange", handleVisibilityChange)
|
||||
window.addEventListener("focus", handleFocus)
|
||||
return () => {
|
||||
document.removeEventListener("visibilitychange", handleVisibilityChange)
|
||||
window.removeEventListener("focus", handleFocus)
|
||||
}
|
||||
}, [maybeMarkConversationRead])
|
||||
|
||||
async function handleSend(content: string) {
|
||||
await handleSendMessage(content)
|
||||
messageListRef.current?.scrollToBottom()
|
||||
}
|
||||
|
||||
function handleMinimize() {
|
||||
setIsVisible(false)
|
||||
requestSupportHostMinimize()
|
||||
}
|
||||
|
||||
function handleToggleMaximize() {
|
||||
requestSupportHostToggleMaximize()
|
||||
}
|
||||
|
||||
async function confirmCloseConversation() {
|
||||
if (isClosingConversation) {
|
||||
return
|
||||
}
|
||||
setIsClosingConversation(true)
|
||||
try {
|
||||
if (conversation?.id) {
|
||||
await closeConversation()
|
||||
}
|
||||
setIsCloseDialogOpen(false)
|
||||
if (isEmbedded) {
|
||||
requestSupportHostClose()
|
||||
} else {
|
||||
window.location.replace(getStandaloneClosedUrl())
|
||||
}
|
||||
} catch (closeError) {
|
||||
window.alert(closeError instanceof Error ? closeError.message : t("supportChat.closeConversationFailed"))
|
||||
} finally {
|
||||
setIsClosingConversation(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!isCloseDialogOpen) {
|
||||
return
|
||||
}
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape" && !isClosingConversation) {
|
||||
setIsCloseDialogOpen(false)
|
||||
}
|
||||
}
|
||||
window.addEventListener("keydown", handleKeyDown)
|
||||
return () => window.removeEventListener("keydown", handleKeyDown)
|
||||
}, [isCloseDialogOpen, isClosingConversation])
|
||||
|
||||
return (
|
||||
<main
|
||||
className="relative flex h-[100dvh] min-h-[100dvh] overflow-hidden bg-muted text-foreground supports-not-[height:100dvh]:h-screen supports-not-[height:100dvh]:min-h-screen"
|
||||
style={{ "--primary": themeColor } as CSSProperties}
|
||||
>
|
||||
<section className="flex h-full w-full flex-col overflow-hidden bg-card text-card-foreground">
|
||||
<header className="shrink-0 border-b border-border/80 bg-card px-3 py-2 shadow-none dark:border-border/70 sm:border-primary/[0.10] sm:bg-primary/[0.06] sm:px-4 sm:py-3 sm:shadow-[0_10px_26px_rgba(15,23,42,0.06)] sm:dark:border-primary/20 sm:dark:bg-primary/10 sm:dark:shadow-none">
|
||||
<div className="flex min-w-0 items-center justify-between gap-2 sm:gap-3">
|
||||
<div className="flex min-w-0 items-center gap-2.5">
|
||||
<div className="hidden size-9 shrink-0 items-center justify-center rounded-lg bg-primary text-primary-foreground shadow-[0_8px_18px_rgba(37,99,235,0.18)] sm:flex">
|
||||
<HeadphonesIcon className="size-[18px]" />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<span
|
||||
className={cn(
|
||||
"size-1.5 shrink-0 rounded-full sm:hidden",
|
||||
getMobileStatusDotClass(status)
|
||||
)}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<div className="truncate text-sm font-semibold text-foreground sm:text-base">
|
||||
{title}
|
||||
</div>
|
||||
</div>
|
||||
<div className="hidden truncate text-xs text-muted-foreground sm:mt-1 sm:block">
|
||||
{subtitle}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-0.5 sm:hidden">
|
||||
{!isEmbedded && status !== "connected" ? (
|
||||
<WindowActionButton
|
||||
onClick={retry}
|
||||
aria-label={t("supportChat.retry")}
|
||||
title={t("supportChat.retry")}
|
||||
>
|
||||
<RotateCwIcon className="size-4" />
|
||||
</WindowActionButton>
|
||||
) : null}
|
||||
{isEmbedded ? (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger
|
||||
render={<WindowActionButton aria-label={t("supportChat.moreActions")} title={t("supportChat.moreActions")} />}
|
||||
>
|
||||
<MoreHorizontalIcon className="size-4" />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-36">
|
||||
<DropdownMenuItem onClick={retry}>
|
||||
<RotateCwIcon className="size-4" />
|
||||
{t("supportChat.retry")}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={handleMinimize}>
|
||||
<MinusIcon className="size-4" />
|
||||
{t("supportChat.minimize")}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={handleToggleMaximize}>
|
||||
{isMaximized ? (
|
||||
<Minimize2Icon className="size-4" />
|
||||
) : (
|
||||
<Maximize2Icon className="size-4" />
|
||||
)}
|
||||
{isMaximized ? t("supportChat.restoreWindow") : t("supportChat.maximize")}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
variant="destructive"
|
||||
onClick={() => setIsCloseDialogOpen(true)}
|
||||
>
|
||||
<XIcon className="size-4" />
|
||||
{t("supportChat.closeWindow")}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
) : (
|
||||
<WindowActionButton
|
||||
onClick={() => setIsCloseDialogOpen(true)}
|
||||
aria-label={t("supportChat.closeChatWindow")}
|
||||
title={t("supportChat.closeChatWindow")}
|
||||
className="hover:bg-rose-50 hover:text-rose-600 dark:hover:bg-rose-950/45 dark:hover:text-rose-300"
|
||||
>
|
||||
<XIcon className="size-4" />
|
||||
</WindowActionButton>
|
||||
)}
|
||||
</div>
|
||||
<div className="hidden shrink-0 items-center gap-1 sm:flex sm:gap-2">
|
||||
{status !== "connected" ? (
|
||||
<SupportChatConnectionStatus status={status} />
|
||||
) : null}
|
||||
<div className="flex items-center gap-0.5 rounded-lg bg-background/55 p-0.5 shadow-sm ring-1 ring-border/70 dark:bg-background/25 dark:ring-white/10">
|
||||
<WindowActionButton
|
||||
onClick={retry}
|
||||
aria-label={t("supportChat.retry")}
|
||||
title={t("supportChat.retry")}
|
||||
>
|
||||
<RotateCwIcon className="size-4" />
|
||||
</WindowActionButton>
|
||||
{isEmbedded ? (
|
||||
<>
|
||||
<WindowActionButton
|
||||
onClick={handleMinimize}
|
||||
aria-label={t("supportChat.minimize")}
|
||||
title={t("supportChat.minimize")}
|
||||
>
|
||||
<MinusIcon className="size-4" />
|
||||
</WindowActionButton>
|
||||
<WindowActionButton
|
||||
onClick={handleToggleMaximize}
|
||||
aria-label={isMaximized ? t("supportChat.restoreWindow") : t("supportChat.maximizeWindow")}
|
||||
title={isMaximized ? t("supportChat.restoreWindow") : t("supportChat.maximizeWindow")}
|
||||
>
|
||||
{isMaximized ? (
|
||||
<Minimize2Icon className="size-4" />
|
||||
) : (
|
||||
<Maximize2Icon className="size-4" />
|
||||
)}
|
||||
</WindowActionButton>
|
||||
</>
|
||||
) : null}
|
||||
<WindowActionButton
|
||||
onClick={() => setIsCloseDialogOpen(true)}
|
||||
aria-label={t("supportChat.closeChatWindow")}
|
||||
title={t("supportChat.closeChatWindow")}
|
||||
className="hover:bg-rose-50 hover:text-rose-600 dark:hover:bg-rose-950/45 dark:hover:text-rose-300"
|
||||
>
|
||||
<XIcon className="size-4" />
|
||||
</WindowActionButton>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="grid min-h-0 flex-1 grid-rows-[minmax(0,1fr)_auto] overflow-hidden bg-muted/60 dark:bg-muted/30">
|
||||
<SupportChatMessageList
|
||||
ref={messageListRef}
|
||||
messages={safeMessages}
|
||||
onNearBottomVisible={maybeMarkConversationRead}
|
||||
hasMoreOlder={messagesHasMore}
|
||||
loadingOlder={messagesLoadingMore}
|
||||
onLoadOlder={loadOlderMessages}
|
||||
/>
|
||||
<div className="shrink-0 border-t border-border/80 bg-card/95 pb-[env(safe-area-inset-bottom)] shadow-[0_-10px_24px_rgba(15,23,42,0.05)] dark:bg-card/90 dark:shadow-none">
|
||||
<CustomerMessageEditor
|
||||
disabled={!conversation}
|
||||
onSend={handleSend}
|
||||
onUploadImage={uploadMessageImage}
|
||||
onSendAttachment={sendAttachment}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error ? (
|
||||
<div className="border-t border-destructive/20 bg-destructive/10 px-4 py-3 text-sm text-destructive">
|
||||
{error}
|
||||
</div>
|
||||
) : null}
|
||||
</section>
|
||||
|
||||
<Dialog
|
||||
open={isCloseDialogOpen}
|
||||
onOpenChange={(open) => {
|
||||
if (!isClosingConversation) {
|
||||
setIsCloseDialogOpen(open)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DialogContent className="max-w-[320px]" showCloseButton={!isClosingConversation}>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t("supportChat.closeDialogTitle")}</DialogTitle>
|
||||
<DialogDescription className="text-xs leading-5">
|
||||
{t("supportChat.closeDialogDescription")}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={isClosingConversation}
|
||||
onClick={() => setIsCloseDialogOpen(false)}
|
||||
>
|
||||
{t("supportChat.continueConversation")}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="destructive"
|
||||
disabled={isClosingConversation}
|
||||
onClick={() => void confirmCloseConversation()}
|
||||
>
|
||||
{isClosingConversation ? t("supportChat.closing") : t("supportChat.confirmClose")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</main>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import assert from "node:assert/strict"
|
||||
import test from "node:test"
|
||||
import ts from "typescript"
|
||||
import { readFile } from "node:fs/promises"
|
||||
import vm from "node:vm"
|
||||
|
||||
async function loadCloseNavigation() {
|
||||
const source = await readFile(new URL("./close-navigation.ts", import.meta.url), "utf8")
|
||||
const compiled = ts.transpileModule(source, {
|
||||
compilerOptions: {
|
||||
target: ts.ScriptTarget.ES2017,
|
||||
module: ts.ModuleKind.CommonJS,
|
||||
},
|
||||
fileName: "close-navigation.ts",
|
||||
})
|
||||
const sandbox = {
|
||||
exports: {},
|
||||
module: { exports: {} },
|
||||
}
|
||||
sandbox.exports = sandbox.module.exports
|
||||
vm.runInNewContext(compiled.outputText, sandbox)
|
||||
return sandbox.module.exports
|
||||
}
|
||||
|
||||
test("standalone close navigates to the non-bootstrapping closed page", async () => {
|
||||
const { getStandaloneClosedUrl } = await loadCloseNavigation()
|
||||
|
||||
assert.equal(getStandaloneClosedUrl(), "/support/chat/closed")
|
||||
})
|
||||
@@ -0,0 +1,5 @@
|
||||
export const SUPPORT_CHAT_CLOSED_PATH = "/support/chat/closed"
|
||||
|
||||
export function getStandaloneClosedUrl() {
|
||||
return SUPPORT_CHAT_CLOSED_PATH
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
"use client"
|
||||
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { useI18n } from "@/i18n/provider"
|
||||
|
||||
type SupportChatConnectionStatusProps = {
|
||||
status: "connecting" | "connected" | "disconnected"
|
||||
}
|
||||
|
||||
export function SupportChatConnectionStatus({ status }: SupportChatConnectionStatusProps) {
|
||||
const t = useI18n()
|
||||
const toneClass =
|
||||
status === "connected"
|
||||
? "border-emerald-200 bg-emerald-50 text-emerald-700 dark:border-emerald-900/70 dark:bg-emerald-950/50 dark:text-emerald-300"
|
||||
: status === "connecting"
|
||||
? "border-amber-200 bg-amber-50 text-amber-700 dark:border-amber-900/70 dark:bg-amber-950/50 dark:text-amber-300"
|
||||
: "border-border bg-muted text-muted-foreground"
|
||||
|
||||
return (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className={cn("h-6 gap-2 px-2.5 text-[11px] font-medium shadow-sm", toneClass)}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
"inline-block size-2 rounded-full",
|
||||
status === "connected"
|
||||
? "bg-emerald-500 shadow-[0_0_0_4px_rgba(16,185,129,0.14)]"
|
||||
: status === "connecting"
|
||||
? "bg-amber-500 shadow-[0_0_0_4px_rgba(245,158,11,0.16)]"
|
||||
: "bg-muted-foreground shadow-[0_0_0_4px_rgba(148,163,184,0.14)]"
|
||||
)}
|
||||
/>
|
||||
<span>{t(`supportChat.${status}`)}</span>
|
||||
</Badge>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
"use client"
|
||||
|
||||
import {
|
||||
SharedMessageEditor,
|
||||
type UploadedMessageEditorImage,
|
||||
} from "@/components/chat/shared-message-editor"
|
||||
|
||||
type CustomerMessageEditorProps = {
|
||||
disabled?: boolean
|
||||
uploadingAsset?: boolean
|
||||
onSend: (html: string) => Promise<void>
|
||||
onUploadImage: (file: File) => Promise<UploadedMessageEditorImage | null>
|
||||
onSendAttachment: (file: File) => Promise<void>
|
||||
}
|
||||
|
||||
export function CustomerMessageEditor({
|
||||
disabled = false,
|
||||
uploadingAsset = false,
|
||||
onSend,
|
||||
onUploadImage,
|
||||
onSendAttachment,
|
||||
}: CustomerMessageEditorProps) {
|
||||
return (
|
||||
<SharedMessageEditor
|
||||
variant="customer"
|
||||
disabled={disabled}
|
||||
uploadingAsset={uploadingAsset}
|
||||
manageLocalUploading
|
||||
onSend={onSend}
|
||||
onUploadImage={onUploadImage}
|
||||
onSendAttachment={onSendAttachment}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import assert from "node:assert/strict"
|
||||
import test from "node:test"
|
||||
import ts from "typescript"
|
||||
import { readFile } from "node:fs/promises"
|
||||
import vm from "node:vm"
|
||||
|
||||
async function loadDemoNavigation() {
|
||||
const source = await readFile(new URL("./demo-navigation.ts", import.meta.url), "utf8")
|
||||
const compiled = ts.transpileModule(source, {
|
||||
compilerOptions: {
|
||||
target: ts.ScriptTarget.ES2017,
|
||||
module: ts.ModuleKind.CommonJS,
|
||||
},
|
||||
fileName: "demo-navigation.ts",
|
||||
})
|
||||
const sandbox = {
|
||||
exports: {},
|
||||
module: { exports: {} },
|
||||
}
|
||||
sandbox.exports = sandbox.module.exports
|
||||
vm.runInNewContext(compiled.outputText, sandbox)
|
||||
return sandbox.module.exports
|
||||
}
|
||||
|
||||
test("widget demo lives below support so /support remains available", async () => {
|
||||
const { getWidgetDemoPath } = await loadDemoNavigation()
|
||||
|
||||
assert.equal(getWidgetDemoPath(), "/support/demo")
|
||||
})
|
||||
@@ -0,0 +1,5 @@
|
||||
export const SUPPORT_DEMO_PATH = "/support/demo"
|
||||
|
||||
export function getWidgetDemoPath() {
|
||||
return SUPPORT_DEMO_PATH
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
"use client"
|
||||
|
||||
import {
|
||||
forwardRef,
|
||||
memo,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useImperativeHandle,
|
||||
useLayoutEffect,
|
||||
useRef,
|
||||
} from "react"
|
||||
|
||||
import { ImMessageHTML } from "@/components/im-message-html"
|
||||
import { useImageLightbox } from "@/components/image-lightbox"
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import type { ImMessage } from "@/lib/api/im"
|
||||
import { renderIMMessageHTML } from "@/lib/im-message"
|
||||
import { cn, formatDateTime } from "@/lib/utils"
|
||||
import { useI18n } from "@/i18n/provider"
|
||||
|
||||
type SupportChatMessageListProps = {
|
||||
messages?: ImMessage[] | null
|
||||
onNearBottomVisible?: () => void
|
||||
hasMoreOlder?: boolean
|
||||
loadingOlder?: boolean
|
||||
onLoadOlder?: () => Promise<void>
|
||||
}
|
||||
|
||||
export type SupportChatMessageListHandle = {
|
||||
scrollToBottom: () => void
|
||||
}
|
||||
|
||||
function getDayKey(value?: string) {
|
||||
if (!value) {
|
||||
return "unknown"
|
||||
}
|
||||
const date = new Date(value)
|
||||
if (Number.isNaN(date.getTime())) {
|
||||
return value.slice(0, 10)
|
||||
}
|
||||
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(
|
||||
date.getDate()
|
||||
).padStart(2, "0")}`
|
||||
}
|
||||
|
||||
function getTimelineLabel(
|
||||
value: string | undefined,
|
||||
t: (key: string, values?: Record<string, string | number>) => string
|
||||
) {
|
||||
if (!value) {
|
||||
return t("supportChat.justNow")
|
||||
}
|
||||
const date = new Date(value)
|
||||
if (Number.isNaN(date.getTime())) {
|
||||
return value
|
||||
}
|
||||
const currentDayKey = getDayKey(value)
|
||||
const todayDayKey = getDayKey(new Date().toISOString())
|
||||
const timeText = `${String(date.getHours()).padStart(2, "0")}:${String(
|
||||
date.getMinutes()
|
||||
).padStart(2, "0")}`
|
||||
if (currentDayKey === todayDayKey) {
|
||||
return t("supportChat.todayAt", { time: timeText })
|
||||
}
|
||||
return `${currentDayKey} ${timeText}`
|
||||
}
|
||||
|
||||
export const SupportChatMessageList = forwardRef<SupportChatMessageListHandle, SupportChatMessageListProps>(
|
||||
function SupportChatMessageList(
|
||||
{
|
||||
messages,
|
||||
onNearBottomVisible,
|
||||
hasMoreOlder = false,
|
||||
loadingOlder = false,
|
||||
onLoadOlder,
|
||||
},
|
||||
ref
|
||||
) {
|
||||
const t = useI18n()
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const contentRef = useRef<HTMLDivElement>(null)
|
||||
const frameRef = useRef<number | null>(null)
|
||||
const shouldStickToBottomRef = useRef(true)
|
||||
const onNearBottomVisibleRef = useRef(onNearBottomVisible)
|
||||
const safeMessages = Array.isArray(messages) ? messages : []
|
||||
const lastMessageId = safeMessages.at(-1)?.id
|
||||
|
||||
useEffect(() => {
|
||||
onNearBottomVisibleRef.current = onNearBottomVisible
|
||||
}, [onNearBottomVisible])
|
||||
|
||||
const isNearBottom = useCallback(
|
||||
(element: HTMLElement, threshold = 80) =>
|
||||
element.scrollHeight - element.scrollTop - element.clientHeight <= threshold,
|
||||
[]
|
||||
)
|
||||
|
||||
const scrollToBottom = useCallback(() => {
|
||||
const container = containerRef.current
|
||||
if (!container) {
|
||||
return
|
||||
}
|
||||
container.scrollTop = container.scrollHeight
|
||||
}, [])
|
||||
|
||||
const scheduleScrollToBottom = useCallback(
|
||||
(attempts = 4) => {
|
||||
if (frameRef.current !== null) {
|
||||
cancelAnimationFrame(frameRef.current)
|
||||
}
|
||||
|
||||
const run = (remaining: number, previousHeight = -1) => {
|
||||
frameRef.current = requestAnimationFrame(() => {
|
||||
const container = containerRef.current
|
||||
if (!container) {
|
||||
frameRef.current = null
|
||||
return
|
||||
}
|
||||
|
||||
const currentHeight = container.scrollHeight
|
||||
scrollToBottom()
|
||||
if (remaining > 1 && currentHeight !== previousHeight) {
|
||||
run(remaining - 1, currentHeight)
|
||||
return
|
||||
}
|
||||
frameRef.current = null
|
||||
})
|
||||
}
|
||||
|
||||
run(attempts)
|
||||
},
|
||||
[scrollToBottom]
|
||||
)
|
||||
|
||||
const handleImageSettled = useCallback(() => {
|
||||
if (shouldStickToBottomRef.current) {
|
||||
scheduleScrollToBottom()
|
||||
onNearBottomVisibleRef.current?.()
|
||||
}
|
||||
}, [scheduleScrollToBottom])
|
||||
|
||||
useImperativeHandle(ref, () => ({
|
||||
scrollToBottom,
|
||||
}))
|
||||
|
||||
useLayoutEffect(() => {
|
||||
shouldStickToBottomRef.current = true
|
||||
scheduleScrollToBottom()
|
||||
return () => {
|
||||
if (frameRef.current !== null) {
|
||||
cancelAnimationFrame(frameRef.current)
|
||||
frameRef.current = null
|
||||
}
|
||||
}
|
||||
}, [lastMessageId, scheduleScrollToBottom])
|
||||
|
||||
useEffect(() => {
|
||||
const container = containerRef.current
|
||||
const content = contentRef.current
|
||||
if (!container || !content) {
|
||||
return
|
||||
}
|
||||
|
||||
const handleScroll = () => {
|
||||
shouldStickToBottomRef.current = isNearBottom(container)
|
||||
if (shouldStickToBottomRef.current) {
|
||||
onNearBottomVisible?.()
|
||||
}
|
||||
}
|
||||
|
||||
const resizeObserver = new ResizeObserver(() => {
|
||||
if (shouldStickToBottomRef.current) {
|
||||
scheduleScrollToBottom()
|
||||
}
|
||||
})
|
||||
|
||||
handleScroll()
|
||||
container.addEventListener("scroll", handleScroll)
|
||||
resizeObserver.observe(container)
|
||||
resizeObserver.observe(content)
|
||||
scrollToBottom()
|
||||
|
||||
return () => {
|
||||
container.removeEventListener("scroll", handleScroll)
|
||||
resizeObserver.disconnect()
|
||||
}
|
||||
}, [isNearBottom, onNearBottomVisible, scheduleScrollToBottom, scrollToBottom])
|
||||
|
||||
const handleLoadOlder = useCallback(async () => {
|
||||
if (!onLoadOlder || loadingOlder || !hasMoreOlder) {
|
||||
return
|
||||
}
|
||||
const container = containerRef.current
|
||||
if (!container) {
|
||||
return
|
||||
}
|
||||
const anchor = {
|
||||
height: container.scrollHeight,
|
||||
top: container.scrollTop,
|
||||
}
|
||||
try {
|
||||
await onLoadOlder()
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
requestAnimationFrame(() => {
|
||||
requestAnimationFrame(() => {
|
||||
const current = containerRef.current
|
||||
if (!current) {
|
||||
return
|
||||
}
|
||||
current.scrollTop = current.scrollHeight - anchor.height + anchor.top
|
||||
})
|
||||
})
|
||||
}, [hasMoreOlder, loadingOlder, onLoadOlder])
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
className="cs-agent-scrollbar flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto px-4 py-4"
|
||||
>
|
||||
<div ref={contentRef} className="flex flex-col gap-4">
|
||||
{hasMoreOlder && onLoadOlder ? (
|
||||
<div className="flex justify-center py-1">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={loadingOlder}
|
||||
onClick={() => void handleLoadOlder()}
|
||||
className="h-7 rounded-full bg-background/90 text-xs text-muted-foreground shadow-sm hover:bg-background hover:text-sky-700 dark:hover:text-sky-400"
|
||||
>
|
||||
{loadingOlder ? t("supportChat.loadingOlder") : t("supportChat.loadOlder")}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{safeMessages.length === 0 ? (
|
||||
<div className="flex min-h-32 items-center justify-center px-3 py-6 text-center text-sm leading-6 text-muted-foreground">
|
||||
{t("supportChat.emptyPrompt")}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{safeMessages.map((message, index) => {
|
||||
const previousMessage = index > 0 ? safeMessages[index - 1] : null
|
||||
const showTimeline =
|
||||
index === 0 ||
|
||||
getDayKey(previousMessage?.sentAt) !== getDayKey(message.sentAt)
|
||||
|
||||
return (
|
||||
<MessageItem
|
||||
key={message.id}
|
||||
message={message}
|
||||
showTimeline={showTimeline}
|
||||
onImageSettled={handleImageSettled}
|
||||
timelineLabel={getTimelineLabel(message.sentAt, t)}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
)
|
||||
|
||||
type MessageItemProps = {
|
||||
message: ImMessage
|
||||
showTimeline: boolean
|
||||
onImageSettled: () => void
|
||||
timelineLabel: string
|
||||
}
|
||||
|
||||
const MessageItem = memo(
|
||||
function MessageItem({ message, showTimeline, onImageSettled, timelineLabel }: MessageItemProps) {
|
||||
const t = useI18n()
|
||||
const { open } = useImageLightbox()
|
||||
const isCustomer = message.senderType === "customer"
|
||||
const senderName = isCustomer ? t("supportChat.customerSelf") : message.senderName?.trim() || t("supportChat.agentLabel")
|
||||
const avatarSrc =
|
||||
!isCustomer && message.senderAvatar?.trim() ? message.senderAvatar.trim() : undefined
|
||||
const htmlContent = renderIMMessageHTML(message)
|
||||
const fallbackName = senderName.slice(0, 1).toUpperCase()
|
||||
|
||||
return (
|
||||
<div>
|
||||
{showTimeline ? (
|
||||
<div className="mb-3 flex items-center justify-center">
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="border-border bg-background/85 text-[11px] font-medium text-muted-foreground shadow-sm"
|
||||
>
|
||||
{timelineLabel}
|
||||
</Badge>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className={cn("flex gap-2.5", isCustomer ? "justify-end" : "justify-start")}>
|
||||
{!isCustomer ? (
|
||||
<Avatar className="mt-5">
|
||||
{avatarSrc ? <AvatarImage src={avatarSrc} alt="" /> : null}
|
||||
<AvatarFallback className="bg-muted text-muted-foreground">
|
||||
{fallbackName || t("supportChat.customerFallback")}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
) : null}
|
||||
|
||||
<div
|
||||
className={cn(
|
||||
"flex max-w-[86%] flex-col gap-1.5",
|
||||
isCustomer ? "items-end" : "items-start"
|
||||
)}
|
||||
>
|
||||
<div className="flex flex-wrap items-center gap-x-2 gap-y-1 px-1 text-[11px] text-muted-foreground">
|
||||
<span className="font-medium">{senderName}</span>
|
||||
<span>{formatDateTime(message.sentAt)}</span>
|
||||
{isCustomer ? (
|
||||
<span>{message.agentRead ? t("supportChat.agentRead") : t("supportChat.agentUnread")}</span>
|
||||
) : null}
|
||||
</div>
|
||||
<div
|
||||
className={cn(
|
||||
"rounded-lg px-3 py-2 text-sm leading-normal shadow-[0_10px_22px_rgba(15,23,42,0.06)]",
|
||||
isCustomer
|
||||
? "bg-[#a9ea7a] text-[#161616] dark:bg-emerald-500 dark:text-emerald-950"
|
||||
: "border border-border bg-card text-card-foreground dark:bg-background"
|
||||
)}
|
||||
>
|
||||
<ImMessageHTML
|
||||
html={htmlContent}
|
||||
className={cn(
|
||||
isCustomer
|
||||
? "[&_p]:text-[#161616] dark:[&_p]:text-emerald-950 [&_a]:text-[#161616] dark:[&_a]:text-emerald-950 [&_a]:underline [&_img]:cursor-zoom-in"
|
||||
: "[&_a]:text-card-foreground [&_a]:underline [&_img]:cursor-zoom-in"
|
||||
)}
|
||||
onImageSettled={onImageSettled}
|
||||
onImageClick={open}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
(prevProps, nextProps) =>
|
||||
isSameMessageItemRender(prevProps.message, nextProps.message) &&
|
||||
prevProps.showTimeline === nextProps.showTimeline &&
|
||||
prevProps.timelineLabel === nextProps.timelineLabel &&
|
||||
prevProps.onImageSettled === nextProps.onImageSettled
|
||||
)
|
||||
|
||||
function isSameMessageItemRender(prev: ImMessage, next: ImMessage) {
|
||||
return (
|
||||
prev.id === next.id &&
|
||||
prev.senderType === next.senderType &&
|
||||
prev.senderName === next.senderName &&
|
||||
prev.senderAvatar === next.senderAvatar &&
|
||||
prev.messageType === next.messageType &&
|
||||
prev.content === next.content &&
|
||||
prev.payload === next.payload &&
|
||||
prev.sentAt === next.sentAt &&
|
||||
prev.agentRead === next.agentRead
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,466 @@
|
||||
"use client"
|
||||
|
||||
import { SignJWT } from "jose"
|
||||
import { CheckIcon, CopyIcon } from "lucide-react"
|
||||
import { useEffect, useMemo, useState } from "react"
|
||||
|
||||
import type { CSAgentConfig } from "@/lib/sdk/config-types"
|
||||
import { useI18n } from "@/i18n/provider"
|
||||
|
||||
const STORAGE_KEY = "cs-agent-web-widget-test-config"
|
||||
const DEFAULT_JWT_TTL_MINUTES = "30"
|
||||
const INITIAL_CONFIG: CSAgentConfig = {
|
||||
channelId: "",
|
||||
baseUrl: "",
|
||||
apiBaseUrl: "",
|
||||
}
|
||||
|
||||
type AuthMode = "guest" | "jwt"
|
||||
|
||||
type WidgetDemoConfig = CSAgentConfig & {
|
||||
authMode?: AuthMode
|
||||
jwtSecret?: string
|
||||
jwtUserId?: string
|
||||
jwtName?: string
|
||||
jwtTtlMinutes?: string
|
||||
}
|
||||
|
||||
function getDefaultConfig(defaultName: string): WidgetDemoConfig {
|
||||
if (typeof window === "undefined") {
|
||||
return INITIAL_CONFIG
|
||||
}
|
||||
|
||||
const savedText = window.localStorage.getItem(STORAGE_KEY)
|
||||
const savedConfig = savedText
|
||||
? (JSON.parse(savedText) as Partial<WidgetDemoConfig>)
|
||||
: {}
|
||||
const query = new URLSearchParams(window.location.search)
|
||||
|
||||
return {
|
||||
channelId: query.get("channelId") ?? savedConfig.channelId ?? "",
|
||||
baseUrl: "",
|
||||
apiBaseUrl: "",
|
||||
authMode: (query.get("authMode") as AuthMode | null) ?? savedConfig.authMode ?? "guest",
|
||||
jwtSecret: savedConfig.jwtSecret ?? "",
|
||||
jwtUserId: query.get("userId") ?? savedConfig.jwtUserId ?? "demo-user-001",
|
||||
jwtName: query.get("name") ?? savedConfig.jwtName ?? defaultName,
|
||||
jwtTtlMinutes: savedConfig.jwtTtlMinutes ?? DEFAULT_JWT_TTL_MINUTES,
|
||||
}
|
||||
}
|
||||
|
||||
function removeMountedWidget() {
|
||||
if (typeof window === "undefined") {
|
||||
return
|
||||
}
|
||||
|
||||
window.CSAgentWidget?.destroy()
|
||||
document
|
||||
.querySelectorAll(
|
||||
'[data-cs-agent-widget="launcher"], [data-cs-agent-widget="frame"], [data-cs-agent-widget="script"]'
|
||||
)
|
||||
.forEach((node) => node.remove())
|
||||
|
||||
delete window.CSAgentConfig
|
||||
delete window.__CS_AGENT_WIDGET_CONFIG__
|
||||
delete window.__CS_AGENT_WIDGET_STATE__
|
||||
delete window.CSAgentWidget
|
||||
}
|
||||
|
||||
function injectWidget(config: CSAgentConfig) {
|
||||
removeMountedWidget()
|
||||
window.CSAgentConfig = config
|
||||
|
||||
const script = document.createElement("script")
|
||||
script.async = true
|
||||
script.src = `${window.location.origin}/sdk/cs-ai-agent-sdk.min.js`
|
||||
script.dataset.csAgentWidget = "script"
|
||||
document.body.appendChild(script)
|
||||
}
|
||||
|
||||
function buildWidgetConfig(config: WidgetDemoConfig): CSAgentConfig {
|
||||
const nextConfig: CSAgentConfig = {
|
||||
channelId: config.channelId.trim(),
|
||||
baseUrl: "",
|
||||
apiBaseUrl: "",
|
||||
}
|
||||
if (config.authMode === "jwt") {
|
||||
nextConfig.getUserToken = undefined
|
||||
}
|
||||
return nextConfig
|
||||
}
|
||||
|
||||
async function signUserToken(config: WidgetDemoConfig, t: (key: string) => string) {
|
||||
const userId = (config.jwtUserId || "").trim()
|
||||
const name = (config.jwtName || "").trim()
|
||||
const secret = (config.jwtSecret || "").trim()
|
||||
const ttl = Number(config.jwtTtlMinutes || DEFAULT_JWT_TTL_MINUTES)
|
||||
|
||||
if (!userId) {
|
||||
throw new Error(t("widgetDemo.missingUserId"))
|
||||
}
|
||||
if (!name) {
|
||||
throw new Error(t("widgetDemo.missingName"))
|
||||
}
|
||||
if (!secret) {
|
||||
throw new Error(t("widgetDemo.missingSecret"))
|
||||
}
|
||||
if (!Number.isFinite(ttl) || ttl <= 0) {
|
||||
throw new Error(t("widgetDemo.invalidTtl"))
|
||||
}
|
||||
|
||||
return new SignJWT({ userId, name })
|
||||
.setProtectedHeader({ alg: "HS256", typ: "JWT" })
|
||||
.setIssuedAt()
|
||||
.setExpirationTime(`${ttl}m`)
|
||||
.sign(new TextEncoder().encode(secret))
|
||||
}
|
||||
|
||||
export function SupportWidgetDemo() {
|
||||
const t = useI18n()
|
||||
const [config, setConfig] = useState<WidgetDemoConfig>({
|
||||
...INITIAL_CONFIG,
|
||||
authMode: "guest",
|
||||
jwtSecret: "",
|
||||
jwtUserId: "demo-user-001",
|
||||
jwtName: t("widgetDemo.defaultName"),
|
||||
jwtTtlMinutes: DEFAULT_JWT_TTL_MINUTES,
|
||||
})
|
||||
const [status, setStatus] = useState(t("widgetDemo.missingChannel"))
|
||||
const [origin, setOrigin] = useState("")
|
||||
const [generatedToken, setGeneratedToken] = useState("")
|
||||
const [latestDirectChatUrl, setLatestDirectChatUrl] = useState("")
|
||||
const [copied, setCopied] = useState(false)
|
||||
const [snippetCopied, setSnippetCopied] = useState(false)
|
||||
|
||||
async function mountWidget(configToMount: WidgetDemoConfig) {
|
||||
const cleanConfig = {
|
||||
...configToMount,
|
||||
channelId: configToMount.channelId.trim(),
|
||||
baseUrl: "",
|
||||
apiBaseUrl: "",
|
||||
getUserToken: undefined,
|
||||
}
|
||||
const nextConfig = buildWidgetConfig(cleanConfig)
|
||||
if (cleanConfig.authMode === "jwt") {
|
||||
nextConfig.getUserToken = () => signUserToken(cleanConfig, t)
|
||||
}
|
||||
setConfig(cleanConfig)
|
||||
setGeneratedToken("")
|
||||
setLatestDirectChatUrl("")
|
||||
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(cleanConfig))
|
||||
|
||||
if (!nextConfig.channelId) {
|
||||
removeMountedWidget()
|
||||
setStatus(t("widgetDemo.missingChannel"))
|
||||
return
|
||||
}
|
||||
|
||||
injectWidget(nextConfig)
|
||||
setStatus(
|
||||
cleanConfig.authMode === "jwt"
|
||||
? t("widgetDemo.mountedJwt")
|
||||
: t("widgetDemo.mountedGuest")
|
||||
)
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const timer = window.setTimeout(() => {
|
||||
const initialConfig = getDefaultConfig(t("widgetDemo.defaultName"))
|
||||
setOrigin(window.location.origin)
|
||||
setConfig(initialConfig)
|
||||
setStatus(initialConfig.channelId ? t("widgetDemo.mounted") : t("widgetDemo.missingChannel"))
|
||||
|
||||
if (initialConfig.channelId) {
|
||||
void mountWidget(initialConfig).catch((error) => {
|
||||
removeMountedWidget()
|
||||
setGeneratedToken("")
|
||||
setStatus(error instanceof Error ? error.message : t("widgetDemo.mountFailed"))
|
||||
})
|
||||
}
|
||||
}, 0)
|
||||
|
||||
return () => {
|
||||
window.clearTimeout(timer)
|
||||
removeMountedWidget()
|
||||
}
|
||||
}, [t])
|
||||
|
||||
const snippet = useMemo(() => {
|
||||
const scriptSrc = origin
|
||||
? `${origin}/sdk/cs-ai-agent-sdk.min.js`
|
||||
: "/sdk/cs-ai-agent-sdk.min.js"
|
||||
|
||||
const configLines = [` channelId: "${config.channelId || ""}"`]
|
||||
if (config.authMode === "jwt") {
|
||||
configLines.push(` async getUserToken() {
|
||||
const res = await fetch("/api/support/user-token", { credentials: "include" });
|
||||
const data = await res.json();
|
||||
return data.userToken;
|
||||
}`)
|
||||
}
|
||||
|
||||
return `<script>
|
||||
window.CSAgentConfig = {
|
||||
${configLines.join(",\n")}
|
||||
};
|
||||
</script>
|
||||
<script async src="${scriptSrc}"></script>`
|
||||
}, [config.authMode, config.channelId, origin])
|
||||
|
||||
function updateField<K extends keyof WidgetDemoConfig>(
|
||||
key: K,
|
||||
value: WidgetDemoConfig[K]
|
||||
) {
|
||||
setConfig((current) => ({ ...current, [key]: value }))
|
||||
}
|
||||
|
||||
async function handleMount() {
|
||||
try {
|
||||
await mountWidget(config)
|
||||
} catch (error) {
|
||||
removeMountedWidget()
|
||||
setGeneratedToken("")
|
||||
setStatus(error instanceof Error ? error.message : t("widgetDemo.mountFailed"))
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCopyDirectUrl() {
|
||||
if (!window.CSAgentWidget || typeof navigator === "undefined") {
|
||||
return
|
||||
}
|
||||
try {
|
||||
const url = await window.CSAgentWidget.getChatUrl()
|
||||
setLatestDirectChatUrl(url)
|
||||
if (config.authMode === "jwt") {
|
||||
setGeneratedToken(new URL(url).searchParams.get("userToken") || "")
|
||||
}
|
||||
await navigator.clipboard.writeText(url)
|
||||
setCopied(true)
|
||||
window.setTimeout(() => setCopied(false), 1600)
|
||||
} catch (error) {
|
||||
setStatus(error instanceof Error ? error.message : t("widgetDemo.linkFailed"))
|
||||
}
|
||||
}
|
||||
|
||||
async function handleOpenDirectChat() {
|
||||
if (!window.CSAgentWidget) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
const url = await window.CSAgentWidget.getChatUrl()
|
||||
setLatestDirectChatUrl(url)
|
||||
if (config.authMode === "jwt") {
|
||||
setGeneratedToken(new URL(url).searchParams.get("userToken") || "")
|
||||
}
|
||||
window.open(url, "_blank", "noopener,noreferrer")
|
||||
} catch (error) {
|
||||
setStatus(error instanceof Error ? error.message : t("widgetDemo.linkFailed"))
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCopySnippet() {
|
||||
if (typeof navigator === "undefined") {
|
||||
return
|
||||
}
|
||||
await navigator.clipboard.writeText(snippet)
|
||||
setSnippetCopied(true)
|
||||
window.setTimeout(() => setSnippetCopied(false), 1600)
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="min-h-svh bg-slate-50 px-6 py-8 text-slate-950">
|
||||
<div className="mx-auto grid max-w-6xl gap-6 lg:grid-cols-[360px_minmax(0,1fr)]">
|
||||
<section className="rounded-lg border border-slate-200 bg-white p-5 shadow-sm">
|
||||
<div className="text-base font-semibold">{t("widgetDemo.title")}</div>
|
||||
<div className="mt-1 text-sm text-slate-500">{status}</div>
|
||||
|
||||
<div className="mt-5 grid gap-3">
|
||||
<TextField
|
||||
label="channelId"
|
||||
value={config.channelId}
|
||||
onChange={(value) => updateField("channelId", value)}
|
||||
/>
|
||||
<SegmentedControl
|
||||
label={t("widgetDemo.authMode")}
|
||||
value={config.authMode || "guest"}
|
||||
onChange={(value) => updateField("authMode", value)}
|
||||
options={[
|
||||
{ label: t("widgetDemo.guest"), value: "guest" },
|
||||
{ label: t("widgetDemo.jwtUser"), value: "jwt" },
|
||||
]}
|
||||
/>
|
||||
{config.authMode === "jwt" ? (
|
||||
<div className="grid gap-3 rounded-md border border-slate-200 p-3">
|
||||
<TextField
|
||||
label="userId"
|
||||
value={config.jwtUserId}
|
||||
onChange={(value) => updateField("jwtUserId", value)}
|
||||
/>
|
||||
<TextField
|
||||
label="name"
|
||||
value={config.jwtName}
|
||||
onChange={(value) => updateField("jwtName", value)}
|
||||
/>
|
||||
<TextField
|
||||
label="JWT Secret"
|
||||
value={config.jwtSecret}
|
||||
onChange={(value) => updateField("jwtSecret", value)}
|
||||
type="password"
|
||||
/>
|
||||
<TextField
|
||||
label={t("widgetDemo.ttlMinutes")}
|
||||
value={config.jwtTtlMinutes}
|
||||
onChange={(value) => updateField("jwtTtlMinutes", value)}
|
||||
type="number"
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="mt-5 flex gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void handleMount()}
|
||||
className="rounded-md bg-slate-950 px-4 py-2 text-sm font-medium text-white"
|
||||
>
|
||||
{t("widgetDemo.mount")}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
removeMountedWidget()
|
||||
setStatus(t("widgetDemo.unmounted"))
|
||||
}}
|
||||
className="rounded-md border border-slate-200 bg-white px-4 py-2 text-sm font-medium"
|
||||
>
|
||||
{t("widgetDemo.unmount")}
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="rounded-lg border border-slate-200 bg-white p-5 shadow-sm">
|
||||
<div className="text-base font-semibold">{t("widgetDemo.snippetTitle")}</div>
|
||||
{config.authMode === "jwt" ? (
|
||||
<div className="mt-2 rounded-md bg-amber-50 px-3 py-2 text-sm text-amber-800">
|
||||
{t("widgetDemo.jwtNotice")}
|
||||
</div>
|
||||
) : null}
|
||||
<div className="relative mt-4">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void handleCopySnippet()}
|
||||
className="absolute right-2 top-2 inline-flex size-8 items-center justify-center rounded-md border border-white/10 bg-white/10 text-slate-200 transition hover:bg-white/20 hover:text-white"
|
||||
aria-label={snippetCopied ? t("widgetDemo.copiedSnippet") : t("widgetDemo.copySnippet")}
|
||||
title={snippetCopied ? t("widgetDemo.copied") : t("widgetDemo.copyCode")}
|
||||
>
|
||||
{snippetCopied ? (
|
||||
<CheckIcon className="size-4" />
|
||||
) : (
|
||||
<CopyIcon className="size-4" />
|
||||
)}
|
||||
</button>
|
||||
<pre className="overflow-x-auto rounded-md bg-slate-950 p-4 pr-12 text-xs leading-5 text-slate-100">
|
||||
<code>{snippet}</code>
|
||||
</pre>
|
||||
</div>
|
||||
<div className="mt-5">
|
||||
<div className="text-sm font-medium text-slate-700">{t("widgetDemo.directChat")}</div>
|
||||
<div className="mt-2 flex flex-col gap-2 sm:flex-row">
|
||||
<input
|
||||
readOnly
|
||||
value={latestDirectChatUrl || t("widgetDemo.directChatPlaceholder")}
|
||||
className="h-9 min-w-0 flex-1 rounded-md border border-slate-200 px-3 font-mono text-xs outline-none"
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
type="button"
|
||||
disabled={!config.channelId}
|
||||
onClick={() => void handleCopyDirectUrl()}
|
||||
className="rounded-md border border-slate-200 bg-white px-3 py-2 text-sm font-medium disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
{copied ? t("widgetDemo.copied") : t("widgetDemo.copy")}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={!config.channelId}
|
||||
onClick={() => void handleOpenDirectChat()}
|
||||
className="rounded-md bg-slate-950 px-3 py-2 text-sm font-medium text-white disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
{t("widgetDemo.openNewWindow")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{generatedToken ? (
|
||||
<div className="mt-4">
|
||||
<div className="text-sm font-medium text-slate-700">{t("widgetDemo.currentToken")}</div>
|
||||
<textarea
|
||||
readOnly
|
||||
value={generatedToken}
|
||||
className="mt-2 h-28 w-full resize-none rounded-md border border-slate-200 p-3 font-mono text-xs outline-none"
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
</section>
|
||||
</div>
|
||||
</main>
|
||||
)
|
||||
}
|
||||
|
||||
function TextField({
|
||||
label,
|
||||
value,
|
||||
onChange,
|
||||
type = "text",
|
||||
}: {
|
||||
label: string
|
||||
value?: string
|
||||
onChange: (value: string) => void
|
||||
type?: string
|
||||
}) {
|
||||
return (
|
||||
<label className="grid gap-1.5 text-sm">
|
||||
<span className="font-medium text-slate-700">{label}</span>
|
||||
<input
|
||||
type={type}
|
||||
value={value || ""}
|
||||
onChange={(event) => onChange(event.target.value)}
|
||||
className="h-9 rounded-md border border-slate-200 px-3 text-sm outline-none focus:border-slate-400"
|
||||
/>
|
||||
</label>
|
||||
)
|
||||
}
|
||||
|
||||
function SegmentedControl<T extends string>({
|
||||
label,
|
||||
value,
|
||||
options,
|
||||
onChange,
|
||||
}: {
|
||||
label: string
|
||||
value: T
|
||||
options: Array<{ label: string; value: T }>
|
||||
onChange: (value: T) => void
|
||||
}) {
|
||||
return (
|
||||
<div className="grid gap-1.5 text-sm">
|
||||
<div className="font-medium text-slate-700">{label}</div>
|
||||
<div className="grid grid-cols-2 rounded-md border border-slate-200 bg-slate-100 p-1">
|
||||
{options.map((option) => (
|
||||
<button
|
||||
key={option.value}
|
||||
type="button"
|
||||
onClick={() => onChange(option.value)}
|
||||
className={
|
||||
option.value === value
|
||||
? "rounded bg-white px-3 py-1.5 text-sm font-medium shadow-sm"
|
||||
: "rounded px-3 py-1.5 text-sm text-slate-600"
|
||||
}
|
||||
>
|
||||
{option.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user