forked from SigNoz/signoz
-
Notifications
You must be signed in to change notification settings - Fork 0
/
useFontObserver.tsx
69 lines (61 loc) · 1.35 KB
/
useFontObserver.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
import FontFaceObserver from 'fontfaceobserver';
import { useEffect, useState } from 'react';
export interface FontFace {
family: string;
weight?:
| `light`
| `normal`
| `bold`
| `bolder`
| `100`
| `200`
| `300`
| `400`
| `500`
| `600`
| `700`
| `800`
| `900`;
style?: `normal` | `italic` | `oblique`;
stretch?:
| `normal`
| `ultra-condensed`
| `extra-condensed`
| `condensed`
| `semi-condensed`
| `semi-expanded`
| `expanded`
| `extra-expanded`
| `ultra-expanded`;
}
export interface Options {
testString?: string;
timeout?: number;
}
export interface Config {
showErrors: boolean;
}
function useFontFaceObserver(
fontFaces: FontFace[] = [],
isEnabled = true,
{ testString, timeout }: Options = {},
{ showErrors }: Config = { showErrors: false },
): boolean {
const [isResolved, setIsResolved] = useState(false);
const fontFacesString = JSON.stringify(fontFaces);
useEffect(() => {
if (isEnabled) {
const promises = JSON.parse(fontFacesString).map(
({ family, weight, style, stretch }: FontFace) =>
new FontFaceObserver(family, {
weight,
style,
stretch,
}).load(testString, timeout),
);
Promise.all(promises).then(() => setIsResolved(true));
}
}, [fontFacesString, testString, timeout, showErrors, isEnabled]);
return isResolved;
}
export default useFontFaceObserver;