-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
disposables.ts
81 lines (69 loc) · 2.09 KB
/
disposables.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
78
79
80
81
import { microTask } from './micro-task'
export type Disposables = ReturnType<typeof disposables>
export function disposables() {
let _disposables: Function[] = []
let api = {
addEventListener<TEventName extends keyof WindowEventMap>(
element: HTMLElement | Window | Document,
name: TEventName,
listener: (event: WindowEventMap[TEventName]) => any,
options?: boolean | AddEventListenerOptions
) {
element.addEventListener(name, listener as any, options)
return api.add(() => element.removeEventListener(name, listener as any, options))
},
requestAnimationFrame(...args: Parameters<typeof requestAnimationFrame>) {
let raf = requestAnimationFrame(...args)
api.add(() => cancelAnimationFrame(raf))
},
nextFrame(...args: Parameters<typeof requestAnimationFrame>) {
api.requestAnimationFrame(() => {
api.requestAnimationFrame(...args)
})
},
setTimeout(...args: Parameters<typeof setTimeout>) {
let timer = setTimeout(...args)
api.add(() => clearTimeout(timer))
},
microTask(...args: Parameters<typeof microTask>) {
let task = { current: true }
microTask(() => {
if (task.current) {
args[0]()
}
})
return api.add(() => {
task.current = false
})
},
style(node: HTMLElement, property: string, value: string) {
let previous = node.style.getPropertyValue(property)
Object.assign(node.style, { [property]: value })
return this.add(() => {
Object.assign(node.style, { [property]: previous })
})
},
group(cb: (d: typeof this) => void) {
let d = disposables()
cb(d)
return this.add(() => d.dispose())
},
add(cb: () => void) {
_disposables.push(cb)
return () => {
let idx = _disposables.indexOf(cb)
if (idx >= 0) {
for (let dispose of _disposables.splice(idx, 1)) {
dispose()
}
}
}
},
dispose() {
for (let dispose of _disposables.splice(0)) {
dispose()
}
},
}
return api
}