@droppii-org/chat-sdk 0.0.19 → 0.0.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/dist/components/chatBubble/ChatBubble.d.ts +10 -0
  2. package/dist/components/chatBubble/ChatBubble.d.ts.map +1 -0
  3. package/dist/components/chatBubble/ChatBubble.js +28 -0
  4. package/dist/components/conversation/DeskConversationList.d.ts +1 -2
  5. package/dist/components/conversation/DeskConversationList.d.ts.map +1 -1
  6. package/dist/components/conversation/DeskConversationList.js +107 -148
  7. package/dist/components/message/MessageHeader.d.ts +8 -0
  8. package/dist/components/message/MessageHeader.d.ts.map +1 -0
  9. package/dist/components/message/MessageHeader.js +9 -0
  10. package/dist/components/message/MessageItem.d.ts +7 -0
  11. package/dist/components/message/MessageItem.d.ts.map +1 -0
  12. package/dist/components/message/MessageItem.js +21 -0
  13. package/dist/components/message/MessageList.d.ts +1 -1
  14. package/dist/components/message/MessageList.d.ts.map +1 -1
  15. package/dist/components/message/MessageList.js +47 -65
  16. package/dist/components/message/footer/BottomSection.d.ts +3 -0
  17. package/dist/components/message/footer/BottomSection.d.ts.map +1 -0
  18. package/dist/components/message/footer/BottomSection.js +6 -0
  19. package/dist/components/message/footer/index.d.ts +3 -0
  20. package/dist/components/message/footer/index.d.ts.map +1 -0
  21. package/dist/components/message/footer/index.js +25 -0
  22. package/dist/constants/index.d.ts +2 -0
  23. package/dist/constants/index.d.ts.map +1 -0
  24. package/dist/constants/index.js +1 -0
  25. package/dist/constants/sdk.d.ts.map +1 -1
  26. package/dist/constants/sdk.js +3 -1
  27. package/dist/context/ChatContext.d.ts +1 -1
  28. package/dist/context/ChatContext.d.ts.map +1 -1
  29. package/dist/context/ChatContext.js +46 -8
  30. package/dist/hooks/conversation/useConversation.d.ts +3 -1
  31. package/dist/hooks/conversation/useConversation.d.ts.map +1 -1
  32. package/dist/hooks/conversation/useConversation.js +24 -14
  33. package/dist/hooks/conversation/useConversationStore.d.ts +11 -0
  34. package/dist/hooks/conversation/useConversationStore.d.ts.map +1 -0
  35. package/dist/hooks/conversation/useConversationStore.js +10 -0
  36. package/dist/hooks/global/useGlobalEvent.d.ts +2 -0
  37. package/dist/hooks/global/useGlobalEvent.d.ts.map +1 -0
  38. package/dist/hooks/global/useGlobalEvent.js +78 -0
  39. package/dist/hooks/message/useMessage.d.ts +18 -6
  40. package/dist/hooks/message/useMessage.d.ts.map +1 -1
  41. package/dist/hooks/message/useMessage.js +115 -37
  42. package/dist/hooks/message/useSendMessage.d.ts +5 -2
  43. package/dist/hooks/message/useSendMessage.d.ts.map +1 -1
  44. package/dist/hooks/message/useSendMessage.js +33 -14
  45. package/dist/index.d.ts +3 -3
  46. package/dist/index.d.ts.map +1 -1
  47. package/dist/index.js +3 -3
  48. package/dist/layout/index.d.ts +7 -0
  49. package/dist/layout/index.d.ts.map +1 -0
  50. package/dist/layout/index.js +11 -0
  51. package/dist/screens/chatBubble/index.d.ts +10 -0
  52. package/dist/screens/chatBubble/index.d.ts.map +1 -0
  53. package/dist/screens/chatBubble/index.js +12 -0
  54. package/dist/screens/desk-message/index.d.ts.map +1 -1
  55. package/dist/screens/desk-message/index.js +3 -2
  56. package/dist/screens/deskMessage/index.d.ts +3 -0
  57. package/dist/screens/deskMessage/index.d.ts.map +1 -0
  58. package/dist/screens/deskMessage/index.js +22 -0
  59. package/dist/styles/global.css +1 -1
  60. package/dist/tsconfig.tsbuildinfo +1 -0
  61. package/dist/types/chat.d.ts +22 -1
  62. package/dist/types/chat.d.ts.map +1 -1
  63. package/dist/types/chat.js +14 -1
  64. package/dist/utils/events.d.ts +13 -0
  65. package/dist/utils/events.d.ts.map +1 -0
  66. package/dist/utils/events.js +4 -0
  67. package/package.json +18 -2
