forked from react-native-community/hooks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseAccessibilityInfo.ts
79 lines (70 loc) · 2.1 KB
/
useAccessibilityInfo.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
import {useEffect, useState} from 'react'
import {AccessibilityInfo, AccessibilityChangeEventName} from 'react-native'
type AccessibilityInfoStaticInitializers =
| 'isBoldTextEnabled'
| 'isScreenReaderEnabled'
| 'isGrayscaleEnabled'
| 'isInvertColorsEnabled'
| 'isReduceMotionEnabled'
| 'isReduceTransparencyEnabled'
function useAccessibilityStateListener(
eventName: AccessibilityChangeEventName,
initializerName: AccessibilityInfoStaticInitializers,
) {
const [isEnabled, setIsEnabled] = useState<boolean | undefined>(undefined)
useEffect(() => {
if (!AccessibilityInfo[initializerName]) {
return
}
AccessibilityInfo[initializerName]().then(setIsEnabled)
const subscription = AccessibilityInfo.addEventListener(
eventName,
setIsEnabled,
)
return () => {
// @ts-expect-error - React Native >= 0.65
if (typeof subscription?.remove === 'function') {
// @ts-expect-error - need update @types/[email protected]
subscription.remove()
} else {
// React Native < 0.65
AccessibilityInfo.removeEventListener(eventName, setIsEnabled)
}
}
}, [eventName, initializerName])
return isEnabled
}
export function useAccessibilityInfo() {
const boldTextEnabled = useAccessibilityStateListener(
'boldTextChanged',
'isBoldTextEnabled',
)
const grayscaleEnabled = useAccessibilityStateListener(
'grayscaleChanged',
'isGrayscaleEnabled',
)
const invertColorsEnabled = useAccessibilityStateListener(
'invertColorsChanged',
'isInvertColorsEnabled',
)
const reduceMotionEnabled = useAccessibilityStateListener(
'reduceMotionChanged',
'isReduceMotionEnabled',
)
const reduceTransparencyEnabled = useAccessibilityStateListener(
'reduceTransparencyChanged',
'isReduceTransparencyEnabled',
)
const screenReaderEnabled = useAccessibilityStateListener(
'screenReaderChanged',
'isScreenReaderEnabled',
)
return {
screenReaderEnabled,
grayscaleEnabled,
invertColorsEnabled,
reduceMotionEnabled,
reduceTransparencyEnabled,
boldTextEnabled,
}
}