mirror of
https://github.com/excalidraw/excalidraw.git
synced 2025-05-03 10:00:07 -04:00
First steps towards onIncrement API
This commit is contained in:
parent
192c4e7658
commit
0c21f1ae07
51 changed files with 1358 additions and 870 deletions
51
packages/common/src/emitter.ts
Normal file
51
packages/common/src/emitter.ts
Normal file
|
@ -0,0 +1,51 @@
|
|||
import type { UnsubscribeCallback } from "@excalidraw/excalidraw/types";
|
||||
|
||||
type Subscriber<T extends any[]> = (...payload: T) => void;
|
||||
|
||||
export class Emitter<T extends any[] = []> {
|
||||
public subscribers: Subscriber<T>[] = [];
|
||||
|
||||
/**
|
||||
* Attaches subscriber
|
||||
*
|
||||
* @returns unsubscribe function
|
||||
*/
|
||||
on(...handlers: Subscriber<T>[] | Subscriber<T>[][]): UnsubscribeCallback {
|
||||
const _handlers = handlers
|
||||
.flat()
|
||||
.filter((item) => typeof item === "function");
|
||||
|
||||
this.subscribers.push(..._handlers);
|
||||
|
||||
return () => this.off(_handlers);
|
||||
}
|
||||
|
||||
once(...handlers: Subscriber<T>[] | Subscriber<T>[][]): UnsubscribeCallback {
|
||||
const _handlers = handlers
|
||||
.flat()
|
||||
.filter((item) => typeof item === "function");
|
||||
|
||||
_handlers.push(() => detach());
|
||||
|
||||
const detach = this.on(..._handlers);
|
||||
return detach;
|
||||
}
|
||||
|
||||
off(...handlers: Subscriber<T>[] | Subscriber<T>[][]) {
|
||||
const _handlers = handlers.flat();
|
||||
this.subscribers = this.subscribers.filter(
|
||||
(handler) => !_handlers.includes(handler),
|
||||
);
|
||||
}
|
||||
|
||||
trigger(...payload: T) {
|
||||
for (const handler of this.subscribers) {
|
||||
handler(...payload);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
clear() {
|
||||
this.subscribers = [];
|
||||
}
|
||||
}
|
|
@ -9,3 +9,4 @@ export * from "./promise-pool";
|
|||
export * from "./random";
|
||||
export * from "./url";
|
||||
export * from "./utils";
|
||||
export * from "./emitter";
|
||||
|
|
|
@ -68,3 +68,8 @@ export type MaybePromise<T> = T | Promise<T>;
|
|||
|
||||
// get union of all keys from the union of types
|
||||
export type AllPossibleKeys<T> = T extends any ? keyof T : never;
|
||||
|
||||
/** Strip all the methods or functions from a type */
|
||||
export type DTO<T> = {
|
||||
[K in keyof T as T[K] extends Function ? never : K]: T[K];
|
||||
};
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue