UNPKG

@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

59 lines (58 loc) 1.95 kB
import { PromiseUtils } from '../../utils/PromiseUtils'; import { arrayChunk } from '../../utils/arrayUtils/arrayChunk'; import { randomInt } from '../../utils/numberUtils/randomInt'; export class ForceStream { _text; model; onPushTextPart; _promise; _stop = false; // пауза в ms между таймаутами speed = { max: 300, min: 100 }; // пауза в ms между таймаутами chunkSize = 'medium'; constructor(_text, model, onPushTextPart) { this._text = _text; this.model = model; this.onPushTextPart = onPushTextPart; } get promise() { return this._promise?.promise; } start = () => { const textChunk = this._text.split(' '); const rndSize = this.chunkSize === 'small' ? { min: 1, max: 4 } : this.chunkSize === 'medium' ? { min: 2, max: 6 } : { min: 4, max: 8 }; const chunk = arrayChunk(textChunk, () => randomInt(rndSize.min, rndSize.max)).map(v => v.join(' ')); this._promise = new PromiseUtils(); this._addTextPart(chunk); }; forceStop = () => { this._stop = true; if (this.model) this.model.typing.value = false; }; _addTextPart = (chunks) => { if (this._stop) return; const part = chunks[0]; const newChunks = chunks.slice(1); if (this.model) { this.model.text += `${part} `; } else if (this.onPushTextPart) { this.onPushTextPart(`${part} `); } if (newChunks.length && !this._stop) { setTimeout(() => this._addTextPart(newChunks), randomInt(100, 300)); } else { if (this.model) this.model.typing.value = false; this._promise?.resolve(true); } }; }