-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
57 lines (55 loc) · 1.76 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
function caseConverter(str: string): string {
if (str.length === 0) return str;
const isUppercase = str[0] === str[0].toUpperCase();
const result = str
.split(/(?=[A-Z])/)
.join("-")
.toLowerCase();
return isUppercase ? `-${result}` : result;
}
export function toCss(obj: any): string {
if (!obj || typeof obj !== "object" || Array.isArray(obj)) {
throw new TypeError(
`expected an argument of type object, but got ${typeof obj}`
);
}
let lines: string[] = [];
for (let index = 0; index < Object.keys(obj).length; index++) {
const id = Object.keys(obj)[index];
const key = caseConverter(id);
const value = obj[id];
if (typeof value === "object") {
const text = toCss(value);
lines.push(`${id}{${text}}`);
} else {
lines.push(`${key}:${value};`);
}
}
return lines.join("");
}
export function injectStyle(
textOrObject: string | object,
id?: string,
overridable = true,
hostElement: HTMLElement = document.head
) {
if (!textOrObject || Array.isArray(textOrObject)) return;
if (typeof textOrObject === 'string' && textOrObject.length === 0) return;
if (id) {
let oldStyle = document.getElementById(id);
if (oldStyle) {
let isStyleTag = oldStyle.tagName.toLowerCase() === "style";
if (!isStyleTag) {
throw new Error("The provided id does not indicate a style tag.");
} else if (isStyleTag && overridable) {
oldStyle.innerHTML = typeof textOrObject === "object" ? toCss(textOrObject) : textOrObject;
}
return;
}
}
let style = document.createElement("style");
style.type = "text/css";
style.innerHTML = typeof textOrObject === "object" ? toCss(textOrObject) : textOrObject;
if (id) style.id = id;
hostElement.appendChild(style);
}