-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathindex.js
More file actions
59 lines (52 loc) · 1.56 KB
/
index.js
File metadata and controls
59 lines (52 loc) · 1.56 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
let cache = {}
let prefix = 'x'
const rules = []
let insert = rule => rules.push(rule)
const hyph = s => s.replace(/[A-Z]|^ms/g, '-$&').toLowerCase()
const mx = (rule, media) => media ? `${media}{${rule}}` : rule
const rx = (cn, prop, val) => `.${cn}{${hyph(prop)}:${val}}`
const noAnd = s => s.replace(/&/g, '')
const isDev = (process.env.NODE_ENV === 'development') || (!process.env.NODE_ENV)
const parse = (obj, child = '', media) =>
Object.keys(obj).map(key => {
const val = obj[key]
if (val === null) return ''
if (typeof val === 'object') {
const m2 = /^@/.test(key) ? key : null
const c2 = m2 ? child : child + key
return parse(val, c2, m2 || media)
}
const _key = key + val + child + media
if (cache[_key]) return cache[_key]
const className = prefix + (rules.length).toString(36)
insert(mx(rx(className + noAnd(child), key, val), media))
cache[_key] = className
return className
})
.join(' ')
function cxs (...styles) {
return styles
.map(style => parse(style))
.join(' ')
.trim()
}
cxs.css = () => rules.sort().join('')
cxs.reset = () => {
cache = {}
while (rules.length) rules.pop()
}
cxs.prefix = val => (prefix = val)
if (typeof document !== 'undefined') {
const sheet = document.head.appendChild(
document.createElement('style')
).sheet
insert = rule => {
rules.push(rule)
try{
sheet.insertRule(rule, rule.includes('@import') ? 0 : sheet.cssRules.length)
}catch(e){
if (isDev) console.warn('whoops, illegal rule inserted', rule)
}
}
}
export default cxs