Init
This commit is contained in:
@@ -0,0 +1,29 @@
|
||||
import { requestJson } from "@/lib/services/http";
|
||||
import type { JsonResult, WidgetConversation } from "@/lib/services/types";
|
||||
|
||||
/** 身份由请求头 X-External-Source / X-External-Id(及可选 X-External-Name)提供,与 GetExternalInfo 一致 */
|
||||
export async function createOrMatchConversation() {
|
||||
const result = await requestJson<JsonResult<WidgetConversation>>(
|
||||
"/api/open/im/conversation/create_or_match",
|
||||
{
|
||||
method: "POST",
|
||||
},
|
||||
);
|
||||
if (!result.data) {
|
||||
throw new Error(result.message || "conversation init failed");
|
||||
}
|
||||
return result.data;
|
||||
}
|
||||
|
||||
export async function closeConversation(conversationId: number) {
|
||||
const result = await requestJson<JsonResult<null>>(
|
||||
"/api/open/im/conversation/close",
|
||||
{
|
||||
method: "POST",
|
||||
body: JSON.stringify({ conversationId }),
|
||||
},
|
||||
);
|
||||
if (result.success === false) {
|
||||
throw new Error(result.message || "conversation close failed");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { readWidgetConfig } from "@/lib/widget/config";
|
||||
import { getOrCreateExternalId } from "@/lib/widget/visitor";
|
||||
|
||||
export async function requestJson<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
const config = readWidgetConfig();
|
||||
const baseUrl = (config.apiBaseUrl || config.baseUrl).replace(/\/$/, "");
|
||||
const visitorId = getOrCreateExternalId();
|
||||
const externalSource = (config.externalSource ?? "web_chat").trim() || "web_chat";
|
||||
const headers = new Headers(init?.headers ?? {});
|
||||
if (
|
||||
!headers.has("Content-Type") &&
|
||||
init?.body &&
|
||||
!(typeof FormData !== "undefined" && init.body instanceof FormData)
|
||||
) {
|
||||
headers.set("Content-Type", "application/json");
|
||||
}
|
||||
headers.set("X-External-Source", externalSource);
|
||||
headers.set("X-External-Id", visitorId);
|
||||
const externalName = (config.subject ?? "").trim();
|
||||
if (externalName) {
|
||||
headers.set("X-External-Name", encodeURIComponent(externalName));
|
||||
}
|
||||
headers.set("X-Channel-Id", config.channelId);
|
||||
const response = await fetch(`${baseUrl}${path}`, {
|
||||
...init,
|
||||
headers,
|
||||
cache: "no-store",
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`Request failed: ${response.status}`);
|
||||
}
|
||||
return (await response.json()) as T;
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
export type WidgetMessageAssetPayload = {
|
||||
assetId: string;
|
||||
filename?: string;
|
||||
fileSize?: number;
|
||||
mimeType?: string;
|
||||
url?: string;
|
||||
};
|
||||
|
||||
export function parseMessageAssetPayload(
|
||||
payload?: string,
|
||||
): WidgetMessageAssetPayload | null {
|
||||
if (!payload?.trim()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const parsed = JSON.parse(payload) as WidgetMessageAssetPayload;
|
||||
if (!parsed?.assetId?.trim()) {
|
||||
return null;
|
||||
}
|
||||
return parsed;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function renderMessageHTML(message: {
|
||||
messageType: string;
|
||||
content: string;
|
||||
payload?: string;
|
||||
}) {
|
||||
if (message.messageType === "html") {
|
||||
return message.content;
|
||||
}
|
||||
|
||||
const asset = parseMessageAssetPayload(message.payload);
|
||||
if (message.messageType === "image") {
|
||||
if (asset?.url) {
|
||||
return `<p><img src="${escapeHTMLAttr(asset.url)}" alt="${escapeHTMLAttr(
|
||||
asset.filename || "image",
|
||||
)}"></p>`;
|
||||
}
|
||||
return "<p>[图片]</p>";
|
||||
}
|
||||
|
||||
if (message.messageType === "attachment") {
|
||||
if (asset?.url) {
|
||||
const title = escapeHTML(asset.filename || message.content || "附件");
|
||||
const meta = formatFileSize(asset.fileSize ?? 0);
|
||||
const metaHTML = meta
|
||||
? `<div class="im-attachment-meta">${escapeHTML(meta)}</div>`
|
||||
: "";
|
||||
return `<div class="im-attachment"><a href="${escapeHTMLAttr(
|
||||
asset.url,
|
||||
)}" target="_blank" rel="noreferrer" download="${escapeHTMLAttr(
|
||||
asset.filename || "",
|
||||
)}" class="im-attachment-link"><span class="im-attachment-icon" aria-hidden="true">${getAttachmentIconSVG()}</span><span class="im-attachment-content"><span class="im-attachment-title">${title}</span>${metaHTML}</span></a></div>`;
|
||||
}
|
||||
return `<p>${escapeHTML(message.content || "[附件]")}</p>`;
|
||||
}
|
||||
|
||||
return `<p>${escapeHTML(message.content || "")}</p>`;
|
||||
}
|
||||
|
||||
export function summarizeMessage(message: {
|
||||
messageType: string;
|
||||
content: string;
|
||||
payload?: string;
|
||||
}) {
|
||||
if (message.messageType === "image") {
|
||||
return "[图片]";
|
||||
}
|
||||
if (message.messageType === "attachment") {
|
||||
const asset = parseMessageAssetPayload(message.payload);
|
||||
return asset?.filename?.trim() ? `[附件] ${asset.filename.trim()}` : "[附件]";
|
||||
}
|
||||
if (message.messageType === "html") {
|
||||
const text = extractTextFromHTML(message.content);
|
||||
if (text.trim()) {
|
||||
return text.substring(0, 100);
|
||||
}
|
||||
if (message.content.includes("<img")) {
|
||||
return "[图片]";
|
||||
}
|
||||
return "[消息]";
|
||||
}
|
||||
return message.content?.substring(0, 100) || "[消息]";
|
||||
}
|
||||
|
||||
function formatFileSize(size: number) {
|
||||
if (!Number.isFinite(size) || size <= 0) {
|
||||
return "";
|
||||
}
|
||||
const units = ["B", "KB", "MB", "GB"];
|
||||
let value = size;
|
||||
let index = 0;
|
||||
while (value >= 1024 && index < units.length - 1) {
|
||||
value /= 1024;
|
||||
index += 1;
|
||||
}
|
||||
const digits = value >= 10 || index === 0 ? 0 : 1;
|
||||
return `${value.toFixed(digits)} ${units[index]}`;
|
||||
}
|
||||
|
||||
function extractTextFromHTML(html: string): string {
|
||||
if (typeof document === "undefined") {
|
||||
return "";
|
||||
}
|
||||
const div = document.createElement("div");
|
||||
div.innerHTML = html;
|
||||
return div.textContent || div.innerText || "";
|
||||
}
|
||||
|
||||
function escapeHTML(value: string) {
|
||||
return value
|
||||
.replaceAll("&", "&")
|
||||
.replaceAll("<", "<")
|
||||
.replaceAll(">", ">")
|
||||
.replaceAll('"', """)
|
||||
.replaceAll("'", "'")
|
||||
.replaceAll("\n", "<br>");
|
||||
}
|
||||
|
||||
function escapeHTMLAttr(value: string) {
|
||||
return value
|
||||
.replaceAll("&", "&")
|
||||
.replaceAll('"', """)
|
||||
.replaceAll("<", "<")
|
||||
.replaceAll(">", ">");
|
||||
}
|
||||
|
||||
function getAttachmentIconSVG() {
|
||||
return `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><path d="M14 2v6h6"></path><path d="M9 15h6"></path><path d="M9 11h2"></path></svg>`;
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import { requestJson } from "@/lib/services/http";
|
||||
import type {
|
||||
CursorResult,
|
||||
JsonResult,
|
||||
WidgetAsset,
|
||||
WidgetMessage,
|
||||
} from "@/lib/services/types";
|
||||
import { generateUUID } from "@/lib/utils";
|
||||
|
||||
const DEFAULT_PAGE_LIMIT = 50;
|
||||
|
||||
function buildListQuery(
|
||||
conversationId: number,
|
||||
options?: { cursor?: number; limit?: number },
|
||||
) {
|
||||
const params = new URLSearchParams({
|
||||
conversationId: String(conversationId),
|
||||
});
|
||||
const cursor = options?.cursor;
|
||||
if (cursor !== undefined && cursor > 0) {
|
||||
params.set("cursor", String(cursor));
|
||||
}
|
||||
const limit = options?.limit ?? DEFAULT_PAGE_LIMIT;
|
||||
if (limit > 0) {
|
||||
params.set("limit", String(limit));
|
||||
}
|
||||
return params.toString();
|
||||
}
|
||||
|
||||
export async function fetchMessagesPage(
|
||||
conversationId: number,
|
||||
options?: { cursor?: number; limit?: number },
|
||||
): Promise<CursorResult<WidgetMessage>> {
|
||||
const qs = buildListQuery(conversationId, options);
|
||||
const result = await requestJson<
|
||||
JsonResult<CursorResult<WidgetMessage>>
|
||||
>(`/api/open/im/message/list?${qs}`);
|
||||
if (result.success === false) {
|
||||
throw new Error(result.message || "加载消息失败");
|
||||
}
|
||||
const data = result.data;
|
||||
return {
|
||||
results: data?.results ?? [],
|
||||
cursor: data?.cursor ?? "",
|
||||
hasMore: Boolean(data?.hasMore),
|
||||
};
|
||||
}
|
||||
|
||||
/** @deprecated 使用 fetchMessagesPage;保留别名供渐进迁移 */
|
||||
export async function fetchMessages(conversationId: number) {
|
||||
const page = await fetchMessagesPage(conversationId);
|
||||
return page.results;
|
||||
}
|
||||
|
||||
export async function sendMessageWithPayload(
|
||||
conversationId: number,
|
||||
payload: {
|
||||
messageType: string;
|
||||
content: string;
|
||||
payload?: string;
|
||||
clientMsgId?: string;
|
||||
},
|
||||
) {
|
||||
const result = await requestJson<JsonResult<WidgetMessage>>("/api/open/im/message/send", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
conversationId,
|
||||
clientMsgId: payload.clientMsgId || `client_${generateUUID()}`,
|
||||
messageType: payload.messageType,
|
||||
content: payload.content,
|
||||
payload: payload.payload || "",
|
||||
}),
|
||||
});
|
||||
if (!result.data) {
|
||||
throw new Error(result.message || "send message failed");
|
||||
}
|
||||
return result.data;
|
||||
}
|
||||
|
||||
export async function sendMessage(conversationId: number, content: string) {
|
||||
return sendMessageWithPayload(conversationId, {
|
||||
messageType: "html",
|
||||
content,
|
||||
payload: "",
|
||||
});
|
||||
}
|
||||
|
||||
export async function markMessageRead(conversationId: number, messageId = 0) {
|
||||
await requestJson<JsonResult<void>>("/api/open/im/message/read", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ conversationId, messageId }),
|
||||
});
|
||||
}
|
||||
|
||||
export async function uploadImage(conversationId: number, file: File) {
|
||||
const formData = new FormData();
|
||||
formData.set("conversationId", String(conversationId));
|
||||
formData.set("file", file);
|
||||
const result = await requestJson<JsonResult<WidgetAsset>>(
|
||||
"/api/open/im/message/upload_image",
|
||||
{
|
||||
method: "POST",
|
||||
body: formData,
|
||||
},
|
||||
);
|
||||
if (!result.data) {
|
||||
throw new Error(result.message || "upload image failed");
|
||||
}
|
||||
return result.data;
|
||||
}
|
||||
|
||||
export async function uploadAttachment(conversationId: number, file: File) {
|
||||
const formData = new FormData();
|
||||
formData.set("conversationId", String(conversationId));
|
||||
formData.set("file", file);
|
||||
const result = await requestJson<JsonResult<WidgetAsset>>(
|
||||
"/api/open/im/message/upload_attachment",
|
||||
{
|
||||
method: "POST",
|
||||
body: formData,
|
||||
},
|
||||
);
|
||||
if (!result.data) {
|
||||
throw new Error(result.message || "upload attachment failed");
|
||||
}
|
||||
return result.data;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import type { WidgetMessage } from "./types";
|
||||
import { summarizeMessage } from "./message-asset";
|
||||
|
||||
export function getNotificationBody(message: WidgetMessage): string {
|
||||
return summarizeMessage(message);
|
||||
}
|
||||
|
||||
export function showNotification(title: string, body: string, onClick?: () => void) {
|
||||
if (typeof Notification === "undefined") {
|
||||
return;
|
||||
}
|
||||
|
||||
if (Notification.permission === "granted") {
|
||||
const notification = new Notification(title, {
|
||||
body,
|
||||
icon: "/favicon.ico",
|
||||
badge: "/favicon.ico",
|
||||
});
|
||||
|
||||
if (onClick) {
|
||||
notification.onclick = () => {
|
||||
onClick();
|
||||
notification.close();
|
||||
};
|
||||
}
|
||||
|
||||
setTimeout(() => {
|
||||
notification.close();
|
||||
}, 5000);
|
||||
} else if (Notification.permission === "default") {
|
||||
Notification.requestPermission().then((permission) => {
|
||||
if (permission === "granted") {
|
||||
showNotification(title, body, onClick);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { readWidgetConfig } from "@/lib/widget/config";
|
||||
import { getOrCreateExternalId } from "@/lib/widget/visitor";
|
||||
|
||||
export type RealtimeEnvelope = {
|
||||
type: string;
|
||||
topic?: string;
|
||||
data?: {
|
||||
conversationId?: number;
|
||||
messageId?: number;
|
||||
};
|
||||
payload?: {
|
||||
conversationId?: number;
|
||||
messageId?: number;
|
||||
};
|
||||
};
|
||||
|
||||
export function createRealtimeConnection(onEvent: (event: RealtimeEnvelope) => void) {
|
||||
const config = readWidgetConfig();
|
||||
const baseUrl = (config.apiBaseUrl || config.baseUrl)
|
||||
.replace(/^http/, "ws")
|
||||
.replace(/\/$/, "");
|
||||
const externalId = encodeURIComponent(getOrCreateExternalId());
|
||||
const externalSource = encodeURIComponent(
|
||||
(config.externalSource ?? "web_chat").trim() || "web_chat",
|
||||
);
|
||||
const externalName = (config.subject ?? "").trim();
|
||||
const nameQuery =
|
||||
externalName !== ""
|
||||
? `&externalName=${encodeURIComponent(externalName)}`
|
||||
: "";
|
||||
const socket = new WebSocket(
|
||||
`${baseUrl}/api/open/im/ws?externalId=${externalId}&externalSource=${externalSource}&channelId=${encodeURIComponent(config.channelId)}${nameQuery}`,
|
||||
);
|
||||
socket.addEventListener("message", (event) => {
|
||||
try {
|
||||
onEvent(JSON.parse(event.data) as RealtimeEnvelope);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
});
|
||||
return socket;
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
export type PageResult<T> = {
|
||||
results: T[];
|
||||
page?: {
|
||||
page: number;
|
||||
limit: number;
|
||||
total: number;
|
||||
};
|
||||
};
|
||||
|
||||
export type CursorResult<T> = {
|
||||
results: T[];
|
||||
cursor: string;
|
||||
hasMore: boolean;
|
||||
};
|
||||
|
||||
export type JsonResult<T> = {
|
||||
success?: boolean;
|
||||
errorCode?: number;
|
||||
code?: number;
|
||||
message?: string;
|
||||
data?: T;
|
||||
};
|
||||
|
||||
export type WidgetConversation = {
|
||||
id: number;
|
||||
subject?: string;
|
||||
status?: number;
|
||||
serviceMode?: number;
|
||||
currentAssigneeId?: number;
|
||||
lastMessageAt?: string;
|
||||
lastMessageSummary?: string;
|
||||
customerUnreadCount?: number;
|
||||
agentUnreadCount?: number;
|
||||
customerLastReadMessageId?: number;
|
||||
customerLastReadSeqNo?: number;
|
||||
customerLastReadAt?: string;
|
||||
agentLastReadMessageId?: number;
|
||||
agentLastReadSeqNo?: number;
|
||||
agentLastReadAt?: string;
|
||||
};
|
||||
|
||||
export type WidgetMessage = {
|
||||
id: number;
|
||||
conversationId: number;
|
||||
senderType: string;
|
||||
senderName?: string;
|
||||
senderAvatar?: string;
|
||||
messageType: string;
|
||||
content: string;
|
||||
payload?: string;
|
||||
seqNo?: number;
|
||||
sentAt?: string;
|
||||
customerRead?: boolean;
|
||||
customerReadAt?: string;
|
||||
agentRead?: boolean;
|
||||
agentReadAt?: string;
|
||||
};
|
||||
|
||||
export type WidgetAsset = {
|
||||
id: number;
|
||||
assetId: string;
|
||||
provider: string;
|
||||
filename: string;
|
||||
fileSize: number;
|
||||
mimeType: string;
|
||||
status: number;
|
||||
url: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
createUserId: number;
|
||||
createUserName: string;
|
||||
updateUserId: number;
|
||||
updateUserName: string;
|
||||
};
|
||||
|
||||
export type WidgetConfigResponse = {
|
||||
title?: string;
|
||||
subtitle?: string;
|
||||
welcomeText?: string;
|
||||
themeColor?: string;
|
||||
};
|
||||
@@ -0,0 +1,13 @@
|
||||
import { requestJson } from "@/lib/services/http";
|
||||
import type { JsonResult, WidgetConfigResponse } from "@/lib/services/types";
|
||||
import { readWidgetConfig } from "@/lib/widget/config";
|
||||
|
||||
export async function fetchWidgetConfig() {
|
||||
const config = readWidgetConfig();
|
||||
const result = await requestJson<JsonResult<WidgetConfigResponse>>(
|
||||
`/api/open/im/widget/config?channelId=${encodeURIComponent(config.channelId)}`,
|
||||
);
|
||||
return result.data ?? {};
|
||||
}
|
||||
|
||||
export { readWidgetConfig };
|
||||
@@ -0,0 +1,569 @@
|
||||
"use client";
|
||||
|
||||
import { create } from "zustand";
|
||||
|
||||
import { createOrMatchConversation } from "@/lib/services/conversation";
|
||||
import {
|
||||
fetchMessagesPage,
|
||||
markMessageRead,
|
||||
sendMessage,
|
||||
sendMessageWithPayload,
|
||||
uploadAttachment,
|
||||
uploadImage,
|
||||
} from "@/lib/services/message";
|
||||
import {
|
||||
getNotificationBody,
|
||||
showNotification,
|
||||
} from "@/lib/services/notification";
|
||||
import { summarizeMessage } from "@/lib/services/message-asset";
|
||||
import {
|
||||
createRealtimeConnection,
|
||||
type RealtimeEnvelope,
|
||||
} from "@/lib/services/realtime";
|
||||
import type {
|
||||
WidgetConfigResponse,
|
||||
WidgetConversation,
|
||||
WidgetMessage,
|
||||
} from "@/lib/services/types";
|
||||
import {
|
||||
fetchWidgetConfig,
|
||||
readWidgetConfig,
|
||||
} from "@/lib/services/widget-config";
|
||||
import { generateUUID } from "@/lib/utils";
|
||||
|
||||
type ChatStatus = "connecting" | "connected" | "disconnected";
|
||||
|
||||
const RECONNECT_BASE_DELAY = 2000;
|
||||
const RECONNECT_MAX_DELAY = 30000;
|
||||
|
||||
function mergeMessagesByIdAsc(
|
||||
a: WidgetMessage[],
|
||||
b: WidgetMessage[],
|
||||
): WidgetMessage[] {
|
||||
const byId = new Map<number, WidgetMessage>();
|
||||
for (const m of a) {
|
||||
byId.set(m.id, m);
|
||||
}
|
||||
for (const m of b) {
|
||||
byId.set(m.id, m);
|
||||
}
|
||||
return Array.from(byId.values()).sort((x, y) => x.id - y.id);
|
||||
}
|
||||
|
||||
function parseCursorId(cursor: string): number {
|
||||
const n = Number.parseInt(cursor, 10);
|
||||
return Number.isFinite(n) && n > 0 ? n : 0;
|
||||
}
|
||||
|
||||
function cursorFromLoadedMessages(messages: WidgetMessage[]): string {
|
||||
if (messages.length === 0) {
|
||||
return "";
|
||||
}
|
||||
return String(Math.min(...messages.map((m) => m.id)));
|
||||
}
|
||||
|
||||
function minWidgetMessageId(messages: WidgetMessage[]): number | null {
|
||||
if (messages.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return Math.min(...messages.map((m) => m.id));
|
||||
}
|
||||
|
||||
function hasMoreAfterLatestSyncMerge(args: {
|
||||
previousMessages: WidgetMessage[];
|
||||
previousHasMore: boolean;
|
||||
merged: WidgetMessage[];
|
||||
apiHasMore: boolean;
|
||||
}): boolean {
|
||||
const prevMin = minWidgetMessageId(args.previousMessages);
|
||||
const mergedMin = minWidgetMessageId(args.merged);
|
||||
|
||||
if (mergedMin === null) {
|
||||
return Boolean(args.apiHasMore);
|
||||
}
|
||||
|
||||
if (!args.previousHasMore && prevMin !== null && mergedMin >= prevMin) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return args.previousHasMore || Boolean(args.apiHasMore);
|
||||
}
|
||||
|
||||
export interface ChatStore {
|
||||
title: string;
|
||||
subtitle: string;
|
||||
welcomeText: string;
|
||||
themeColor: string;
|
||||
conversation: WidgetConversation | null;
|
||||
messages: WidgetMessage[];
|
||||
messagesCursor: string;
|
||||
messagesHasMore: boolean;
|
||||
messagesLoadingMore: boolean;
|
||||
status: ChatStatus;
|
||||
error: string;
|
||||
isOpen: boolean;
|
||||
isVisible: boolean;
|
||||
initialized: boolean;
|
||||
socket: WebSocket | null;
|
||||
readingMessageId: number;
|
||||
|
||||
setIsOpen: (isOpen: boolean) => void;
|
||||
setIsVisible: (isVisible: boolean) => void;
|
||||
bootstrap: () => void;
|
||||
handleSendMessage: (html: string) => Promise<void>;
|
||||
uploadMessageImage: (
|
||||
file: File,
|
||||
) => Promise<{ url: string; filename?: string } | null>;
|
||||
sendAttachment: (file: File) => Promise<void>;
|
||||
retry: () => void;
|
||||
disconnectSocket: () => void;
|
||||
refreshMessages: () => Promise<void>;
|
||||
syncLatestMessages: () => Promise<void>;
|
||||
loadOlderMessages: () => Promise<void>;
|
||||
markConversationRead: () => Promise<void>;
|
||||
}
|
||||
|
||||
let bootstrapToken = 0;
|
||||
|
||||
export const useChatStore = create<ChatStore>((set, get) => {
|
||||
let reconnectTimer: number | null = null;
|
||||
let pingTimer: number | null = null;
|
||||
let reconnectAttempt = 0;
|
||||
let shouldReconnect = false;
|
||||
|
||||
const clearRealtimeTimers = () => {
|
||||
if (reconnectTimer !== null) {
|
||||
window.clearTimeout(reconnectTimer);
|
||||
reconnectTimer = null;
|
||||
}
|
||||
if (pingTimer !== null) {
|
||||
window.clearInterval(pingTimer);
|
||||
pingTimer = null;
|
||||
}
|
||||
};
|
||||
|
||||
const scheduleReconnect = () => {
|
||||
if (!shouldReconnect || reconnectTimer !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const delay = Math.min(
|
||||
RECONNECT_BASE_DELAY * 2 ** reconnectAttempt,
|
||||
RECONNECT_MAX_DELAY,
|
||||
);
|
||||
set({ status: "connecting" });
|
||||
reconnectTimer = window.setTimeout(() => {
|
||||
reconnectTimer = null;
|
||||
reconnectAttempt += 1;
|
||||
if (!shouldReconnect || !get().isOpen) {
|
||||
return;
|
||||
}
|
||||
connectSocket();
|
||||
}, delay);
|
||||
};
|
||||
|
||||
const closeSocket = (options?: { reconnect?: boolean }) => {
|
||||
shouldReconnect = options?.reconnect ?? false;
|
||||
clearRealtimeTimers();
|
||||
if (!shouldReconnect) {
|
||||
reconnectAttempt = 0;
|
||||
}
|
||||
|
||||
const socket = get().socket;
|
||||
if (
|
||||
socket &&
|
||||
(socket.readyState === WebSocket.OPEN ||
|
||||
socket.readyState === WebSocket.CONNECTING)
|
||||
) {
|
||||
socket.close();
|
||||
}
|
||||
|
||||
set({ socket: null });
|
||||
};
|
||||
|
||||
const connectSocket = () => {
|
||||
const conversationId = get().conversation?.id;
|
||||
if (!conversationId) {
|
||||
return;
|
||||
}
|
||||
closeSocket({ reconnect: false });
|
||||
shouldReconnect = true;
|
||||
|
||||
const handleRealtimeEvent = (event: RealtimeEnvelope) => {
|
||||
const payload = event.data ?? event.payload;
|
||||
const needsRefresh =
|
||||
event.type === "message.created" ||
|
||||
event.type?.startsWith("conversation.");
|
||||
|
||||
if (needsRefresh && payload?.conversationId === conversationId) {
|
||||
void get()
|
||||
.syncLatestMessages()
|
||||
.then(() => {
|
||||
if (event.type === "message.created") {
|
||||
const state = get();
|
||||
const lastMessage = state.messages.at(-1);
|
||||
if (
|
||||
lastMessage &&
|
||||
lastMessage.senderType !== "customer" &&
|
||||
typeof document !== "undefined" &&
|
||||
document.visibilityState !== "visible"
|
||||
) {
|
||||
showNotification(
|
||||
"新消息",
|
||||
getNotificationBody(lastMessage),
|
||||
() => {
|
||||
state.setIsOpen(true);
|
||||
state.setIsVisible(true);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const socket = createRealtimeConnection(handleRealtimeEvent);
|
||||
set({ socket });
|
||||
|
||||
socket.addEventListener("open", () => {
|
||||
clearRealtimeTimers();
|
||||
reconnectAttempt = 0;
|
||||
pingTimer = window.setInterval(() => {
|
||||
if (socket.readyState === WebSocket.OPEN) {
|
||||
socket.send(JSON.stringify({ type: "ping" }));
|
||||
}
|
||||
}, 20000);
|
||||
if (get().isOpen && get().socket === socket) {
|
||||
set({ status: "connected" });
|
||||
}
|
||||
});
|
||||
|
||||
socket.addEventListener("error", () => {
|
||||
if (get().socket === socket) {
|
||||
scheduleReconnect();
|
||||
}
|
||||
});
|
||||
|
||||
socket.addEventListener("close", () => {
|
||||
if (pingTimer !== null) {
|
||||
window.clearInterval(pingTimer);
|
||||
pingTimer = null;
|
||||
}
|
||||
if (get().socket === socket) {
|
||||
set({ socket: null });
|
||||
}
|
||||
if (get().isOpen) {
|
||||
if (shouldReconnect) {
|
||||
scheduleReconnect();
|
||||
} else {
|
||||
set({ status: "disconnected" });
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
title: "在线客服",
|
||||
subtitle: "",
|
||||
welcomeText: "",
|
||||
themeColor: "#2563eb",
|
||||
conversation: null,
|
||||
messages: [],
|
||||
messagesCursor: "",
|
||||
messagesHasMore: false,
|
||||
messagesLoadingMore: false,
|
||||
status: "connecting",
|
||||
error: "",
|
||||
isOpen: typeof window !== "undefined" ? window.self === window.top : false,
|
||||
isVisible:
|
||||
typeof window !== "undefined" ? window.self === window.top : false,
|
||||
initialized: false,
|
||||
socket: null,
|
||||
readingMessageId: 0,
|
||||
|
||||
setIsOpen: (isOpen: boolean) => {
|
||||
set({ isOpen });
|
||||
},
|
||||
|
||||
setIsVisible: (isVisible: boolean) => {
|
||||
set({ isVisible });
|
||||
},
|
||||
|
||||
disconnectSocket: () => {
|
||||
closeSocket({ reconnect: false });
|
||||
},
|
||||
|
||||
refreshMessages: async () => {
|
||||
const conversationId = get().conversation?.id;
|
||||
if (!conversationId) return;
|
||||
|
||||
try {
|
||||
const page = await fetchMessagesPage(conversationId);
|
||||
const currentConversation = get().conversation;
|
||||
set({
|
||||
messages: page.results,
|
||||
messagesCursor: cursorFromLoadedMessages(page.results) || page.cursor,
|
||||
messagesHasMore: page.hasMore,
|
||||
conversation: currentConversation,
|
||||
});
|
||||
} catch (e) {
|
||||
console.error("Failed to refresh messages", e);
|
||||
}
|
||||
},
|
||||
|
||||
syncLatestMessages: async () => {
|
||||
const conversationId = get().conversation?.id;
|
||||
if (!conversationId) return;
|
||||
|
||||
try {
|
||||
const page = await fetchMessagesPage(conversationId);
|
||||
const batch = page.results;
|
||||
if (batch.length === 0) {
|
||||
return;
|
||||
}
|
||||
const firstId = batch[0]!.id;
|
||||
const currentConversation = get().conversation;
|
||||
set((state) => {
|
||||
const preserved = state.messages.filter((m) => m.id < firstId);
|
||||
const merged = mergeMessagesByIdAsc(preserved, batch);
|
||||
return {
|
||||
messages: merged,
|
||||
messagesCursor: cursorFromLoadedMessages(merged) || page.cursor,
|
||||
messagesHasMore: hasMoreAfterLatestSyncMerge({
|
||||
previousMessages: state.messages,
|
||||
previousHasMore: state.messagesHasMore,
|
||||
merged,
|
||||
apiHasMore: Boolean(page.hasMore),
|
||||
}),
|
||||
conversation: currentConversation,
|
||||
};
|
||||
});
|
||||
} catch (e) {
|
||||
console.error("Failed to sync messages", e);
|
||||
}
|
||||
},
|
||||
|
||||
loadOlderMessages: async () => {
|
||||
const conversationId = get().conversation?.id;
|
||||
if (
|
||||
!conversationId ||
|
||||
get().messagesLoadingMore ||
|
||||
!get().messagesHasMore
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const cursorId = parseCursorId(get().messagesCursor);
|
||||
if (cursorId <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
set({ messagesLoadingMore: true });
|
||||
try {
|
||||
const page = await fetchMessagesPage(conversationId, {
|
||||
cursor: cursorId,
|
||||
});
|
||||
const currentConversation = get().conversation;
|
||||
set((state) => {
|
||||
const merged = mergeMessagesByIdAsc(page.results, state.messages);
|
||||
return {
|
||||
messages: merged,
|
||||
messagesCursor: cursorFromLoadedMessages(merged) || page.cursor,
|
||||
messagesHasMore: page.hasMore,
|
||||
messagesLoadingMore: false,
|
||||
conversation: currentConversation,
|
||||
};
|
||||
});
|
||||
} catch (e) {
|
||||
set({ messagesLoadingMore: false });
|
||||
console.error("Failed to load older messages", e);
|
||||
}
|
||||
},
|
||||
|
||||
markConversationRead: async () => {
|
||||
const state = get();
|
||||
const conversation = state.conversation;
|
||||
const lastMessage = state.messages.at(-1);
|
||||
if (!conversation?.id || !lastMessage) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
(conversation.customerUnreadCount ?? 0) <= 0 &&
|
||||
(conversation.customerLastReadMessageId ?? 0) >= lastMessage.id
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (state.readingMessageId === lastMessage.id) {
|
||||
return;
|
||||
}
|
||||
|
||||
set({ readingMessageId: lastMessage.id });
|
||||
try {
|
||||
await markMessageRead(conversation.id, lastMessage.id);
|
||||
set((current) => ({
|
||||
readingMessageId: 0,
|
||||
messages: current.messages.map((item) =>
|
||||
(item.seqNo ?? 0) <= (lastMessage.seqNo ?? 0)
|
||||
? { ...item, customerRead: true }
|
||||
: item,
|
||||
),
|
||||
conversation: current.conversation
|
||||
? {
|
||||
...current.conversation,
|
||||
customerUnreadCount: 0,
|
||||
customerLastReadMessageId: lastMessage.id,
|
||||
customerLastReadSeqNo: lastMessage.seqNo,
|
||||
}
|
||||
: null,
|
||||
}));
|
||||
} catch (error) {
|
||||
set({ readingMessageId: 0 });
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
|
||||
bootstrap: () => {
|
||||
const token = ++bootstrapToken;
|
||||
|
||||
if (!get().isOpen) {
|
||||
closeSocket({ reconnect: false });
|
||||
set({ status: "disconnected" });
|
||||
return;
|
||||
}
|
||||
|
||||
const activateChat = async () => {
|
||||
try {
|
||||
set({ error: "", status: "connecting" });
|
||||
|
||||
const hostConfig = readWidgetConfig();
|
||||
const widgetConfig: WidgetConfigResponse =
|
||||
await fetchWidgetConfig().catch(() => ({}));
|
||||
if (bootstrapToken !== token || !get().isOpen) return;
|
||||
|
||||
set({
|
||||
title: hostConfig.title || widgetConfig.title || "在线客服",
|
||||
subtitle: hostConfig.subtitle || widgetConfig.subtitle || "",
|
||||
welcomeText: widgetConfig.welcomeText || "",
|
||||
themeColor:
|
||||
hostConfig.themeColor || widgetConfig.themeColor || "#2563eb",
|
||||
});
|
||||
|
||||
let currentConversation = get().conversation;
|
||||
if (!get().initialized || !currentConversation) {
|
||||
currentConversation = await createOrMatchConversation();
|
||||
if (bootstrapToken !== token || !get().isOpen) return;
|
||||
set({ initialized: true, conversation: currentConversation });
|
||||
}
|
||||
|
||||
await get().refreshMessages();
|
||||
if (bootstrapToken !== token || !get().isOpen) return;
|
||||
|
||||
connectSocket();
|
||||
} catch (bootstrapError) {
|
||||
if (bootstrapToken !== token || !get().isOpen) return;
|
||||
set({
|
||||
status: "disconnected",
|
||||
error:
|
||||
bootstrapError instanceof Error
|
||||
? bootstrapError.message
|
||||
: "初始化失败",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
void activateChat();
|
||||
},
|
||||
|
||||
handleSendMessage: async (content: string) => {
|
||||
const conversationId = get().conversation?.id;
|
||||
if (!conversationId) return;
|
||||
set({ error: "" });
|
||||
try {
|
||||
const nextMessage = await sendMessage(conversationId, content);
|
||||
set((state) => ({
|
||||
messages: state.messages.some((m) => m.id === nextMessage.id)
|
||||
? state.messages.map((m) =>
|
||||
m.id === nextMessage.id ? nextMessage : m,
|
||||
)
|
||||
: [...state.messages, nextMessage],
|
||||
conversation: state.conversation
|
||||
? {
|
||||
...state.conversation,
|
||||
customerLastReadMessageId: nextMessage.id,
|
||||
customerLastReadSeqNo: nextMessage.seqNo,
|
||||
customerUnreadCount: 0,
|
||||
lastMessageAt: nextMessage.sentAt,
|
||||
lastMessageSummary: summarizeMessage(nextMessage),
|
||||
}
|
||||
: null,
|
||||
}));
|
||||
} catch (e) {
|
||||
set({ error: e instanceof Error ? e.message : "发送消息失败" });
|
||||
}
|
||||
},
|
||||
|
||||
uploadMessageImage: async (file: File) => {
|
||||
const conversationId = get().conversation?.id;
|
||||
if (!conversationId) return null;
|
||||
set({ error: "" });
|
||||
try {
|
||||
const asset = await uploadImage(conversationId, file);
|
||||
return { url: asset.url, filename: asset.filename };
|
||||
} catch (e) {
|
||||
set({ error: e instanceof Error ? e.message : "发送图片失败" });
|
||||
return null;
|
||||
}
|
||||
},
|
||||
|
||||
sendAttachment: async (file: File) => {
|
||||
const conversationId = get().conversation?.id;
|
||||
if (!conversationId) return;
|
||||
set({ error: "" });
|
||||
try {
|
||||
const asset = await uploadAttachment(conversationId, file);
|
||||
const nextMessage = await sendMessageWithPayload(conversationId, {
|
||||
messageType: "attachment",
|
||||
content: asset.filename,
|
||||
payload: JSON.stringify({ assetId: asset.assetId }),
|
||||
clientMsgId: `widget_attachment_${generateUUID()}`,
|
||||
});
|
||||
set((state) => ({
|
||||
messages: state.messages.some((m) => m.id === nextMessage.id)
|
||||
? state.messages.map((m) =>
|
||||
m.id === nextMessage.id ? nextMessage : m,
|
||||
)
|
||||
: [...state.messages, nextMessage],
|
||||
conversation: state.conversation
|
||||
? {
|
||||
...state.conversation,
|
||||
customerLastReadMessageId: nextMessage.id,
|
||||
customerLastReadSeqNo: nextMessage.seqNo,
|
||||
customerUnreadCount: 0,
|
||||
lastMessageAt: nextMessage.sentAt,
|
||||
lastMessageSummary: summarizeMessage(nextMessage),
|
||||
}
|
||||
: null,
|
||||
}));
|
||||
} catch (e) {
|
||||
set({ error: e instanceof Error ? e.message : "发送附件失败" });
|
||||
}
|
||||
},
|
||||
|
||||
retry: async () => {
|
||||
if (!get().conversation?.id) return;
|
||||
|
||||
set({ error: "", status: "connecting" });
|
||||
try {
|
||||
await get().refreshMessages();
|
||||
if (get().isOpen) {
|
||||
shouldReconnect = true;
|
||||
connectSocket();
|
||||
}
|
||||
} catch (retryError) {
|
||||
set({
|
||||
status: "disconnected",
|
||||
error: retryError instanceof Error ? retryError.message : "刷新失败",
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
import { clsx, type ClassValue } from "clsx";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs));
|
||||
}
|
||||
|
||||
export function generateUUID() {
|
||||
if (typeof globalThis.crypto?.randomUUID === "function") {
|
||||
return globalThis.crypto.randomUUID();
|
||||
}
|
||||
|
||||
const bytes = new Uint8Array(16);
|
||||
if (typeof globalThis.crypto?.getRandomValues === "function") {
|
||||
globalThis.crypto.getRandomValues(bytes);
|
||||
} else {
|
||||
for (let i = 0; i < bytes.length; i += 1) {
|
||||
bytes[i] = Math.floor(Math.random() * 256);
|
||||
}
|
||||
}
|
||||
|
||||
bytes[6] = (bytes[6] & 0x0f) | 0x40;
|
||||
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
||||
|
||||
const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0"));
|
||||
return [
|
||||
hex.slice(0, 4).join(""),
|
||||
hex.slice(4, 6).join(""),
|
||||
hex.slice(6, 8).join(""),
|
||||
hex.slice(8, 10).join(""),
|
||||
hex.slice(10, 16).join(""),
|
||||
].join("-");
|
||||
}
|
||||
|
||||
export function formatDateTime(value?: string | null) {
|
||||
if (!value) {
|
||||
return "";
|
||||
}
|
||||
const date = new Date(value);
|
||||
if (Number.isNaN(date.getTime())) {
|
||||
return value;
|
||||
}
|
||||
const pad = (num: number) => String(num).padStart(2, "0");
|
||||
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
export type WidgetHostConfig = {
|
||||
channelId: string;
|
||||
baseUrl: string;
|
||||
apiBaseUrl?: string;
|
||||
/** 与后端 enums.ExternalSource 一致,默认 web_chat */
|
||||
externalSource?: string;
|
||||
title?: string;
|
||||
subtitle?: string;
|
||||
position?: "left" | "right";
|
||||
themeColor?: string;
|
||||
width?: string;
|
||||
/** 访客展示名,随请求以 X-External-Name / WS query externalName 传给后端作 ExternalName */
|
||||
subject?: string;
|
||||
};
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
CSAgentConfig?: WidgetHostConfig;
|
||||
__CS_AGENT_WIDGET_CONFIG__?: WidgetHostConfig;
|
||||
}
|
||||
}
|
||||
|
||||
export function readWidgetConfig(): WidgetHostConfig {
|
||||
if (typeof window === "undefined") {
|
||||
return {
|
||||
channelId: "",
|
||||
baseUrl: "",
|
||||
apiBaseUrl: "",
|
||||
};
|
||||
}
|
||||
const query = new URLSearchParams(window.location.search);
|
||||
const fallback = {
|
||||
channelId: query.get("channelId") ?? "",
|
||||
baseUrl: query.get("baseUrl") ?? "",
|
||||
apiBaseUrl: query.get("apiBaseUrl") ?? undefined,
|
||||
externalSource: query.get("externalSource") ?? undefined,
|
||||
title: query.get("title") ?? undefined,
|
||||
subtitle: query.get("subtitle") ?? undefined,
|
||||
position: (query.get("position") as "left" | "right" | null) ?? undefined,
|
||||
themeColor: query.get("themeColor") ?? undefined,
|
||||
width: query.get("width") ?? undefined,
|
||||
subject: query.get("subject") ?? undefined,
|
||||
};
|
||||
return window.__CS_AGENT_WIDGET_CONFIG__ ?? window.CSAgentConfig ?? fallback;
|
||||
}
|
||||
|
||||
export function setWidgetConfig(config: WidgetHostConfig) {
|
||||
if (typeof window === "undefined") {
|
||||
return;
|
||||
}
|
||||
window.__CS_AGENT_WIDGET_CONFIG__ = config;
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { setWidgetConfig, type WidgetHostConfig } from "@/lib/widget/config";
|
||||
|
||||
const INIT_MESSAGE_TYPE = "cs-agent:init";
|
||||
const OPEN_MESSAGE_TYPE = "cs-agent:open";
|
||||
const MINIMIZE_MESSAGE_TYPE = "cs-agent:minimize";
|
||||
const MAXIMIZED_MESSAGE_TYPE = "cs-agent:maximized";
|
||||
const READY_MESSAGE_TYPE = "cs-agent:ready";
|
||||
const REQUEST_MINIMIZE_MESSAGE_TYPE = "cs-agent:request-minimize";
|
||||
const REQUEST_CLOSE_MESSAGE_TYPE = "cs-agent:request-close";
|
||||
const REQUEST_TOGGLE_MAXIMIZE_MESSAGE_TYPE = "cs-agent:request-toggle-maximize";
|
||||
|
||||
type HostBridgeOptions = {
|
||||
onOpen?: () => void;
|
||||
onMinimize?: () => void;
|
||||
onMaximizedChange?: (isMaximized: boolean) => void;
|
||||
};
|
||||
|
||||
export function bindHostBridge(options: HostBridgeOptions = {}) {
|
||||
if (typeof window === "undefined") {
|
||||
return () => undefined;
|
||||
}
|
||||
|
||||
if (window.parent && window.parent !== window) {
|
||||
window.parent.postMessage({ type: READY_MESSAGE_TYPE }, "*");
|
||||
}
|
||||
|
||||
const handleMessage = (
|
||||
event: MessageEvent,
|
||||
) => {
|
||||
const data = event.data as
|
||||
| {
|
||||
type?: string;
|
||||
payload?: WidgetHostConfig | { isMaximized?: boolean };
|
||||
}
|
||||
| undefined;
|
||||
if (!data?.type) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.type === INIT_MESSAGE_TYPE && data.payload) {
|
||||
setWidgetConfig(data.payload as WidgetHostConfig);
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.type === OPEN_MESSAGE_TYPE) {
|
||||
options.onOpen?.();
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.type === MINIMIZE_MESSAGE_TYPE) {
|
||||
options.onMinimize?.();
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.type === MAXIMIZED_MESSAGE_TYPE) {
|
||||
options.onMaximizedChange?.(
|
||||
Boolean((data.payload as { isMaximized?: boolean } | undefined)?.isMaximized),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("message", handleMessage);
|
||||
return () => window.removeEventListener("message", handleMessage);
|
||||
}
|
||||
|
||||
function postToParent(type: string) {
|
||||
if (typeof window === "undefined") {
|
||||
return;
|
||||
}
|
||||
if (window.parent && window.parent !== window) {
|
||||
window.parent.postMessage({ type }, "*");
|
||||
}
|
||||
}
|
||||
|
||||
export function requestHostMinimize() {
|
||||
postToParent(REQUEST_MINIMIZE_MESSAGE_TYPE);
|
||||
}
|
||||
|
||||
export function requestHostClose() {
|
||||
postToParent(REQUEST_CLOSE_MESSAGE_TYPE);
|
||||
}
|
||||
|
||||
export function requestHostToggleMaximize() {
|
||||
postToParent(REQUEST_TOGGLE_MAXIMIZE_MESSAGE_TYPE);
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
(function () {
|
||||
if (window.__CS_AGENT_WIDGET_LOADED__) {
|
||||
return;
|
||||
}
|
||||
window.__CS_AGENT_WIDGET_LOADED__ = true;
|
||||
|
||||
var config = window.CSAgentConfig || {};
|
||||
var baseUrl = String(config.baseUrl || "").replace(/\/$/, "");
|
||||
if (!config.channelId || !baseUrl) {
|
||||
console.error("[cs-agent-widget] channelId and baseUrl are required");
|
||||
return;
|
||||
}
|
||||
|
||||
function resolveWidgetBaseUrl() {
|
||||
var currentScript = document.currentScript;
|
||||
if (currentScript && currentScript.src) {
|
||||
return currentScript.src.replace(/\/sdk\/cs-agent-widget\.js(?:\?.*)?$/, "");
|
||||
}
|
||||
if (/\/widget$/.test(baseUrl)) {
|
||||
return baseUrl;
|
||||
}
|
||||
return baseUrl + "/widget";
|
||||
}
|
||||
|
||||
var button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.dataset.csAgentWidget = "launcher";
|
||||
button.setAttribute("aria-label", config.title || "在线客服");
|
||||
button.textContent = config.title || "在线客服";
|
||||
button.style.position = "fixed";
|
||||
button.style.bottom = "24px";
|
||||
button.style.right = config.position === "left" ? "" : "24px";
|
||||
button.style.left = config.position === "left" ? "24px" : "";
|
||||
button.style.zIndex = "2147483000";
|
||||
button.style.border = "0";
|
||||
button.style.borderRadius = "999px";
|
||||
button.style.padding = "14px 18px";
|
||||
button.style.background = config.themeColor || "#0f6cbd";
|
||||
button.style.color = "#fff";
|
||||
button.style.font = "600 14px/1 sans-serif";
|
||||
button.style.boxShadow = "0 18px 40px rgba(15, 35, 65, 0.24)";
|
||||
button.style.cursor = "pointer";
|
||||
|
||||
var widgetBaseUrl = resolveWidgetBaseUrl();
|
||||
var frameUrl = new URL(widgetBaseUrl + "/frame/");
|
||||
frameUrl.searchParams.set("channelId", config.channelId);
|
||||
frameUrl.searchParams.set("baseUrl", baseUrl);
|
||||
if (config.apiBaseUrl) frameUrl.searchParams.set("apiBaseUrl", config.apiBaseUrl);
|
||||
if (config.title) frameUrl.searchParams.set("title", config.title);
|
||||
if (config.subtitle) frameUrl.searchParams.set("subtitle", config.subtitle);
|
||||
if (config.position) frameUrl.searchParams.set("position", config.position);
|
||||
if (config.themeColor) frameUrl.searchParams.set("themeColor", config.themeColor);
|
||||
if (config.width) frameUrl.searchParams.set("width", config.width);
|
||||
var frame = null;
|
||||
var frameLoaded = false;
|
||||
var frameReady = false;
|
||||
var initSent = false;
|
||||
var isOpen = false;
|
||||
var isMaximized = false;
|
||||
var frameHideTimer = null;
|
||||
var frameDestroyTimer = null;
|
||||
var animationDuration = 260;
|
||||
|
||||
function clearFrameTimers() {
|
||||
if (frameHideTimer) {
|
||||
window.clearTimeout(frameHideTimer);
|
||||
frameHideTimer = null;
|
||||
}
|
||||
if (frameDestroyTimer) {
|
||||
window.clearTimeout(frameDestroyTimer);
|
||||
frameDestroyTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
function applyFrameLayout() {
|
||||
if (!frame) {
|
||||
return;
|
||||
}
|
||||
|
||||
frame.style.position = "fixed";
|
||||
frame.style.border = "0";
|
||||
frame.style.overflow = "hidden";
|
||||
frame.style.background = "#fff";
|
||||
frame.style.zIndex = "2147483000";
|
||||
frame.style.boxShadow = "0 28px 80px rgba(15, 35, 65, 0.28)";
|
||||
frame.style.willChange = "top,right,bottom,left,width,height,opacity,transform,border-radius";
|
||||
frame.style.transition =
|
||||
"top 260ms cubic-bezier(0.22, 1, 0.36, 1), right 260ms cubic-bezier(0.22, 1, 0.36, 1), bottom 260ms cubic-bezier(0.22, 1, 0.36, 1), left 260ms cubic-bezier(0.22, 1, 0.36, 1), width 260ms cubic-bezier(0.22, 1, 0.36, 1), height 260ms cubic-bezier(0.22, 1, 0.36, 1), opacity 220ms ease, transform 260ms cubic-bezier(0.22, 1, 0.36, 1), border-radius 260ms cubic-bezier(0.22, 1, 0.36, 1), box-shadow 260ms ease";
|
||||
frame.style.transformOrigin =
|
||||
config.position === "left" ? "left bottom" : "right bottom";
|
||||
|
||||
if (isMaximized) {
|
||||
frame.style.top = "20px";
|
||||
frame.style.right = "20px";
|
||||
frame.style.bottom = "20px";
|
||||
frame.style.left = "20px";
|
||||
frame.style.width = "calc(100vw - 40px)";
|
||||
frame.style.maxWidth = "none";
|
||||
frame.style.height = "calc(100vh - 40px)";
|
||||
frame.style.borderRadius = "24px";
|
||||
return;
|
||||
}
|
||||
|
||||
frame.style.top = "";
|
||||
frame.style.bottom = "88px";
|
||||
frame.style.right = config.position === "left" ? "" : "24px";
|
||||
frame.style.left = config.position === "left" ? "24px" : "";
|
||||
frame.style.width = config.width || "380px";
|
||||
frame.style.maxWidth = "calc(100vw - 24px)";
|
||||
frame.style.height = "min(760px, calc(100vh - 112px))";
|
||||
frame.style.borderRadius = "28px";
|
||||
}
|
||||
|
||||
function flushFrameState() {
|
||||
if (!frame || !frameLoaded || !frameReady) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!initSent) {
|
||||
initSent = true;
|
||||
postToFrame({
|
||||
type: "cs-agent:init",
|
||||
payload: config,
|
||||
});
|
||||
}
|
||||
|
||||
postToFrame({ type: isOpen ? "cs-agent:open" : "cs-agent:minimize" });
|
||||
postToFrame({
|
||||
type: "cs-agent:maximized",
|
||||
payload: { isMaximized: isMaximized },
|
||||
});
|
||||
}
|
||||
|
||||
function postToFrame(message) {
|
||||
if (!frame || !frame.contentWindow) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
frame.contentWindow.postMessage(message, frameUrl.origin);
|
||||
} catch (error) {
|
||||
console.error("[cs-agent-widget] postMessage failed", error);
|
||||
}
|
||||
}
|
||||
|
||||
function syncFrameVisibility() {
|
||||
if (!frame) {
|
||||
return;
|
||||
}
|
||||
clearFrameTimers();
|
||||
applyFrameLayout();
|
||||
frame.style.display = "block";
|
||||
|
||||
if (isOpen) {
|
||||
frame.style.visibility = "visible";
|
||||
frame.style.pointerEvents = "auto";
|
||||
frameHideTimer = window.setTimeout(function () {
|
||||
if (!frame) {
|
||||
return;
|
||||
}
|
||||
frame.style.opacity = "1";
|
||||
frame.style.transform = "translate3d(0, 0, 0) scale(1)";
|
||||
}, 16);
|
||||
flushFrameState();
|
||||
return;
|
||||
}
|
||||
|
||||
frame.style.pointerEvents = "none";
|
||||
frame.style.opacity = "0";
|
||||
frame.style.transform = isMaximized
|
||||
? "translate3d(0, 10px, 0) scale(0.985)"
|
||||
: "translate3d(0, 16px, 0) scale(0.96)";
|
||||
frameHideTimer = window.setTimeout(function () {
|
||||
if (!frame || isOpen) {
|
||||
return;
|
||||
}
|
||||
frame.style.visibility = "hidden";
|
||||
}, animationDuration);
|
||||
flushFrameState();
|
||||
}
|
||||
|
||||
function handleWindowMessage(event) {
|
||||
if (!frame || event.source !== frame.contentWindow) {
|
||||
return;
|
||||
}
|
||||
|
||||
var data = event.data || {};
|
||||
if (data.type === "cs-agent:ready") {
|
||||
frameReady = true;
|
||||
flushFrameState();
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.type === "cs-agent:request-minimize") {
|
||||
isOpen = false;
|
||||
syncFrameVisibility();
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.type === "cs-agent:request-close") {
|
||||
destroyFrame();
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.type === "cs-agent:request-toggle-maximize") {
|
||||
isMaximized = !isMaximized;
|
||||
syncFrameVisibility();
|
||||
}
|
||||
}
|
||||
|
||||
function destroyFrame() {
|
||||
if (!frame) {
|
||||
return;
|
||||
}
|
||||
clearFrameTimers();
|
||||
frame.style.pointerEvents = "none";
|
||||
frame.style.opacity = "0";
|
||||
frame.style.transform = "translate3d(0, 18px, 0) scale(0.94)";
|
||||
frame.style.visibility = "hidden";
|
||||
frameDestroyTimer = window.setTimeout(function () {
|
||||
if (!frame) {
|
||||
return;
|
||||
}
|
||||
if (frame.parentNode) {
|
||||
frame.parentNode.removeChild(frame);
|
||||
}
|
||||
frame = null;
|
||||
frameLoaded = false;
|
||||
frameReady = false;
|
||||
initSent = false;
|
||||
isOpen = false;
|
||||
isMaximized = false;
|
||||
clearFrameTimers();
|
||||
}, animationDuration);
|
||||
}
|
||||
|
||||
function createFrame() {
|
||||
if (frame) {
|
||||
return frame;
|
||||
}
|
||||
|
||||
frame = document.createElement("iframe");
|
||||
frame.dataset.csAgentWidget = "frame";
|
||||
frame.title = config.title || "在线客服";
|
||||
frame.src = frameUrl.toString();
|
||||
applyFrameLayout();
|
||||
frame.style.display = "block";
|
||||
frame.style.visibility = "hidden";
|
||||
frame.style.pointerEvents = "none";
|
||||
frame.style.opacity = "0";
|
||||
frame.style.transform = "translate3d(0, 18px, 0) scale(0.96)";
|
||||
frame.addEventListener("load", function () {
|
||||
frameLoaded = true;
|
||||
syncFrameVisibility();
|
||||
});
|
||||
|
||||
document.body.appendChild(frame);
|
||||
return frame;
|
||||
}
|
||||
|
||||
button.addEventListener("click", function () {
|
||||
if (!frame) {
|
||||
createFrame();
|
||||
}
|
||||
isOpen = !isOpen;
|
||||
syncFrameVisibility();
|
||||
});
|
||||
|
||||
window.addEventListener("message", handleWindowMessage);
|
||||
document.body.appendChild(button);
|
||||
})();
|
||||
@@ -0,0 +1,16 @@
|
||||
import { generateUUID } from "@/lib/utils";
|
||||
|
||||
const EXTERNAL_ID_KEY = "cs-agent:external-id";
|
||||
|
||||
export function getOrCreateExternalId() {
|
||||
if (typeof window === "undefined") {
|
||||
return "";
|
||||
}
|
||||
const current = window.localStorage.getItem(EXTERNAL_ID_KEY);
|
||||
if (current) {
|
||||
return current;
|
||||
}
|
||||
const visitorId = `visitor_${generateUUID()}`;
|
||||
window.localStorage.setItem(EXTERNAL_ID_KEY, visitorId);
|
||||
return visitorId;
|
||||
}
|
||||
Reference in New Issue
Block a user