-
Notifications
You must be signed in to change notification settings - Fork 1
/
device.tsx
79 lines (75 loc) · 2.67 KB
/
device.tsx
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 { BatteryInfo, Device as CapacitorDevice, DeviceInfo, GetLanguageCodeResult, LanguageTag } from '@capacitor/device';
import React, { createContext, useCallback, useContext, useEffect, useRef, useState } from 'react';
import { Id } from '@deep-foundation/deeplinks/imports/minilinks';
import { useDeep } from '@deep-foundation/deeplinks/imports/client';
import isEqual from 'lodash/isEqual';
import { useSaver } from './saver';
interface DeviceContext {
id?: Id;
name: string;
info: DeviceInfo | {};
battery: BatteryInfo | {};
language: string;
tag: string;
}
export const deviceContext = createContext<DeviceContext | null>(null);
export function useDevice() {
return useContext(deviceContext);
}
export function DeviceProvider({
children,
containerId,
interval = 1000,
saver = false,
}: {
children?: any;
containerId: Id;
interval?: number;
saver?: boolean;
}) {
const deep = useDeep();
const [device, setDevice] = useState<DeviceContext | null>(null);
const deviceRef = useRef<DeviceContext | null>(null);
const save = useSaver({
mode: 'device',
getType: () => deep.id('@deep-foundation/deepmemo-links', 'Device'),
});
const sync = useCallback(async (device: DeviceContext, containerId: Id) => {
if (deep && containerId) {
let { id, ...object } = device;
id = await save(object, id, object.name, containerId);
if (!deviceRef?.current?.id && !!id) {
deviceRef.current.id = id;
setDevice({ id, ...object });
}
}
}, []);
useEffect(() => {
const i = setInterval(async () => {
try {
const device: DeviceContext = {
...(deviceRef.current || {}),
name: (await CapacitorDevice.getId()).identifier,
info: await (async () => { try { return await CapacitorDevice.getInfo() } catch(e) { return {} }})(),
battery: await (async () => { try { return await CapacitorDevice.getBatteryInfo() } catch(e) { return {} }})(),
language: await (async () => { try { return (await CapacitorDevice.getLanguageCode()).value } catch(e) { return 'en' }})(),
tag: await (async () => { try { return (await CapacitorDevice.getLanguageTag()).value } catch(e) { return 'en' }})(),
};
if (!deviceRef.current || !isEqual(deviceRef.current, device) || !deviceRef?.current?.id) {
deviceRef.current = device;
setDevice(device);
}
} catch(e) {
}
}, interval);
return () => clearInterval(i);
}, []);
useEffect(() => {
!!device && saver && sync(device, containerId);
}, [device, saver, containerId]);
return <>
<deviceContext.Provider value={device}>
{children}
</deviceContext.Provider>
</>
}