feat: widget sdk
This commit is contained in:
@@ -3,7 +3,7 @@ import { createSlice, PayloadAction } from "@reduxjs/toolkit";
|
||||
export interface State {
|
||||
ids: number[];
|
||||
// todo: check object type
|
||||
byId: { [id: number]: any };
|
||||
byId: { [id: number]: number[] };
|
||||
}
|
||||
|
||||
const initialState: State = {
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import toast from "react-hot-toast";
|
||||
import { removeReplyingMessage, addReplyingMessage } from "../../app/slices/message";
|
||||
import { removeReplyingMessage, addReplyingMessage, MessagePayload } from "../../app/slices/message";
|
||||
import { useSendChannelMsgMutation } from "../../app/services/channel";
|
||||
import { useSendMsgMutation } from "../../app/services/user";
|
||||
import { useReplyMessageMutation } from "../../app/services/message";
|
||||
import { useAppDispatch, useAppSelector } from "../../app/store";
|
||||
import { ContentTypeKey } from "../../types/message";
|
||||
|
||||
interface Props {
|
||||
context: "user" | "channel";
|
||||
@@ -18,12 +19,7 @@ interface SendMessagesDTO {
|
||||
channels: number[];
|
||||
}
|
||||
|
||||
interface SendMessageDTO {
|
||||
context: "user" | "channel";
|
||||
from: number;
|
||||
to: number;
|
||||
}
|
||||
|
||||
type SendMessageDTO = { type: ContentTypeKey } & Partial<MessagePayload>
|
||||
const useSendMessage = (props?: Props) => {
|
||||
const { context = "user", from = 0, to = 0 } = props || {};
|
||||
const dispatch = useAppDispatch();
|
||||
@@ -65,7 +61,7 @@ const useSendMessage = (props?: Props) => {
|
||||
const sendMessage = async ({
|
||||
type = "text",
|
||||
content,
|
||||
properties = {},
|
||||
properties,
|
||||
reply_mid,
|
||||
...rest
|
||||
}: SendMessageDTO) => {
|
||||
@@ -80,7 +76,7 @@ const useSendMessage = (props?: Props) => {
|
||||
await sendFn({
|
||||
id: to,
|
||||
content,
|
||||
properties: { ...properties },
|
||||
properties,
|
||||
type,
|
||||
from_uid: from,
|
||||
...rest
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
// import React from "react";
|
||||
|
||||
type Props = {};
|
||||
|
||||
const Chat = (props: Props) => {
|
||||
return <div className=" bg-black">Chat</div>;
|
||||
};
|
||||
|
||||
export default Chat;
|
||||
@@ -1,18 +0,0 @@
|
||||
import { useState } from "react";
|
||||
import Chat from "./Chat";
|
||||
type Props = {};
|
||||
|
||||
function Embed({ }: Props) {
|
||||
const [visible, setVisible] = useState(false);
|
||||
const toggleVisible = () => {
|
||||
setVisible((prev) => !prev);
|
||||
};
|
||||
return (
|
||||
<div className="bg-slate-400 w-12 h-12">
|
||||
<button onClick={toggleVisible}>{visible ? "close" : "open"}</button>
|
||||
{visible && <Chat />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default Embed;
|
||||
@@ -1,13 +1,14 @@
|
||||
import ReactDOM from "react-dom/client";
|
||||
import Embed from "./embed/index";
|
||||
import { Provider } from "react-redux";
|
||||
|
||||
import Widget from "./widget/index";
|
||||
import './assets/index.css';
|
||||
import MarkdownStyleOverride from "./common/component/MarkdownStyleOverride";
|
||||
import store from "./app/store";
|
||||
|
||||
const root = ReactDOM.createRoot(document.getElementById("root") as HTMLElement);
|
||||
|
||||
root.render(
|
||||
<>
|
||||
<Embed />
|
||||
<MarkdownStyleOverride />
|
||||
</>
|
||||
<Provider store={store}>
|
||||
<Widget />
|
||||
</Provider>
|
||||
);
|
||||
@@ -28,7 +28,7 @@ import HomePage from "./home";
|
||||
import ChatPage from "./chat";
|
||||
import Loading from "../common/component/Loading";
|
||||
import store, { useAppSelector } from "../app/store";
|
||||
import GuestLogining from "./guest";
|
||||
import GuestLogin from "./guest";
|
||||
let toastId: string;
|
||||
const PageRoutes = () => {
|
||||
const {
|
||||
@@ -51,7 +51,7 @@ const PageRoutes = () => {
|
||||
<HashRouter>
|
||||
<Suspense fallback={<Loading fullscreen={true} />}>
|
||||
<Routes>
|
||||
<Route path="/guest_login" element={<GuestLogining />} />
|
||||
<Route path="/guest_login" element={<GuestLogin />} />
|
||||
<Route path="/cb/:type/:payload" element={<CallbackPage />} />
|
||||
<Route path="/oauth/:token" element={<OAuthPage />} />
|
||||
<Route
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
// import React from "react";
|
||||
import { useAppSelector } from "../app/store";
|
||||
|
||||
type Props = {
|
||||
handleClick: () => void
|
||||
};
|
||||
|
||||
const Icon = ({ handleClick }: Props) => {
|
||||
const { logo } = useAppSelector(store => store.server);
|
||||
if (!logo) return null;
|
||||
return <button className="rounded-full w-12 h-12" onClick={handleClick}>
|
||||
<img src={logo} alt="logo" className="w-full h-full" />
|
||||
</button>;
|
||||
};
|
||||
|
||||
export default Icon;
|
||||
@@ -0,0 +1,25 @@
|
||||
import { FC } from 'react';
|
||||
import { useAppSelector } from '../../app/store';
|
||||
import IconClose from './close.svg';
|
||||
|
||||
type Props = {
|
||||
handleClose: () => void;
|
||||
};
|
||||
|
||||
const Index: FC<Props> = ({ handleClose }) => {
|
||||
const { name, logo } = useAppSelector(store => store.server);
|
||||
return (
|
||||
<div className="flex gap-4 justify-between items-center p-2">
|
||||
<div className="relative w-10 h-10">
|
||||
<img src={logo} alt="logo" className="w-full h-full" />
|
||||
</div>
|
||||
<div className="flex flex-col flex-1">
|
||||
<span className="text-gray-900 text-lg">{name}</span>
|
||||
{/* <span className="text-gray-400 text-sm">{online ? 'Active now' : 'Offline now'}</span> */}
|
||||
</div>
|
||||
<IconClose className="w-5 h-5 mr-2 cursor-pointer" onClick={handleClose} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Index;
|
||||
@@ -0,0 +1,14 @@
|
||||
import clsx from 'clsx';
|
||||
|
||||
type Props = {
|
||||
thin?: boolean
|
||||
};
|
||||
|
||||
const Index = ({ thin = false }: Props) => {
|
||||
const h = thin ? 'h-[1px]' : 'h-0.5';
|
||||
return (
|
||||
<hr className={clsx('w-full bg-gray-300 border-none', h)} />
|
||||
);
|
||||
};
|
||||
|
||||
export default Index;
|
||||
@@ -0,0 +1,81 @@
|
||||
import { FC, memo } from 'react';
|
||||
import clsx from 'clsx';
|
||||
import { MessagePayload } from '../../../../app/slices/message';
|
||||
// import { Message } from '../../../../types/chatbot';
|
||||
// import Image from 'next/image';
|
||||
import { useAppSelector } from '../../../../app/store';
|
||||
import { getInitials, getInitialsAvatar } from '../../../../common/utils';
|
||||
|
||||
type TimeProps = {
|
||||
time: number;
|
||||
};
|
||||
|
||||
const Time: FC<TimeProps> = ({ time }) => {
|
||||
return (
|
||||
<time className="text-gray-300 text-sm">{`${new Date(time).toLocaleTimeString('en-US', {
|
||||
minute: 'numeric',
|
||||
hour: 'numeric',
|
||||
hour12: true,
|
||||
})}`}</time>
|
||||
);
|
||||
};
|
||||
|
||||
export type MessageProps = {
|
||||
compact?: boolean;
|
||||
isFirst?: boolean;
|
||||
} & MessagePayload;
|
||||
|
||||
const Index: FC<MessageProps> = (props) => {
|
||||
const { server: { name, logo }, loginUser } = useAppSelector(store => { return { server: store.server, loginUser: store.authData.user }; });
|
||||
const { from_uid, content, created_at, compact, isFirst = false } = props;
|
||||
// 暂时写死
|
||||
const isHost = from_uid == 304;
|
||||
return (
|
||||
<div
|
||||
className={clsx(
|
||||
'flex flex-col relative pl-14 py-1 hover:bg-gray-100 rounded-sm',
|
||||
compact ? 'mt-2' : 'mt-6',
|
||||
isFirst ? 'mt-0' : ''
|
||||
)}
|
||||
>
|
||||
{!compact && (
|
||||
<div className="absolute left-2 top-2 w-10 h-10 rounded-full overflow-hidden">
|
||||
{isHost ? (
|
||||
<img src={logo} alt="logo" className="w-full h-full" />
|
||||
) : (
|
||||
<img className="w-10 h-10" src={getInitialsAvatar({ initials: getInitials(loginUser?.name ?? "Unkown") })} alt="avatar" />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{!compact && (
|
||||
<span className="flex items-center gap-2 leading-6">
|
||||
<em className="text-black not-italic font-bold text-md">{isHost ? name : loginUser?.name}</em>
|
||||
<Time time={created_at ?? 0} />
|
||||
</span>
|
||||
)}
|
||||
<p
|
||||
className={clsx(
|
||||
'text-gray-600 text-sm whitespace-normal break-words mt-2 w-[80%]',
|
||||
compact ? 'group relative mt-0' : ''
|
||||
)}
|
||||
>
|
||||
{compact && (
|
||||
<time className="absolute -left-2 top-0 -translate-x-full text-gray-300 text-[10px] invisible group-hover:visible">{`${new Date(created_at)
|
||||
.toLocaleTimeString('en-US', {
|
||||
second: 'numeric',
|
||||
minute: 'numeric',
|
||||
hour: 'numeric',
|
||||
hour12: true,
|
||||
})
|
||||
.split(' ')[0]
|
||||
}`}</time>
|
||||
)}
|
||||
{content}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default memo(Index, (prev, next) => {
|
||||
return prev.mid === next.mid;
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
/* eslint-disable @typescript-eslint/indent */
|
||||
import { FC, memo } from 'react';
|
||||
// import { MessagePayload } from '../../../app/slices/message';
|
||||
import { useAppSelector } from '../../../app/store';
|
||||
import TextMessage from './Message/Text';
|
||||
|
||||
type Props = {
|
||||
uid: number
|
||||
};
|
||||
|
||||
// 间隔10秒
|
||||
const interval = 10 * 1000;
|
||||
const Index: FC<Props> = ({ uid }) => {
|
||||
const { mids, messageMap } = useAppSelector(store => { return { mids: store.userMessage.byId[uid], messageMap: store.message }; });
|
||||
console.log("mids", mids, uid);
|
||||
|
||||
if (!mids) return null;
|
||||
return mids.map((mid, idx) => {
|
||||
const currMsg = messageMap[mid];
|
||||
const prevMsg = messageMap[mids[idx - 1]];
|
||||
const compact = !prevMsg
|
||||
? false
|
||||
: prevMsg.from_uid !== currMsg.from_uid
|
||||
? false
|
||||
: (currMsg.created_at ?? 0) - (prevMsg.created_at ?? 0) < interval;
|
||||
return <TextMessage key={currMsg.mid} {...currMsg} compact={compact} isFirst={idx === 0} />;
|
||||
});
|
||||
};
|
||||
|
||||
export default memo(Index, (prev, next) => {
|
||||
return JSON.stringify(prev.uid) === JSON.stringify(next.uid);
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
// import clsx from 'clsx'
|
||||
import { memo } from 'react';
|
||||
import { useAppSelector } from '../../app/store';
|
||||
|
||||
const TextMessage = ({ text, animate = '' }: { text: string; animate?: string }) => (
|
||||
<p className={`text-gray-600 text-md mb-3 ${animate}`}>{text}</p>
|
||||
);
|
||||
const Index = () => {
|
||||
const { name, logo } = useAppSelector(store => store.server);
|
||||
return (
|
||||
<div className="flex gap-2">
|
||||
<div className="w-12 h-12">
|
||||
<img src={logo} alt="logo" className="w-full h-full" />
|
||||
</div>
|
||||
<div className="flex flex-col">
|
||||
<span className="flex items-center gap-2 leading-6">
|
||||
<em className="text-black not-italic font-bold text-lg">{name}</em>
|
||||
<time className="text-gray-300 text-sm">{`${new Date().toLocaleTimeString('en-US', {
|
||||
minute: 'numeric',
|
||||
hour: 'numeric',
|
||||
hour12: true,
|
||||
})}`}</time>
|
||||
</span>
|
||||
<TextMessage text="Hi there, Nice to meet you!" animate="animate-[fadeInUp_.5s_ease-in-out_both]" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default memo(Index);
|
||||
@@ -0,0 +1,3 @@
|
||||
<svg width="22" height="22" viewBox="0 0 22 22" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M16.25 5.75L5.75 16.25M5.75 5.75L16.25 16.25" stroke="#667085" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 241 B |
@@ -0,0 +1,83 @@
|
||||
import { useState, useEffect, useRef, ChangeEvent } from 'react';
|
||||
import Header from './Header';
|
||||
import Welcome from './Welcome';
|
||||
import MessageFeed from './MessageFeed';
|
||||
import Line from './Line';
|
||||
import useSendMessage from '../../common/hook/useSendMessage';
|
||||
import { useAppSelector } from '../../app/store';
|
||||
type Props = {
|
||||
handleClose: () => void
|
||||
}
|
||||
|
||||
const Index = ({ handleClose }: Props) => {
|
||||
const messageListRef = useRef<HTMLElement | null>(null);
|
||||
const loginUid = useAppSelector(store => store.authData.user?.uid);
|
||||
const { sendMessage, isSuccess } = useSendMessage({
|
||||
from: loginUid,
|
||||
to: 304,
|
||||
context: "user"
|
||||
});
|
||||
// const { checked, firstEnter, session } = useSession({ preCheck: true });
|
||||
// const { isSending, sendSuccess, sendMessage, message } = useSendMessage();
|
||||
// const { appendMessage, messages } = useFeed();
|
||||
// const messageListRef = useRef<HTMLElement | null>(null);
|
||||
const [input, setInput] = useState('');
|
||||
const handleInput = (evt: ChangeEvent<HTMLTextAreaElement>) => {
|
||||
setInput(evt.target.value);
|
||||
};
|
||||
const handleSend = () => {
|
||||
if (!input) return;
|
||||
sendMessage({
|
||||
type: "text",
|
||||
content: input
|
||||
});
|
||||
setInput("");
|
||||
};
|
||||
|
||||
// 自动滚动到底部,todo:根据距离底部位置大小自动滚动 类似微信体验
|
||||
useEffect(() => {
|
||||
const container = messageListRef.current;
|
||||
if (container) {
|
||||
setTimeout(() => {
|
||||
container.scrollTop = container.scrollHeight;
|
||||
}, 30);
|
||||
}
|
||||
}, [isSuccess]);
|
||||
return (
|
||||
<aside className="flex flex-col justify-between bg-white w-full h-full rounded-[10px] pointer-events-auto">
|
||||
<Header handleClose={handleClose} />
|
||||
<Line />
|
||||
{/* message list */}
|
||||
<section ref={messageListRef} className="px-2 py-3 flex-1 overflow-y-auto scroll-smooth">
|
||||
<Welcome />
|
||||
<MessageFeed uid={304} />
|
||||
</section>
|
||||
<Line />
|
||||
{/* message input */}
|
||||
<div className="w-full px-2 py-3">
|
||||
<textarea
|
||||
value={input}
|
||||
onChange={handleInput}
|
||||
className="w-full h-full text-sm p-2 rounded-lg bg-gray-200 resize-none text-black outline-none"
|
||||
placeholder="Write a message..."
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
<Line thin />
|
||||
{/* operation area */}
|
||||
<div className="w-full flex px-3 py-2 justify-between">
|
||||
<div className="opts">{/* opts placeholder */}</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleSend}
|
||||
disabled={input.trim() === ''}
|
||||
className="rounded-full bg-[#FA491D] disabled:bg-gray-200 text-white disabled:text-gray-400 text-xs leading-4 px-2 py-1.5 "
|
||||
>
|
||||
Send
|
||||
</button>
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
};
|
||||
|
||||
export default Index;
|
||||
@@ -0,0 +1,29 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { useGetServerQuery } from "../app/services/server";
|
||||
|
||||
import Icon from "./Icon";
|
||||
import Popup from "./Popup";
|
||||
import usePreload from "./usePreload";
|
||||
// type Props = {
|
||||
|
||||
// };
|
||||
|
||||
function Widget() {
|
||||
const { rehydrated } = usePreload();
|
||||
const [visible, setVisible] = useState(false);
|
||||
const { isLoading, isError } = useGetServerQuery();
|
||||
const toggleVisible = () => {
|
||||
setVisible((prev) => !prev);
|
||||
};
|
||||
useEffect(() => {
|
||||
// 有无iframe内嵌
|
||||
const parentWindow = window.parent;
|
||||
if (parentWindow) {
|
||||
parentWindow.postMessage(visible ? 'OPEN' : 'CLOSE', '*');
|
||||
}
|
||||
}, [visible]);
|
||||
if (isLoading || isError || !rehydrated) return null;
|
||||
return visible ? <Popup handleClose={toggleVisible} /> : <Icon handleClick={toggleVisible} />;
|
||||
}
|
||||
|
||||
export default Widget;
|
||||
@@ -0,0 +1,42 @@
|
||||
import { useEffect } from "react";
|
||||
import dayjs from "dayjs";
|
||||
import { useAppSelector } from "../app/store";
|
||||
import initCache, { useRehydrate } from "../app/cache";
|
||||
import useStreaming from "../common/hook/useStreaming";
|
||||
// type Props={
|
||||
// guest?:boolean
|
||||
// }
|
||||
export default function usePreload() {
|
||||
const { rehydrate, rehydrated } = useRehydrate();
|
||||
const {
|
||||
loginUid,
|
||||
token,
|
||||
expireTime = +new Date(),
|
||||
} = useAppSelector((store) => {
|
||||
return {
|
||||
loginUid: store.authData.user?.uid,
|
||||
token: store.authData.token,
|
||||
expireTime: store.authData.expireTime
|
||||
};
|
||||
});
|
||||
const { setStreamingReady } = useStreaming();
|
||||
useEffect(() => {
|
||||
initCache();
|
||||
rehydrate();
|
||||
return () => {
|
||||
setStreamingReady(false);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const tokenAlmostExpire = dayjs().isAfter(new Date(expireTime - 20 * 1000));
|
||||
const canStreaming = !!loginUid && rehydrated && !!token && !tokenAlmostExpire;
|
||||
// console.log("ttt", loginUid, rehydrated, token);
|
||||
|
||||
useEffect(() => {
|
||||
setStreamingReady(canStreaming);
|
||||
}, [canStreaming]);
|
||||
|
||||
return {
|
||||
rehydrated
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user