shelving
Version:
Toolkit for using data in JavaScript.
45 lines (44 loc) • 1.56 kB
JavaScript
import { DataStore } from "../../store/DataStore.js";
import { SECOND } from "../../util/constants.js";
import { awaitDispose } from "../../util/dispose.js";
import { getRandomKey } from "../../util/random.js";
import { Timeout } from "../../util/timeout.js";
// Constants.
const TEMPORARY_NOTICE_MS = 5 * SECOND; // How long before notices hide themselves.
/** Store a single notice. */
export class NoticeStore extends DataStore {
_notices;
key = getRandomKey();
constructor(notices, children, status) {
super({ status, children });
this._notices = notices;
notices.add(this);
this._autoclose();
}
show(children, status = this.value.status) {
this.value = { children, status };
}
/** Close this notice (permanently). */
close() {
this._notices.delete(this);
}
// Override to automatically close this notice a few seconds after it's opened (after the user has had chance to read it).
write(data) {
super.write(data);
this._autoclose();
}
// Ping this to trigger auto-closing the notice.
_autoclose() {
const { status } = this.value;
if (status !== "loading")
this._timeout.set();
else
this._timeout.clear();
}
_timeout = new Timeout(() => this.close(), TEMPORARY_NOTICE_MS);
// Implement `AsyncDispose`
async [Symbol.asyncDispose]() {
await awaitDispose(() => this.close(), // Remove self from parent when we dispose.
super[Symbol.asyncDispose]());
}
}