@plteam/chat-ui
Version:
CUI Kit is a free and open-source library for creating AI assistant chat interfaces, built with React, Material UI, and TypeScript
72 lines (71 loc) • 3.22 kB
JavaScript
import * as React from 'react';
import { ThreadModel } from '../../models';
import internalApi from './history/internalApi';
export const useApiRefInitialization = (apiManager, model, props) => {
React.useEffect(() => {
const getAllThreads = () => model.list.value.map(v => v.data);
const onChangeThread = async (threadId) => {
const threadModel = model.get(threadId);
model.currentThread.value = threadModel;
if (!!threadModel && !!threadModel.isLoadingFullData.value && !!props.getFullThread) {
let fullThread = props.getFullThread(threadModel.id);
if (fullThread instanceof Promise) {
fullThread = await fullThread;
}
if (fullThread) {
threadModel.setFullData(fullThread);
}
}
if (threadModel?.isLoadingFullData.value) {
threadModel.isLoadingFullData.value = false;
}
};
const openNewThread = (thread) => {
if (!thread.isNew) {
thread.isNew = true;
}
model.currentThread.value = model.createFromData(thread ?? ThreadModel.createEmptyData(), props.onUserMessageSent);
;
};
const handleDeleteThread = (id) => {
model.delete(id);
};
const getThreadById = (id) => {
return model.get(id);
};
const getCurrentThread = () => {
return model.currentThread.value?.data;
};
const setMenuDrawerOpen = (v) => {
model.menuDrawerOpen.value = v;
};
const setDeleteItem = (v) => {
model.deleteItem.value = v;
};
const setActiveTool = (v, threadId) => {
if (threadId) {
const thread = model.list.value.find((t) => t.id === threadId);
if (thread)
thread.tool.value = v;
}
else if (model.currentThread.value) {
model.currentThread.value.tool.value = v;
}
props.onToolChanged?.(v);
};
internalApi.value = { model };
apiManager.setMethod('setActiveTool', setActiveTool);
apiManager.setMethod('setMenuDrawerOpen', setMenuDrawerOpen);
apiManager.setMethod('setDeleteItem', setDeleteItem);
apiManager.setMethod('handleCreateNewThread', props.handleCreateNewThread ?? ThreadModel.createEmptyData);
apiManager.setMethod('onChangeCurrentThread', props.onChangeCurrentThread);
apiManager.setMethod('onThreadDeleted', props.onThreadDeleted);
apiManager.setMethod('onChangeThread', onChangeThread);
apiManager.setMethod('getAllThreads', getAllThreads);
apiManager.setMethod('openNewThread', openNewThread);
apiManager.setMethod('deleteThread', handleDeleteThread);
apiManager.setMethod('getCurrentThread', getCurrentThread);
apiManager.setMethod('getThreadById', getThreadById);
apiManager.setMethod('emitter', model.emitter.getMethods());
}, [props, model]);
};