@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
76 lines (75 loc) • 2.47 kB
JavaScript
import { ObservableReactValue } from "../utils/observers";
import getVideoPoster from "../utils/getVideoPoster";
import md5 from "md5";
import loadUrlFile from "../utils/loadUrlFile";
import { randomInt } from "../utils/numberUtils/randomInt";
const emptyFile = new File([''], 'empty');
class AttachmentModel {
_data;
progress = new ObservableReactValue(0);
error = new ObservableReactValue(undefined);
poster = new ObservableReactValue(undefined);
isLoading = new ObservableReactValue(true);
_file = emptyFile;
_id = randomInt(1, 1000);
_url = '';
constructor(_data) {
this._data = _data;
this._createSelf();
}
get id() { return this._id; }
get data() { return this._data; }
get file() { return this._file; }
get url() { return this._url; }
get type() { return this._data.type || 'file'; }
get name() { return this._file.name; }
get isGallery() { return this.type !== 'file'; }
_createPoster = async () => {
const img = document.createElement('img');
if (this._data.poster) {
img.src = this._data.poster;
}
else {
if (this.type.startsWith('image')) {
img.src = this._url;
}
if (this.type.startsWith('video')) {
img.src = await getVideoPoster(this._url);
}
}
img.onload = () => {
this.poster.value = img;
};
};
setProgress = (n) => { this.progress.value = n; };
setError = (e) => { this.error.value = e; };
setId = (id) => { this._id = id; };
get contentData() {
const data = {
id: this.id,
type: this.type,
file: this.file,
url: this._url,
poster: this.poster.value?.src,
};
return data;
}
_createSelf = async () => {
const { file, url, id } = this.data;
if (file) {
this._file = file;
this._url = URL.createObjectURL(this._file);
}
else if (url) {
const loadedFile = await loadUrlFile(url);
if (loadedFile) {
this._file = loadedFile;
this._url = url;
}
}
this._id = id || md5(this._url);
this.isLoading.value = false;
this._createPoster();
};
}
export default AttachmentModel;