-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
128 lines (99 loc) · 2.54 KB
/
index.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
import {
asyncState,
on_destroy,
toReadable,
toWritable,
unstore,
} from "@sveu/shared"
import { support } from "../support"
interface UserAgentData {
mobile: boolean
architecture: string
model: string
platform: string
platformVersion: string
bitness: string
brands: UserAgentDataBrand[]
}
interface UserAgentDataBrand {
name: string
version: string
}
/**
* Get user agent
*
* @remarks This function use the User-Agent Client Hints api. See https://developer.mozilla.org/en-US/docs/Web/API/NavigatorUAData
*
* @example
* ```ts
* const { supported, mobile, arch, model, platform, platformVersion, bitness, brands } = useragent()
* ```
* @returns
* - `supported` - Whether the browser supports the User-Agent Client Hints api.
* - `mobile` - Whether the device is a mobile device.
* - `arch` - The architecture of the device.
* - `model` - The model of the device.
* - `platform` - The platform of the device.
* - `platformVersion` - The platform version of the device.
* - `bitness` - The bitness of the device.
* - `brands` - The brands of the device.
*
*/
export function useragent() {
const mobile = toWritable(false)
const arch = toWritable("")
const model = toWritable("")
const platform = toWritable("")
const platformVersion = toWritable("")
const bitness = toWritable("")
const brands = toWritable<UserAgentDataBrand[]>([{ name: "", version: "" }])
const supported = support("userAgentData")
if (unstore(supported)) {
const { state } = asyncState<UserAgentData>(
// @ts-expect-error navigator.userAgentData is not supported in all browsers
navigator.userAgentData.getHighEntropyValues([
"architecture",
"model",
"platform",
"platformVersion",
"bitness",
]),
{
mobile: false,
architecture: "",
model: "",
platform: "",
platformVersion: "",
bitness: "",
brands: [{ name: "", version: "" }],
}
)
const unsubscribe = state.subscribe((v) => {
if (!v) return
mobile.set(v.mobile)
arch.set(v.architecture)
model.set(v.model)
platform.set(v.platform)
platformVersion.set(v.platformVersion)
bitness.set(v.bitness)
const _brands = v.brands.map((b: any) => {
return {
name: b.brand,
version: b.version,
}
})
brands.set(_brands)
})
on_destroy(unsubscribe)
}
return {
supported,
brands: toReadable(brands),
mobile: toReadable(mobile),
arch: toReadable(arch),
model: toReadable(model),
platform: toReadable(platform),
platformVersion: toReadable(platformVersion),
bitness: toReadable(bitness),
}
}