@@ -0,0 +1,25 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { LexicalComposer } from "@lexical/react/LexicalComposer";
4
+ import { RichTextPlugin } from "@lexical/react/LexicalRichTextPlugin";
5
+ import { ContentEditable } from "@lexical/react/LexicalContentEditable";
6
+ import { LexicalErrorBoundary } from "@lexical/react/LexicalErrorBoundary";
7
+ import FooterBottomSection from "./BottomSection";
8
+ const theme = {
9
+ // Theme styling goes here
10
+ };
11
+ // Catch any errors that occur during Lexical updates and log them
12
+ // or throw them as needed. If you don't throw them, Lexical will
13
+ // try to recover gracefully without losing user data.
14
+ const onError = (error) => {
15
+ console.error(error);
16
+ };
17
+ const initialConfig = {
18
+ namespace: "ChatInput",
19
+ theme,
20
+ onError,
21
+ };
22
+ const MessageFooter = () => {
23
+ return (_jsx(LexicalComposer, { initialConfig: initialConfig, children: _jsxs("div", { className: "border-t px-4 py-3", children: [_jsx("div", { className: "relative", children: _jsx(RichTextPlugin, { contentEditable: _jsx(ContentEditable, { className: "border border-indigo-500 rounded-md bg-blue-100 min-h-[64px] px-3 py-2 text-sm" }), ErrorBoundary: LexicalErrorBoundary, "aria-placeholder": "Nh\u1EADp tin nh\u1EAFn", placeholder: _jsx("div", { className: "absolute top-2 left-3", children: _jsx("p", { className: "text-gray-500 text-sm", children: "Nh\u1EADp tin nh\u1EAFn" }) }) }) }), _jsx(FooterBottomSection, {})] }) }));
24
+ };
25
+ export default MessageFooter;
@@ -0,0 +1,2 @@
1
+ export declare const coreWasmPath = "https://droppiistg.blob.core.windows.net/droppii-stg-public/3315964d-11d5-4d27-8af7-d2ec2354994f.wasm";
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/constants/index.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,YAAY,0GACgF,CAAC"}
@@ -0,0 +1 @@
1
+ export const coreWasmPath = "https://droppiistg.blob.core.windows.net/droppii-stg-public/3315964d-11d5-4d27-8af7-d2ec2354994f.wasm";
@@ -1 +1 @@
1
- {"version":3,"file":"sdk.d.ts","sourceRoot":"","sources":["../../src/constants/sdk.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,yBAAyB,CAAC;AAEjD,eAAO,MAAM,QAAQ,EAAE,UAAU,CAAC,OAAO,MAAM,CAI7C,CAAC"}
1
+ {"version":3,"file":"sdk.d.ts","sourceRoot":"","sources":["../../src/constants/sdk.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,yBAAyB,CAAC;AAGjD,eAAO,MAAM,QAAQ,EAAE,UAAU,CAAC,OAAO,MAAM,CAI7C,CAAC"}
@@ -1,5 +1,7 @@
1
1
  import { getSDK } from "@openim/wasm-client-sdk";
2
+ import { coreWasmPath } from "./index";
2
3
  export const DChatSDK = getSDK({
3
- coreWasmPath: "https://pub-b11e10131a914403b2a326ec38f7e99f.r2.dev/openIM.wasm",
4
+ coreWasmPath,
4
5
  sqlWasmPath: "/sql-wasm.wasm",
6
+ debug: process.env.NODE_ENV === "development",
5
7
  });
@@ -1,5 +1,5 @@
1
1
  import { ChatContextType, ChatProviderProps } from "../types/chat";
2
2
  export declare const ChatContext: import("react").Context<ChatContextType>;
3
3
  export declare const useChatContext: () => ChatContextType;
4
- export declare const ChatProvider: ({ children, config }: ChatProviderProps) => import("react/jsx-runtime").JSX.Element;
4
+ export declare const ChatProvider: ({ children, config, refetchToken, }: ChatProviderProps) => import("react/jsx-runtime").JSX.Element;
5
5
  //# sourceMappingURL=ChatContext.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"ChatContext.d.ts","sourceRoot":"","sources":["../../src/context/ChatContext.tsx"],"names":[],"mappings":"AAIA,OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAInE,eAAO,MAAM,WAAW,0CAEtB,CAAC;AAEH,eAAO,MAAM,cAAc,uBAAgC,CAAC;AAE5D,eAAO,MAAM,YAAY,GAAI,sBAAsB,iBAAiB,4CAkCnE,CAAC"}
1
+ {"version":3,"file":"ChatContext.d.ts","sourceRoot":"","sources":["../../src/context/ChatContext.tsx"],"names":[],"mappings":"AAIA,OAAO,EACL,eAAe,EACf,iBAAiB,EAElB,MAAM,eAAe,CAAC;AAIvB,eAAO,MAAM,WAAW,0CAGtB,CAAC;AAEH,eAAO,MAAM,cAAc,uBAAgC,CAAC;AAE5D,eAAO,MAAM,YAAY,GAAI,qCAI1B,iBAAiB,4CA2EnB,CAAC"}
@@ -1,14 +1,17 @@
1
1
  "use client";
2
2
  import { jsx as _jsx } from "react/jsx-runtime";
3
3
  import { createContext, useContext, useEffect, useState } from "react";
4
- import { Spin } from "antd";
4
+ import { CbEvents } from "@openim/wasm-client-sdk";
5
+ import { ConnectStatus, } from "../types/chat";
5
6
  import { DChatSDK } from "../constants/sdk";
7
+ import MainLayout from "../layout";
6
8
  export const ChatContext = createContext({
7
9
  user: null,
10
+ connectStatus: ConnectStatus.Disconnected,
8
11
  });
9
12
  export const useChatContext = () => useContext(ChatContext);
10
- export const ChatProvider = ({ children, config }) => {
11
- const [loading, setLoading] = useState(true);
13
+ export const ChatProvider = ({ children, config, refetchToken, }) => {
14
+ const [connectStatus, setConnectStatus] = useState(ConnectStatus.Disconnected);
12
15
  const [user, setUser] = useState(null);
13
16
  const getUserInfo = () => {
14
17
  DChatSDK.getSelfUserInfo()
@@ -19,18 +22,53 @@ export const ChatProvider = ({ children, config }) => {
19
22
  console.log("getSelfUserInfo", errCode, errMsg);
20
23
  });
21
24
  };
22
- const handleLogin = () => {
23
- DChatSDK.login(config)
25
+ const handleLogin = (newToken) => {
26
+ DChatSDK.login(Object.assign(Object.assign({}, config), { token: newToken || config.token }))
24
27
  .then((res) => {
25
28
  getUserInfo();
26
- setLoading(false);
27
29
  })
28
30
  .catch(({ errCode, errMsg }) => {
29
31
  console.log("handleLogin", errCode, errMsg);
30
32
  });
31
33
  };
32
34
  useEffect(() => {
33
- handleLogin();
35
+ if (config) {
36
+ handleLogin();
37
+ }
34
38
  }, [config]);
35
- return (_jsx(ChatContext.Provider, { value: { user }, children: loading ? _jsx(Spin, { fullscreen: true }) : children }));
39
+ useEffect(() => {
40
+ DChatSDK.on(CbEvents.OnUserTokenExpired, () => {
41
+ console.log("OnUserTokenExpired");
42
+ refetchToken().then((token) => {
43
+ if (!!token) {
44
+ handleLogin(token);
45
+ }
46
+ });
47
+ });
48
+ DChatSDK.on(CbEvents.OnUserTokenInvalid, () => {
49
+ console.log("OnUserTokenInvalid");
50
+ refetchToken().then((token) => {
51
+ if (!!token) {
52
+ handleLogin(token);
53
+ }
54
+ });
55
+ });
56
+ DChatSDK.on(CbEvents.OnConnectSuccess, () => {
57
+ setConnectStatus(ConnectStatus.Connected);
58
+ });
59
+ DChatSDK.on(CbEvents.OnConnecting, () => {
60
+ setConnectStatus(ConnectStatus.Connecting);
61
+ });
62
+ DChatSDK.on(CbEvents.OnConnectFailed, () => {
63
+ setConnectStatus(ConnectStatus.Disconnected);
64
+ });
65
+ return () => {
66
+ DChatSDK.off(CbEvents.OnUserTokenExpired, () => { });
67
+ DChatSDK.off(CbEvents.OnUserTokenInvalid, () => { });
68
+ DChatSDK.off(CbEvents.OnConnectSuccess, () => { });
69
+ DChatSDK.off(CbEvents.OnConnectFailed, () => { });
70
+ DChatSDK.off(CbEvents.OnConnecting, () => { });
71
+ };
72
+ }, [refetchToken]);
73
+ return (_jsx(ChatContext.Provider, { value: { user, connectStatus }, children: _jsx(MainLayout, { children: children }) }));
36
74
  };
@@ -1,6 +1,8 @@
1
1
  import { ConversationItem, SessionType } from "@openim/wasm-client-sdk";
2
- export declare const useConversationList: () => {
2
+ export declare const useConversationList: (selectedThreadId?: string) => {
3
3
  conversationList: ConversationItem[];
4
+ getAllConversationList: () => Promise<void>;
5
+ markConversationMessageAsRead: (conversationId: string) => void;
4
6
  };
5
7
  export declare const useConversationDetail: ({ sourceID, sessionType, }: {
6
8
  sourceID: string;
@@ -1 +1 @@
1
- {"version":3,"file":"useConversation.d.ts","sourceRoot":"","sources":["../../../src/hooks/conversation/useConversation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AAIxE,eAAO,MAAM,mBAAmB;;CAoC/B,CAAC;AAEF,eAAO,MAAM,qBAAqB,GAAI,4BAGnC;IACD,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,WAAW,CAAC;CAC1B;;CAwBA,CAAC"}
1
+ {"version":3,"file":"useConversation.d.ts","sourceRoot":"","sources":["../../../src/hooks/conversation/useConversation.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,gBAAgB,EAChB,WAAW,EAEZ,MAAM,yBAAyB,CAAC;AAIjC,eAAO,MAAM,mBAAmB,GAAI,mBAAmB,MAAM;;;oDAgBxC,MAAM;CAmC1B,CAAC;AAEF,eAAO,MAAM,qBAAqB,GAAI,4BAGnC;IACD,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,WAAW,CAAC;CAC1B;;CAuBA,CAAC"}
@@ -1,35 +1,46 @@
1
+ import { CbEvents, } from "@openim/wasm-client-sdk";
1
2
  import { useCallback, useEffect, useState } from "react";
2
3
  import { DChatSDK } from "../../constants/sdk";
3
- export const useConversationList = () => {
4
+ export const useConversationList = (selectedThreadId) => {
4
5
  const [conversationList, setConversationList] = useState([]);
5
6
  const getAllConversationList = useCallback(async () => {
6
7
  DChatSDK.getAllConversationList()
7
8
  .then(({ data }) => {
8
- console.log("getAllConversationList", data);
9
9
  setConversationList(data);
10
10
  })
11
11
  .catch((err) => {
12
12
  console.log("getAllConversationList", err);
13
13
  });
14
14
  }, []);
15
- const getOneConversation = useCallback(async () => {
16
- DChatSDK.getOneConversation({
17
- sourceID: "3408237279",
18
- sessionType: 3,
19
- })
20
- .then(({ data }) => {
21
- console.log("getOneConversation", data);
22
- })
23
- .catch((err) => {
24
- console.log("getOneConversation", err);
15
+ const markConversationMessageAsRead = useCallback((conversationId) => {
16
+ if (!conversationId)
17
+ return;
18
+ DChatSDK.markConversationMessageAsRead(conversationId)
19
+ .then()
20
+ .catch(({ errCode, errMsg }) => {
21
+ // Failed call
25
22
  });
26
23
  }, []);
27
24
  useEffect(() => {
28
25
  getAllConversationList();
29
- getOneConversation();
30
26
  }, [getAllConversationList]);
27
+ useEffect(() => {
28
+ DChatSDK.on(CbEvents.OnConversationChanged, ({ data }) => {
29
+ setConversationList(data);
30
+ });
31
+ return () => {
32
+ DChatSDK.off(CbEvents.OnConversationChanged, () => { });
33
+ };
34
+ }, []);
35
+ useEffect(() => {
36
+ if (selectedThreadId) {
37
+ markConversationMessageAsRead(selectedThreadId);
38
+ }
39
+ }, [selectedThreadId, markConversationMessageAsRead]);
31
40
  return {
32
41
  conversationList,
42
+ getAllConversationList,
43
+ markConversationMessageAsRead,
33
44
  };
34
45
  };
35
46
  export const useConversationDetail = ({ sourceID, sessionType, }) => {
@@ -40,7 +51,6 @@ export const useConversationDetail = ({ sourceID, sessionType, }) => {
40
51
  sessionType,
41
52
  })
42
53
  .then(({ data }) => {
43
- console.log("getOneConversation", data);
44
54
  setConversationDetail(data);
45
55
  })
46
56
  .catch((err) => {
@@ -0,0 +1,11 @@
1
+ interface ConversationStore {
2
+ conversationData: any;
3
+ setConversationData: (data: any) => void;
4
+ selectedThreadId: string;
5
+ selectedSourceId: string;
6
+ setSelectedThreadId: (threadId: string) => void;
7
+ setSelectedSourceId: (sourceId: string) => void;
8
+ }
9
+ declare const useConversationStore: import("zustand").UseBoundStore<import("zustand").StoreApi<ConversationStore>>;
10
+ export default useConversationStore;
11
+ //# sourceMappingURL=useConversationStore.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useConversationStore.d.ts","sourceRoot":"","sources":["../../../src/hooks/conversation/useConversationStore.ts"],"names":[],"mappings":"AAEA,UAAU,iBAAiB;IACzB,gBAAgB,EAAE,GAAG,CAAC;IACtB,mBAAmB,EAAE,CAAC,IAAI,EAAE,GAAG,KAAK,IAAI,CAAC;IACzC,gBAAgB,EAAE,MAAM,CAAC;IACzB,gBAAgB,EAAE,MAAM,CAAC;IACzB,mBAAmB,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,IAAI,CAAC;IAChD,mBAAmB,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,IAAI,CAAC;CACjD;AAED,QAAA,MAAM,oBAAoB,gFAOvB,CAAC;AAEJ,eAAe,oBAAoB,CAAC"}
@@ -0,0 +1,10 @@
1
+ import { create } from "zustand";
2
+ const useConversationStore = create((set) => ({
3
+ conversationData: null,
4
+ setConversationData: (data) => set({ conversationData: data }),
5
+ selectedThreadId: "",
6
+ setSelectedThreadId: (threadId) => set({ selectedThreadId: threadId }),
7
+ selectedSourceId: "",
8
+ setSelectedSourceId: (sourceId) => set({ selectedSourceId: sourceId }),
9
+ }));
10
+ export default useConversationStore;
@@ -0,0 +1,2 @@
1
+ export declare const useGlobalEvent: () => void;
2
+ //# sourceMappingURL=useGlobalEvent.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useGlobalEvent.d.ts","sourceRoot":"","sources":["../../../src/hooks/global/useGlobalEvent.ts"],"names":[],"mappings":"AAiBA,eAAO,MAAM,cAAc,YAqF1B,CAAC"}
@@ -0,0 +1,78 @@
1
+ import { useEffect } from "react";
2
+ import { DChatSDK } from "../../constants/sdk";
3
+ import { CbEvents, MessageType, SessionType, } from "@openim/wasm-client-sdk";
4
+ import { CustomType } from "../../types/chat";
5
+ import { pushNewMessage, updateOneMessage } from "../message/useMessage";
6
+ import { useChatContext } from "../../context/ChatContext";
7
+ import useConversationStore from "../conversation/useConversationStore";
8
+ const notPushType = [MessageType.TypingMessage, MessageType.RevokeMessage];
9
+ export const useGlobalEvent = () => {
10
+ const { user } = useChatContext();
11
+ const selectedSourceId = useConversationStore((state) => state.selectedSourceId);
12
+ const revokedMessageHandler = ({ data }) => {
13
+ updateOneMessage({
14
+ clientMsgID: data.clientMsgID,
15
+ contentType: MessageType.RevokeMessage,
16
+ notificationElem: {
17
+ detail: JSON.stringify(data),
18
+ },
19
+ });
20
+ };
21
+ const inCurrentConversation = (newServerMsg) => {
22
+ switch (newServerMsg.sessionType) {
23
+ case SessionType.Single:
24
+ return (newServerMsg.sendID === selectedSourceId ||
25
+ ((user === null || user === void 0 ? void 0 : user.userID) && newServerMsg.recvID === selectedSourceId));
26
+ case SessionType.Group:
27
+ case SessionType.WorkingGroup:
28
+ return newServerMsg.groupID === selectedSourceId;
29
+ case SessionType.Notification:
30
+ return newServerMsg.sendID === selectedSourceId;
31
+ default:
32
+ return false;
33
+ }
34
+ };
35
+ const handleNewMessage = (newServerMsg) => {
36
+ if (newServerMsg.contentType === MessageType.CustomMessage) {
37
+ const customData = JSON.parse(newServerMsg.customElem.data);
38
+ if (CustomType.CallingInvite <= customData.customType &&
39
+ customData.customType <= CustomType.CallingHungup) {
40
+ return;
41
+ }
42
+ }
43
+ if (!inCurrentConversation(newServerMsg))
44
+ return;
45
+ if (!notPushType.includes(newServerMsg.contentType)) {
46
+ pushNewMessage(newServerMsg);
47
+ }
48
+ };
49
+ const newMessageHandler = ({ data }) => {
50
+ data.map((message) => handleNewMessage(message));
51
+ };
52
+ const loginCheck = async () => {
53
+ // check openIM token and user info
54
+ };
55
+ const setIMListener = () => {
56
+ // message
57
+ DChatSDK.on(CbEvents.OnRecvNewMessages, newMessageHandler);
58
+ DChatSDK.on(CbEvents.OnNewRecvMessageRevoked, revokedMessageHandler);
59
+ };
60
+ const disposeIMListener = () => {
61
+ // message
62
+ DChatSDK.off(CbEvents.OnRecvNewMessages, newMessageHandler);
63
+ };
64
+ /** LIFE CYCLE */
65
+ useEffect(() => {
66
+ loginCheck();
67
+ setIMListener();
68
+ window.addEventListener("online", () => {
69
+ DChatSDK.networkStatusChanged();
70
+ });
71
+ window.addEventListener("offline", () => {
72
+ DChatSDK.networkStatusChanged();
73
+ });
74
+ return () => {
75
+ disposeIMListener();
76
+ };
77
+ }, []);
78
+ };
@@ -1,9 +1,21 @@
1
1
  import { MessageItem } from "@openim/wasm-client-sdk";
2
- export declare const useMessage: (conversationId?: string) => {
3
- refetch: () => void;
4
- isEnd?: boolean | undefined;
5
- errCode?: number | undefined;
6
- errMsg?: string | undefined;
7
- messageList?: MessageItem[] | undefined;
2
+ import { GroupMessageItem } from "../../types/chat";
3
+ export declare const useMessage: (conversationId: string) => {
4
+ loadState: {
5
+ initLoading: boolean;
6
+ hasMoreOld: boolean;
7
+ messageList: MessageItem[];
8
+ groupMessageList: GroupMessageItem[];
9
+ };
10
+ latestLoadState: import("react").RefObject<{
11
+ initLoading: boolean;
12
+ hasMoreOld: boolean;
13
+ messageList: MessageItem[];
14
+ groupMessageList: GroupMessageItem[];
15
+ }>;
16
+ moreOldLoading: boolean;
17
+ getMoreOldMessages: (loadMore?: any) => Promise<void>;
8
18
  };
19
+ export declare const pushNewMessage: (message: MessageItem) => void;
20
+ export declare const updateOneMessage: (message: MessageItem) => void;
9
21
  //# sourceMappingURL=useMessage.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"useMessage.d.ts","sourceRoot":"","sources":["../../../src/hooks/message/useMessage.ts"],"names":[],"mappings":"AACA,OAAO,EAIL,WAAW,EACZ,MAAM,yBAAyB,CAAC;AAGjC,eAAO,MAAM,UAAU,GAAI,iBAAiB,MAAM;;;;;;CAqDjD,CAAC"}
1
+ {"version":3,"file":"useMessage.d.ts","sourceRoot":"","sources":["../../../src/hooks/message/useMessage.ts"],"names":[],"mappings":"AACA,OAAO,EAAY,WAAW,EAAE,MAAM,yBAAyB,CAAC;AAEhE,OAAO,EAAqB,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAOvE,eAAO,MAAM,UAAU,GAAI,gBAAgB,MAAM;;;;qBAI1B,WAAW,EAAE;0BACR,gBAAgB,EAAE;;;;;qBADvB,WAAW,EAAE;0BACR,gBAAgB,EAAE;;;;CA8I7C,CAAC;AAEF,eAAO,MAAM,cAAc,GAAI,SAAS,WAAW,SACpB,CAAC;AAChC,eAAO,MAAM,gBAAgB,GAAI,SAAS,WAAW,SACpB,CAAC"}
@@ -1,46 +1,124 @@
1
- import { useCallback, useEffect, useState } from "react";
2
- import { ViewType, CbEvents, } from "@openim/wasm-client-sdk";
1
+ import { useEffect, useState } from "react";
2
+ import { ViewType } from "@openim/wasm-client-sdk";
3
3
  import { DChatSDK } from "../../constants/sdk";
4
+ import { v4 as uuidv4 } from "uuid";
5
+ import { useLatest, useRequest } from "ahooks";
6
+ import emitter, { emit } from "../../utils/events";
7
+ const PAGE_SIZE = 50;
4
8
  export const useMessage = (conversationId) => {
5
- const [dataMessages, setDataMessages] = useState(null);
6
- const getAdvancedHistoryMessageList = useCallback(() => {
7
- if (!conversationId)
8
- return;
9
- DChatSDK.getSelfUserInfo()
10
- .then(({ data }) => {
11
- console.log("getSelfUserInfo", data);
12
- })
13
- .catch(({ errCode, errMsg }) => {
14
- console.log("getSelfUserInfo", errCode, errMsg);
15
- });
16
- DChatSDK.getAdvancedHistoryMessageList({
17
- conversationID: conversationId,
18
- count: 1000,
19
- startClientMsgID: "",
9
+ const [loadState, setLoadState] = useState({
10
+ initLoading: true,
11
+ hasMoreOld: true,
12
+ messageList: [],
13
+ groupMessageList: [],
14
+ });
15
+ const latestLoadState = useLatest(loadState);
16
+ const parseGroupMessageList = (messageList) => {
17
+ if (!messageList)
18
+ return [];
19
+ const mGroupMessages = messageList === null || messageList === void 0 ? void 0 : messageList.reduce((acc, cur) => {
20
+ const extendMessageInfo = JSON.parse((cur === null || cur === void 0 ? void 0 : cur.ex) || "{}");
21
+ if (extendMessageInfo === null || extendMessageInfo === void 0 ? void 0 : extendMessageInfo.groupMessageID) {
22
+ const findGroupMessageIndex = acc.findIndex((item) => item.groupMessageID === (extendMessageInfo === null || extendMessageInfo === void 0 ? void 0 : extendMessageInfo.groupMessageID));
23
+ if (findGroupMessageIndex === -1) {
24
+ acc.push({
25
+ groupMessageID: extendMessageInfo.groupMessageID,
26
+ messages: [cur],
27
+ sendID: cur.sendID,
28
+ sendTime: cur.sendTime,
29
+ });
30
+ }
31
+ else {
32
+ acc[findGroupMessageIndex].messages.push(cur);
33
+ }
34
+ }
35
+ else {
36
+ acc.push({
37
+ groupMessageID: uuidv4(),
38
+ messages: [cur],
39
+ sendID: cur.sendID,
40
+ sendTime: cur.sendTime,
41
+ });
42
+ }
43
+ return acc;
44
+ }, []);
45
+ return mGroupMessages;
46
+ };
47
+ const { loading: moreOldLoading, runAsync: getMoreOldMessages } = useRequest(async (loadMore = true) => {
48
+ var _a, _b;
49
+ const reqConversationID = conversationId;
50
+ const { data } = await DChatSDK.getAdvancedHistoryMessageList({
51
+ count: PAGE_SIZE,
52
+ startClientMsgID: loadMore
53
+ ? ((_b = (_a = latestLoadState.current) === null || _a === void 0 ? void 0 : _a.messageList[0]) === null || _b === void 0 ? void 0 : _b.clientMsgID) || ""
54
+ : "",
55
+ conversationID: conversationId !== null && conversationId !== void 0 ? conversationId : "",
20
56
  viewType: ViewType.History,
21
- })
22
- .then(({ data }) => {
23
- console.log("getAdvancedHistoryMessageList", data);
24
- setDataMessages(data);
25
- })
26
- .catch((err) => {
27
- console.log("getAdvancedHistoryMessageList", err);
28
57
  });
29
- }, [conversationId]);
30
- const onRecvNewMessages = useCallback((data) => {
31
- getAdvancedHistoryMessageList();
32
- }, [getAdvancedHistoryMessageList]);
58
+ if (conversationId !== reqConversationID)
59
+ return;
60
+ setTimeout(() => setLoadState((preState) => {
61
+ const messageList = [
62
+ ...data.messageList,
63
+ ...(loadMore ? preState.messageList : []),
64
+ ];
65
+ const groupMessageList = parseGroupMessageList(messageList);
66
+ return Object.assign(Object.assign({}, preState), { initLoading: false, hasMoreOld: !data.isEnd, messageList,
67
+ groupMessageList });
68
+ }));
69
+ }, {
70
+ manual: true,
71
+ });
72
+ const loadHistoryMessages = () => getMoreOldMessages(false);
33
73
  useEffect(() => {
34
- getAdvancedHistoryMessageList();
35
- }, [getAdvancedHistoryMessageList]);
74
+ const pushNewMessage = (message) => {
75
+ var _a, _b;
76
+ if ((_b = (_a = latestLoadState.current) === null || _a === void 0 ? void 0 : _a.messageList) === null || _b === void 0 ? void 0 : _b.find((item) => item.clientMsgID === message.clientMsgID)) {
77
+ return;
78
+ }
79
+ setLoadState((preState) => {
80
+ const messageList = [...preState.messageList, message];
81
+ const groupMessageList = parseGroupMessageList(messageList);
82
+ return Object.assign(Object.assign({}, preState), { messageList,
83
+ groupMessageList });
84
+ });
85
+ };
86
+ const updateOneMessage = (message) => {
87
+ setLoadState((preState) => {
88
+ const tmpList = [...preState.messageList];
89
+ const idx = tmpList.findIndex((msg) => msg.clientMsgID === message.clientMsgID);
90
+ if (idx < 0) {
91
+ return preState;
92
+ }
93
+ tmpList[idx] = Object.assign(Object.assign({}, tmpList[idx]), message);
94
+ const groupMessageList = parseGroupMessageList(tmpList);
95
+ return Object.assign(Object.assign({}, preState), { messageList: tmpList, groupMessageList });
96
+ });
97
+ };
98
+ emitter.on("PUSH_NEW_MSG", pushNewMessage);
99
+ emitter.on("UPDATE_ONE_MSG", updateOneMessage);
100
+ return () => {
101
+ emitter.off("PUSH_NEW_MSG", pushNewMessage);
102
+ emitter.off("UPDATE_ONE_MSG", updateOneMessage);
103
+ };
104
+ }, []);
36
105
  useEffect(() => {
37
- DChatSDK.on(CbEvents.OnRecvNewMessages, ({ data }) => {
38
- console.log("OnRecvNewMessages123", data);
39
- onRecvNewMessages(data);
40
- });
106
+ loadHistoryMessages();
41
107
  return () => {
42
- DChatSDK.off(CbEvents.OnRecvNewMessages, () => { });
108
+ setLoadState(() => ({
109
+ initLoading: true,
110
+ hasMoreOld: true,
111
+ messageList: [],
112
+ groupMessageList: [],
113
+ }));
43
114
  };
44
- }, [onRecvNewMessages]);
45
- return Object.assign(Object.assign({}, dataMessages), { refetch: getAdvancedHistoryMessageList });
115
+ }, [conversationId]);
116
+ return {
117
+ loadState,
118
+ latestLoadState,
119
+ moreOldLoading,
120
+ getMoreOldMessages,
121
+ };
46
122
  };
123
+ export const pushNewMessage = (message) => emit("PUSH_NEW_MSG", message);
124
+ export const updateOneMessage = (message) => emit("UPDATE_ONE_MSG", message);
@@ -1,10 +1,13 @@
1
+ import { MessageItem } from "@openim/wasm-client-sdk";
2
+ import { ExtendMessageInfo } from "../../types/chat";
1
3
  interface SendMessageProps {
2
4
  recvID: string;
3
5
  groupID: string;
4
6
  }
5
- export declare const createTextMessage: (text: string) => Promise<import("@openim/wasm-client-sdk").MessageItem | null>;
7
+ export declare const createTextMessage: (text: string) => Promise<MessageItem | null>;
6
8
  export declare const useSendMessage: (props: SendMessageProps) => {
7
- sendTextMessage: (text: string) => Promise<boolean>;
9
+ sendTextMessage: (text: string, lastMessage?: MessageItem) => Promise<null | undefined>;
8
10
  };
11
+ export declare const generateExtendMessageInfo: (currentUserID: string, lastMessage?: MessageItem) => ExtendMessageInfo;
9
12
  export {};
10
13
  //# sourceMappingURL=useSendMessage.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"useSendMessage.d.ts","sourceRoot":"","sources":["../../../src/hooks/message/useSendMessage.ts"],"names":[],"mappings":"AAGA,UAAU,gBAAgB;IACxB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,eAAO,MAAM,iBAAiB,GAAU,MAAM,MAAM,kEAUnD,CAAC;AAEF,eAAO,MAAM,cAAc,GAAI,OAAO,gBAAgB;4BAIf,MAAM;CAsB5C,CAAC"}
1
+ {"version":3,"file":"useSendMessage.d.ts","sourceRoot":"","sources":["../../../src/hooks/message/useSendMessage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAiB,MAAM,yBAAyB,CAAC;AAErE,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAQrD,UAAU,gBAAgB;IACxB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,eAAO,MAAM,iBAAiB,GAAU,MAAM,MAAM,gCAanD,CAAC;AAEF,eAAO,MAAM,cAAc,GAAI,OAAO,gBAAgB;4BAKrC,MAAM,gBAAgB,WAAW;CAqCjD,CAAC;AAEF,eAAO,MAAM,yBAAyB,GACpC,eAAe,MAAM,EACrB,cAAc,WAAW,KAapB,iBACN,CAAC"}
@@ -1,41 +1,60 @@
1
+ import { MessageStatus } from "@openim/wasm-client-sdk";
1
2
  import { DChatSDK } from "../../constants/sdk";
3
+ import dayjs from "dayjs";
4
+ import { v4 as uuidv4 } from "uuid";
2
5
  import { useChatContext } from "../../context/ChatContext";
6
+ import { useCallback } from "react";
7
+ import { pushNewMessage, updateOneMessage } from "./useMessage";
8
+ import { emit } from "../../utils/events";
3
9
  export const createTextMessage = async (text) => {
4
- let textMessage = await DChatSDK.createTextMessage(text)
10
+ let textMessage = await DChatSDK.createTextMessage(text, new Date().getTime().toString())
5
11
  .then(({ data }) => {
6
12
  return data;
7
13
  })
8
14
  .catch(({ errCode, errMsg }) => {
9
- console.log("createTextMessage", errCode, errMsg);
15
+ console.error("createTextMessage", errCode, errMsg);
10
16
  return null;
11
17
  });
12
18
  return textMessage;
13
19
  };
14
20
  export const useSendMessage = (props) => {
15
- const { user } = useChatContext();
16
21
  const { recvID, groupID } = props;
17
- const sendTextMessage = async (text) => {
18
- let result = false;
22
+ const { user } = useChatContext();
23
+ const sendTextMessage = useCallback(async (text, lastMessage) => {
24
+ let result = null;
19
25
  if (!recvID && !groupID)
20
- return false;
26
+ return null;
21
27
  const textMessage = await createTextMessage(text);
22
- console.log("textMessage", textMessage);
23
28
  if (!textMessage)
24
- return false;
29
+ return null;
30
+ const extendMessageInfo = generateExtendMessageInfo((user === null || user === void 0 ? void 0 : user.userID) || "", lastMessage);
31
+ const messageItem = Object.assign(Object.assign({}, textMessage), { ex: JSON.stringify(extendMessageInfo) || "{}" });
32
+ //manual send text msg = auto push
33
+ pushNewMessage(messageItem);
34
+ emit("CHAT_LIST_SCROLL_TO_BOTTOM");
25
35
  try {
26
- await DChatSDK.sendMessage({
36
+ const { data: successMessage } = await DChatSDK.sendMessage({
27
37
  recvID,
28
38
  groupID,
29
- message: textMessage,
39
+ message: messageItem,
30
40
  });
31
- result = true;
41
+ updateOneMessage(successMessage);
32
42
  }
33
43
  catch (error) {
34
- console.log("sendMessage", error);
44
+ updateOneMessage(Object.assign(Object.assign({}, messageItem), { status: MessageStatus.Failed }));
35
45
  }
36
- return result;
37
- };
46
+ }, [recvID, groupID, user]);
38
47
  return {
39
48
  sendTextMessage,
40
49
  };
41
50
  };
51
+ export const generateExtendMessageInfo = (currentUserID, lastMessage) => {
52
+ const diffSendTime = dayjs().diff(lastMessage === null || lastMessage === void 0 ? void 0 : lastMessage.sendTime, "minutes");
53
+ const isSameSender = (lastMessage === null || lastMessage === void 0 ? void 0 : lastMessage.sendID) === currentUserID;
54
+ const lastMessageExtendMessageInfo = JSON.parse((lastMessage === null || lastMessage === void 0 ? void 0 : lastMessage.ex) || "{}");
55
+ return {
56
+ groupMessageID: isSameSender && diffSendTime <= 5
57
+ ? (lastMessageExtendMessageInfo === null || lastMessageExtendMessageInfo === void 0 ? void 0 : lastMessageExtendMessageInfo.groupMessageID) || uuidv4()
58
+ : uuidv4(),
59
+ };
60
+ };