-
-
Notifications
You must be signed in to change notification settings - Fork 123
/
Copy pathuse-css-var.ts
126 lines (103 loc) · 2.7 KB
/
use-css-var.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
type ColorType = "hsla";
export type VarOptions = {
type: ColorType;
transparency?: number;
apply?: (value: string) => string;
};
export type Breakpoints = {
sm: boolean;
md: boolean;
lg: boolean;
xl: boolean;
xxl: boolean;
};
export function useBreakpoints(): Breakpoints {
const breakpoints: Breakpoints = reactive({
sm: false,
md: false,
lg: false,
xl: false,
xxl: false,
});
const updateBreakpoints = () => {
breakpoints.sm = window.innerWidth < 640;
breakpoints.md = window.innerWidth >= 640;
breakpoints.lg = window.innerWidth >= 768;
breakpoints.xl = window.innerWidth >= 1024;
breakpoints.xxl = window.innerWidth >= 1280;
};
onMounted(() => {
updateBreakpoints();
window.addEventListener("resize", updateBreakpoints);
});
onUnmounted(() => {
window.removeEventListener("resize", updateBreakpoints);
});
return breakpoints;
}
class ThemeObserver {
// eslint-disable-next-line no-use-before-define
private static instance?: ThemeObserver;
private readonly observer: MutationObserver;
private fns: (() => void)[] = [];
private constructor() {
this.observer = new MutationObserver(mutations => {
mutations.forEach(mutation => {
if (mutation.attributeName === "data-theme") {
this.fire();
}
});
});
const html = document.querySelector("html");
if (!html) {
throw new Error("No html element found");
}
this.observer.observe(html, { attributes: true });
}
public static getInstance() {
if (!ThemeObserver.instance) {
ThemeObserver.instance = new ThemeObserver();
}
return ThemeObserver.instance;
}
private fire() {
this.fns.forEach(fn => fn());
}
public add(fn: () => void) {
this.fns.push(fn);
}
public remove(fn: () => void) {
this.fns = this.fns.filter(f => f !== fn);
}
}
export function useCssVar(name: string, options?: VarOptions) {
if (!options) {
options = {
type: "hsla",
transparency: 1,
apply: undefined,
};
}
const cssVal = ref(getComputedStyle(document.documentElement).getPropertyValue(name).trim());
const update = () => {
cssVal.value = getComputedStyle(document.documentElement).getPropertyValue(name).trim();
};
ThemeObserver.getInstance().add(update);
onUnmounted(() => {
ThemeObserver.getInstance().remove(update);
});
switch (options.type) {
case "hsla": {
return computed(() => {
if (!document) {
return "";
}
let val = cssVal.value.trim().split(" ").join(", ");
if (options?.transparency) {
val += `, ${options.transparency}`;
}
return `hsla(${val})`;
});
}
}
}