@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
36 lines (35 loc) • 1.01 kB
JavaScript
import { randomId } from '../numberUtils/randomInt';
export class ObservableReactValue {
_value;
debug;
_listeners = [];
constructor(_value, debug = false) {
this._value = _value;
this.debug = debug;
}
get value() {
return this._value;
}
set value(newValue) {
this.setValue(newValue);
}
setValue(newValue) {
if (this._value !== newValue) {
this._value = newValue;
if (this.debug)
console.trace('set new messages', newValue);
this._listeners.map(v => v.fn());
}
}
getSnapshot = () => this.value;
subscribe = (callback) => {
const key = `key${randomId()}`;
this._listeners.push({ key, fn: callback });
return () => {
const index = this._listeners.findIndex(v => v.key === key);
if (index >= 0) {
this._listeners.splice(index, 1);
}
};
};
}