@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
53 lines (52 loc) • 1.7 kB
JavaScript
import { isDefined } from '../utils/isDefined';
import { arrayPluck } from '../utils/arrayUtils/arrayPluck';
const rootMessageHash = 'rootMessage';
/**
* TODO: Created in case the user needs to build a message tree in their own way
*/
export class ThreadBranchMapManager {
_mapObject = {};
_map = new Map();
_currentMapId = '';
pushValue = (messageId, parentId) => {
if (!parentId) {
parentId = rootMessageHash;
}
if (!this._mapObject[parentId]) {
this._mapObject[parentId] = [];
}
this._mapObject[parentId].push(messageId);
};
createDefaultMap = (messages) => {
this.clear();
for (const message of messages) {
this.pushValue(message.id, message.parentId);
}
return this;
};
createMap = (messages) => {
const newMapId = arrayPluck(messages, 'id').join('-');
if (newMapId === this._currentMapId)
return this._map;
this._currentMapId = newMapId;
this.clear();
this.createDefaultMap(messages);
this._map = this.getMap(messages);
return this._map;
};
getMap = (messages) => {
const map = new Map();
for (const parentId in this._mapObject) {
const parentMessages = this._mapObject[parentId]
.map(id => messages.find(m => m.id === id))
.filter(isDefined);
map.set(parentId, { messages: parentMessages });
}
return map;
};
clear = () => {
this._mapObject = {};
this._map = new Map();
this._currentMapId = '';
};
}