-
Notifications
You must be signed in to change notification settings - Fork 7
/
cssutil.ts
71 lines (61 loc) · 1.84 KB
/
cssutil.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
/*
* Philip Crotwell
* University of South Carolina, 2019
* https://www.seis.sc.edu
*/
export const AUTO_CLASSED = "autoseisplotjs";
export const AUTO_COLOR_SELECTOR = "seisplotjsautocolor";
export const G_DATA_SELECTOR = "seisplotjsdata";
/**
* Inserts text as css into the head of an html document. No checking
* as to validity of the css is done, just inserts a style
* element at the beginning of the head.
*
* @param cssText textual css for insertion
* @param id optional id for style element
* @returns the style html element inserted
*/
export function insertCSS(cssText: string, id: string): HTMLElement {
const head = document.head;
if (head === null) {
throw new Error("document.head is null");
}
if (id) {
for (const c of Array.from(head.children)) {
// only remove if a <style> element, classed with autoseisplotjs and same id within head
if (isIdStyleElement(c, id)) {
// null check for flow
if (typeof c.parentNode !== "undefined" && c.parentNode !== null) {
c.parentNode.removeChild(c);
}
break;
}
}
}
const styleElement = document.createElement("style");
if (id) {
styleElement.id = id;
}
styleElement.type = "text/css";
styleElement.classList.add(AUTO_CLASSED);
styleElement.appendChild(document.createTextNode(cssText));
head.insertBefore(styleElement, head.firstChild);
return styleElement;
}
export function isCSSInserted(id: string): boolean {
const head = document.head;
if (head === null) {
throw new Error("document.head is null");
}
for (const c of Array.from(head.children)) {
if (isIdStyleElement(c, id)) {
return true;
}
}
return false;
}
export function isIdStyleElement(c: Element, id: string): boolean {
return (
c.localName === "style" && c.id === id && c.classList.contains(AUTO_CLASSED)
);
}