forked from mobxjs/mobx
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintercept-utils.ts
More file actions
46 lines (41 loc) · 1.44 KB
/
Copy pathintercept-utils.ts
File metadata and controls
46 lines (41 loc) · 1.44 KB
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
import { Lambda, invariant, once, untrackedEnd, untrackedStart } from "../internal"
export type IInterceptor<T> = (change: T) => T | null
export interface IInterceptable<T> {
interceptors: IInterceptor<T>[] | undefined
intercept(handler: IInterceptor<T>): Lambda
}
export function hasInterceptors(interceptable: IInterceptable<any>) {
return interceptable.interceptors !== undefined && interceptable.interceptors.length > 0
}
export function registerInterceptor<T>(
interceptable: IInterceptable<T>,
handler: IInterceptor<T>
): Lambda {
const interceptors = interceptable.interceptors || (interceptable.interceptors = [])
interceptors.push(handler)
return once(() => {
const idx = interceptors.indexOf(handler)
if (idx !== -1) interceptors.splice(idx, 1)
})
}
export function interceptChange<T>(
interceptable: IInterceptable<T | null>,
change: T | null
): T | null {
const prevU = untrackedStart()
try {
const interceptors = interceptable.interceptors
if (interceptors)
for (let i = 0, l = interceptors.length; i < l; i++) {
change = interceptors[i](change)
invariant(
!change || (change as any).type,
"Intercept handlers should return nothing or a change object"
)
if (!change) break
}
return change
} finally {
untrackedEnd(prevU)
}
}