wkit/src/css.js

45 lines
947 B
JavaScript
Raw Normal View History

2023-03-06 19:20:23 +08:00
/**
* {}
* @author yutent<yutent.io@gmail.com>
* @date 2023/03/06 16:27:49
*/
2023-03-07 19:15:23 +08:00
import { RESET_CSS_STYLE } from './constants.js'
2023-03-06 19:20:23 +08:00
let MyCSSStyleSheet = CSSStyleSheet
if (!document.adoptedStyleSheets) {
MyCSSStyleSheet = class {
elem = document.createElement('style')
replaceSync(css) {
this.elem.textContent = css.replace(/\s+/g, ' ')
}
}
}
2023-03-06 19:20:23 +08:00
export function css(strs, ...args) {
2023-03-07 19:15:23 +08:00
let output = ''
2023-03-06 19:20:23 +08:00
let tmp = Array.from(strs)
while (tmp.length) {
output += tmp.shift() + (args.shift() || '')
}
return output
}
export function adoptStyles(root, styles = '') {
let sheet = new MyCSSStyleSheet()
2023-03-06 19:20:23 +08:00
if (typeof styles === 'string') {
styles = [styles]
} else {
styles = styles.flat(Infinity)
}
styles = (RESET_CSS_STYLE + styles.join(' ')).trim()
sheet.replaceSync(styles)
if (root.adoptedStyleSheets) {
root.adoptedStyleSheets.push(sheet)
} else {
root.appendChild(sheet.elem)
}
2023-03-06 19:20:23 +08:00
}