export class Loader extends HTMLElement {
_loaded: number;
_total: number;
_initializing = false;
_error = "";
constructor() {
super();
this._loaded = 0;
this._total = 0;
this.attachShadow({ mode: "open" });
if (!this.shadowRoot) return;
this.shadowRoot.innerHTML = `
Loading file...
0.0 MB(0)%of?? MB
`;
}
get error() {
return this._error;
}
set error(value: string) {
this._error = value;
}
get loaded() {
return this._loaded;
}
set loaded(value: number) {
this._loaded = value;
}
get total() {
return this._total;
}
set total(value: number) {
this._total = value;
}
get value() {
return Math.round((this.loaded / this.total) * 100);
}
convertBytesToMegabytes(bytes: number) {
return (bytes / 1024 / 1024).toFixed(1);
}
update() {
if (!this.shadowRoot) return;
const bar = this.shadowRoot.querySelector(".progress-bar") as HTMLElement;
const text = this.shadowRoot.querySelector("#text") as HTMLElement;
const loadedText = this.shadowRoot.querySelector("#loaded") as HTMLElement;
const totalText = this.shadowRoot.querySelector("#total") as HTMLElement;
const percentageText = this.shadowRoot.querySelector("#percentage") as HTMLElement;
if (!bar) return;
const total = this.total;
requestAnimationFrame(() => {
// If an error occurred, show the error message and hide the progress bar
if (this._error) {
if (!text.classList.contains("error")) {
text.classList.add("error");
}
text.innerText = this._error;
return;
}
// Update the progress bar for decoding of chunks
if (this._initializing) {
loadedText.innerText = `${this.loaded}`;
totalText.innerText = `${this.total} chunks`;
percentageText.innerText = `(${this.value}%)`;
return;
}
// Indeterminate progress bar is given if no calculable total available.
if (total < 0) {
if (!bar.classList.contains("progress-bar-indeterminate")) bar.classList.add("progress-bar-indeterminate");
if (this.loaded > 0) {
loadedText.innerText = `${this.convertBytesToMegabytes(this.loaded)} MB`;
}
return;
}
const value = this.value;
// Finished loading, starting initialization
if (value === 100) {
this._initializing = true;
if (this.total > 0) {
loadedText.innerText = `${this.convertBytesToMegabytes(this.loaded)} MB`;
totalText.innerText = `${this.convertBytesToMegabytes(this.total)} MB`;
percentageText.innerText = `(${value}%)`;
}
text.innerText = "Initializing...";
bar.classList.add("progress-bar-indeterminate");
return;
}
// Update progress bar
bar.style.setProperty("--ls-loader-position", `${value - 100}%`);
if (value > 0) {
percentageText.innerText = `(${value}%)`;
}
if (this.loaded > 0) {
loadedText.innerText = `${this.convertBytesToMegabytes(this.loaded)} MB`;
}
if (this.total > 0) {
totalText.innerText = `${this.convertBytesToMegabytes(this.total)} MB`;
}
});
}
static get observedAttributes() {
return ["hidden"];
}
}
customElements.define("loading-progress-bar", Loader);