UNPKG

@ant-design/x-sdk

Version:

placeholder for @ant-design/x-sdk

97 lines 2.87 kB
import { chatMessagesStoreHelper } from "../x-chat/store"; /** * We manage all conversation stores here, so that useXChat can get the conversation data by conversationKey. */ export const conversationStoreHelper = { _allConversationStores: new Map(), set: (key, store) => { conversationStoreHelper._allConversationStores.set(key, store); }, delete: key => { conversationStoreHelper._allConversationStores.delete(key); }, getConversation: conversationKey => { for (const store of conversationStoreHelper._allConversationStores.values()) { if (store) { const conversation = store.getConversation(conversationKey); if (conversation) { return conversation; } } } } }; export class ConversationStore { conversations = []; listeners = []; storeKey; activeConversationKey; emitListeners() { this.listeners.forEach(listener => { listener(); }); } constructor(defaultConversations, defaultActiveConversationKey) { this.setConversations(defaultConversations); this.storeKey = Math.random().toString(); conversationStoreHelper.set(this.storeKey, this); this.activeConversationKey = defaultActiveConversationKey; } setActiveConversationKey = key => { this.activeConversationKey = key; this.emitListeners(); return true; }; setConversations = list => { this.conversations = [...list]; this.emitListeners(); return true; }; getConversation = key => { return this.conversations.find(item => item.key === key); }; addConversation = (conversation, placement) => { const exist = this.getConversation(conversation.key); if (!exist) { this.setConversations(placement === 'prepend' ? [conversation, ...this.conversations] : [...this.conversations, conversation]); return true; } return false; }; setConversation = (key, conversation) => { const exist = this.getConversation(key); if (exist) { Object.assign(exist, conversation); this.setConversations([...this.conversations]); return true; } return false; }; removeConversation = key => { const index = this.conversations.findIndex(item => item.key === key); if (index !== -1) { this.conversations.splice(index, 1); this.setConversations([...this.conversations]); return true; } return false; }; getMessages = key => { return chatMessagesStoreHelper.getMessages(key); }; getSnapshot = () => { return this.conversations; }; getActiveConversationKey = () => { return this.activeConversationKey; }; subscribe = callback => { this.listeners.push(callback); return () => { this.listeners = this.listeners.filter(listener => listener !== callback); }; }; destroy = () => { conversationStoreHelper.delete(this.storeKey); }; }