-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathhooks.ts
87 lines (77 loc) · 2.66 KB
/
hooks.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
82
83
84
85
86
87
import { useState, useEffect } from 'react';
import {
addSilentListener,
getRingerMode,
setNativeSilenceCheckInterval,
setRingerMode,
} from './module';
import type { RingerModeType } from './types';
/**
* `useRingerMode` is a custom hook to get the current ringer mode of the device.
* It also provides a function to change the ringer mode. This hook is intended to be used in react components where ringer mode needs to be managed.
*
* @returns {Object} - Contains the current mode, any error occurred, and a function to set a new mode.
* @property {RingerModeType | undefined} mode - The current mode of the device's ringer.
* @property {any} error - Any error that occurred while getting or setting the ringer mode.
* @property {Function} setMode - Function to set a new ringer mode.
*
* @example
* ```ts
const { mode, setMode, error } = useRingerMode();
* ```
*/
export const useRingerMode = () => {
const [mode, setCurrentMode] = useState<RingerModeType | undefined>();
const [error, setError] = useState<any>(null);
useEffect(() => {
(async () => {
try {
const currentMode = await getRingerMode();
setCurrentMode(currentMode);
} catch (err: any) {
setError(err);
}
})();
}, []);
const setMode = async (newMode: RingerModeType) => {
setError(null);
try {
const currentMode = await setRingerMode(newMode);
setCurrentMode(currentMode);
} catch (err: any) {
setError(err);
}
};
return { mode, error, setMode };
};
/**
* `useSilentSwitch` is a custom hook to check if the iOS device is in silent mode.
*
* @param {number} nativeIntervalCheck - The native interval to check the status in seconds. Default is 2 seconds.
*
* @returns {Object | undefined} - Contains boolean properties `isMuted` and `initialQuery` on iOS. Returns `undefined` for the first call and on non-iOS platforms.
* @property {boolean} isMuted - Represents the ring/mute switch position.
* @property {boolean} initialQuery - Informs whether reported status is the very first one reported.
*
* @platform iOS
*
* @example
* ```ts
const { isMuted, initialQuery } = useSilentSwitch(nativeIntervalCheck?: number);
* ```
*/
export const useSilentSwitch = (nativeIntervalCheck?: number) => {
const [status, setStatus] = useState<
{ isMuted: boolean; initialQuery: boolean } | undefined
>();
if (nativeIntervalCheck) setNativeSilenceCheckInterval(nativeIntervalCheck);
useEffect(() => {
const silentListener = addSilentListener((event) => {
setStatus(event);
});
return function unmountSilentSwitchListener() {
silentListener.remove();
};
}, []);
return status;
};