-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathuseVtEvents.ts
77 lines (68 loc) · 2.15 KB
/
useVtEvents.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import type { Coordinates } from './useDraggable';
/**
* Event name mapping to the payload of the type.
*/
type EventMap = {
vtDragFinished: { id: string; position: Coordinates };
vtBeingDragged: { id: string; position: Coordinates };
vtDragStarted: { id: string; position: Coordinates };
vtDismissed: { id: string };
vtStarted: { id: string };
vtFinished: { id: string };
vtLoadStop: { id: string };
vtPromptResponse: { id: string; response: any };
vtPaused: { id: string };
vtResumed: { id: string };
};
export type EventName = keyof EventMap;
type Events = {
on: <T extends EventName>(event: T, callback: (payload: EventMap[T]) => void) => void;
once: <T extends EventName>(event: T, callback: (payload: EventMap[T]) => void) => void;
off: <T extends EventName>(event: T, callback?: (payload: EventMap[T]) => void) => void;
emit: <T extends EventName>(event: T, payload: EventMap[T]) => void;
};
const events: Record<keyof EventMap, CallableFunction[]> = {
vtDragFinished: [],
vtBeingDragged: [],
vtDragStarted: [],
vtDismissed: [],
vtStarted: [],
vtFinished: [],
vtLoadStop: [],
vtPromptResponse: [],
vtPaused: [],
vtResumed: []
};
export default function useVtEvents(): Events {
return {
on(event, callback) {
if (!events[event]) {
events[event] = [];
}
events[event].push(callback);
},
once(event, callback) {
const onceCallback = (payload: EventMap[typeof event]) => {
callback(payload);
this.off(event, onceCallback);
};
this.on(event, onceCallback);
},
off(event, callback) {
if (!events[event]) {
return;
}
if (callback) {
events[event] = events[event].filter(cb => cb !== callback);
} else {
events[event] = [];
}
},
emit(event, payload) {
if (!events[event]) {
return;
}
events[event].forEach(callback => callback(payload));
}
};
}