-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathhooks.ts
63 lines (50 loc) · 1.61 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
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
import { contrastColor } from './colorUtils';
/**
* Ref that will set the foreground color of an element to contrast with its
* background color.
*/
export function useContrastFgColorRef<
T extends HTMLElement,
>(): React.RefObject<T> {
const ref = useRef<T>(null);
useLayoutEffect(() => {
if (ref.current == null) {
return;
}
const computedStyle = getComputedStyle(ref.current);
const { backgroundColor } = computedStyle;
ref.current.style.color = contrastColor(backgroundColor);
}, []);
return ref;
}
/**
* Extract a --dh-color-xxxx variable from the pseudo content of an element.
* @param elementRef Ref to the element to extract the color from.
* @param pseudoElement The pseudo element to extract the color from.
*/
export function useDhColorFromPseudoContent(
elementRef: React.RefObject<HTMLElement | null>,
pseudoElement: ':before' | ':after'
): string | undefined {
const [color, setColor] = useState<string>();
useEffect(() => {
if (elementRef.current == null) {
return;
}
const pseudoContent = getComputedStyle(
elementRef.current,
pseudoElement
).getPropertyValue('content');
// Extract the var name from the content (e.g. '--dh-color-gray-900')
const dhColorVarName = /"(--dh-color-.*?)[,"]/.exec(pseudoContent)?.[1];
if (dhColorVarName == null) {
return;
}
const dhColorValue = getComputedStyle(elementRef.current).getPropertyValue(
dhColorVarName
);
setColor(dhColorValue);
}, [elementRef, pseudoElement]);
return color;
}