2022-04-21 18:51:03 +02:00
|
|
|
import { Controller } from '@hotwired/stimulus';
|
|
|
|
import { debounce } from '@utils';
|
|
|
|
|
|
|
|
export type Detail = Record<string, unknown>;
|
|
|
|
|
|
|
|
export class ApplicationController extends Controller {
|
|
|
|
#debounced = new Map<() => void, () => void>();
|
|
|
|
|
|
|
|
protected debounce(fn: () => void, interval: number): void {
|
2022-10-24 20:15:09 +02:00
|
|
|
this.globalDispatch('debounced:added');
|
|
|
|
|
2022-04-21 18:51:03 +02:00
|
|
|
let debounced = this.#debounced.get(fn);
|
|
|
|
if (!debounced) {
|
2022-10-25 10:56:22 +02:00
|
|
|
const wrapper = () => {
|
2022-10-24 20:15:09 +02:00
|
|
|
fn.bind(this)();
|
|
|
|
this.#debounced.delete(fn);
|
|
|
|
if (this.#debounced.size == 0) {
|
|
|
|
this.globalDispatch('debounced:empty');
|
|
|
|
}
|
2022-10-25 10:56:22 +02:00
|
|
|
};
|
2022-10-24 20:15:09 +02:00
|
|
|
|
|
|
|
debounced = debounce(wrapper.bind(this), interval);
|
|
|
|
|
2022-04-21 18:51:03 +02:00
|
|
|
this.#debounced.set(fn, debounced);
|
|
|
|
}
|
|
|
|
debounced();
|
|
|
|
}
|
|
|
|
|
2022-05-06 19:44:33 +02:00
|
|
|
protected globalDispatch<T = Detail>(type: string, detail?: T): void {
|
2022-04-21 18:51:03 +02:00
|
|
|
this.dispatch(type, {
|
2022-08-31 15:57:37 +02:00
|
|
|
detail: detail as object,
|
2022-04-21 18:51:03 +02:00
|
|
|
prefix: '',
|
|
|
|
target: document.documentElement
|
|
|
|
});
|
|
|
|
}
|
2022-05-04 12:42:42 +02:00
|
|
|
|
|
|
|
protected on<HandlerEvent extends Event = Event>(
|
|
|
|
eventName: string,
|
|
|
|
handler: (event: HandlerEvent) => void
|
2022-05-06 19:44:33 +02:00
|
|
|
): void {
|
|
|
|
this.onTarget(this.element, eventName, handler);
|
|
|
|
}
|
|
|
|
|
|
|
|
protected onGlobal<HandlerEvent extends Event = Event>(
|
|
|
|
eventName: string,
|
|
|
|
handler: (event: HandlerEvent) => void
|
|
|
|
): void {
|
|
|
|
this.onTarget(document.documentElement, eventName, handler);
|
|
|
|
}
|
|
|
|
|
|
|
|
private onTarget<HandlerEvent extends Event = Event>(
|
|
|
|
target: EventTarget,
|
|
|
|
eventName: string,
|
|
|
|
handler: (event: HandlerEvent) => void
|
2022-05-04 12:42:42 +02:00
|
|
|
): void {
|
|
|
|
const disconnect = this.disconnect;
|
|
|
|
const callback = (event: Event): void => {
|
|
|
|
handler(event as HandlerEvent);
|
|
|
|
};
|
2022-05-06 19:44:33 +02:00
|
|
|
target.addEventListener(eventName, callback);
|
2022-05-04 12:42:42 +02:00
|
|
|
this.disconnect = () => {
|
2022-05-06 19:44:33 +02:00
|
|
|
target.removeEventListener(eventName, callback);
|
2022-05-04 12:42:42 +02:00
|
|
|
disconnect.call(this);
|
|
|
|
};
|
|
|
|
}
|
2022-04-21 18:51:03 +02:00
|
|
|
}
|