-
-
Notifications
You must be signed in to change notification settings - Fork 435
Expand file tree
/
Copy pathwebComponentStyleUtils.ts
More file actions
41 lines (36 loc) · 1.46 KB
/
webComponentStyleUtils.ts
File metadata and controls
41 lines (36 loc) · 1.46 KB
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
import {CREATE_ELEMENT} from '../consts/htmlConstants';
import {CustomStyle} from '../../types/styles';
export class WebComponentStyleUtils {
public static apply(style: string, shadowRoot: ShadowRoot | null) {
if (!shadowRoot) return;
try {
WebComponentStyleUtils.applyStyleSheet(style, shadowRoot);
} catch (_) {
// fallback for if CSSStyleSheet is not supported (Safari)
WebComponentStyleUtils.addStyleElement(style, shadowRoot);
}
}
private static applyStyleSheet(style: string, shadowRoot: ShadowRoot) {
const styleSheet = new CSSStyleSheet();
styleSheet.replaceSync(style);
shadowRoot.adoptedStyleSheets.push(styleSheet);
}
private static addStyleElement(style: string, shadowRoot: ShadowRoot) {
const stylesDocument = CREATE_ELEMENT('style') as HTMLStyleElement;
stylesDocument.innerHTML = style;
shadowRoot.appendChild(stylesDocument);
}
private static camelToKebab(str: string): string {
return str.replace(/[A-Z]/g, (match) => `-${match.toLowerCase()}`);
}
public static applyChatStyle(chatStyle: CustomStyle | undefined, shadowRoot: ShadowRoot | null) {
if (!chatStyle || !shadowRoot) return;
const declarations = Object.entries(chatStyle)
.filter(([, value]) => value)
.map(([key, value]) => `${WebComponentStyleUtils.camelToKebab(key)}: ${value};`)
.join(' ');
if (declarations) {
WebComponentStyleUtils.apply(`:host { ${declarations} }`, shadowRoot);
}
}
}