dsh-brain/src-client/panel/seat.ts

90 lines
2.2 KiB
TypeScript

// Adapted from dsh-mnemon (MIT), see vendor/dsh-mnemon/LICENSE.
// Minimal external-store / held-seat primitives used by the Brain panel seats.
export class ExternalStore<T> {
protected snapshot: T
private readonly listeners = new Set<() => void>()
constructor(initial: T) {
this.snapshot = initial
}
readonly getSnapshot = (): T => this.snapshot
readonly subscribe = (listener: () => void): (() => void) => {
this.listeners.add(listener)
return () => {
this.listeners.delete(listener)
}
}
protected get listenerCount(): number {
return this.listeners.size
}
protected setSnapshot(next: T, force = false): void {
if (!force && Object.is(next, this.snapshot)) return
this.snapshot = next
this.notify()
}
protected notify(): void {
for (const listener of [...this.listeners]) listener()
}
}
export class HeldSeat<T> extends ExternalStore<T | undefined> {
private owner: symbol | undefined
constructor() {
super(undefined)
}
protected hold(value: T): () => void {
const token = Symbol('held-seat')
this.owner = token
this.setSnapshot(value)
return () => {
if (this.owner !== token) return
this.owner = undefined
this.setSnapshot(undefined)
}
}
}
export interface RafCoalescer {
schedule(): void
flush(): void
cancel(): void
readonly pending: boolean
}
export function createRafCoalescer(run: () => void): RafCoalescer {
let frameId: number | undefined
let microtaskToken: object | undefined
return {
schedule(): void {
if (typeof requestAnimationFrame === 'function') {
if (frameId !== undefined) return
frameId = requestAnimationFrame(() => { frameId = undefined; run() })
return
}
if (microtaskToken !== undefined) return
microtaskToken = {}
queueMicrotask(() => { microtaskToken = undefined; run() })
},
flush(): void {
this.cancel()
run()
},
cancel(): void {
if (frameId !== undefined && typeof cancelAnimationFrame === 'function') cancelAnimationFrame(frameId)
frameId = undefined
microtaskToken = undefined
},
get pending(): boolean {
return frameId !== undefined || microtaskToken !== undefined
},
}
}