-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
99 lines (85 loc) · 2.08 KB
/
index.js
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
'use strict'
var inserted = {}
var session = {}
var is_client = typeof window === 'object'
/**
* insert css inside head tag. and return a function to remove css and cached
* @param {string} css css rules string
* @param {object} options
* @return {function} remove the style element and cached css
*/
exports = module.exports = function(css, options) {
return insert(inserted, css, options)
}
/**
* same as module.exports. This for server side rendering
* if called inside a session.
* @param {string} css css rules string
* @param {object} options
* @return {function} remove the style element and cached css
*/
exports.session = function(css, options) {
return insert(session, css, options)
}
/**
* return css strings in array
* @return {array}
*/
exports.getCss = getCss
function getCss() {
return Object.keys(inserted).concat(Object.keys(session))
}
exports.cleanAllCss = function() {
cleanStore(inserted)
cleanStore(session)
}
exports.getCssAndResetSess = function() {
var css = getCss()
cleanStore(session)
return css
}
exports.cleanSessCss = function() {
cleanStore(session)
}
function cleanStore(store) {
var arr = Object.keys(store)
for (var i = 0, len = arr.length; i < len; ++i) {
var fn = store[arr[i]]
delete store[arr[i]]
fn()
}
}
function insert(store, css, options) {
if (!css) return nop
if (store[css]) return store[css]
store[css] = removeCss
var elm = null
var head = null
if (is_client) {
elm = document.createElement('style')
elm.setAttribute('type', 'text/css')
if ('textContent' in elm) {
elm.textContent = css
}
else {
elm.styleSheet.cssText = css
}
head = document.getElementsByTagName('head')[0]
if (options && options.prepend) {
head.insertBefore(elm, head.childNodes[0])
}
else {
head.appendChild(elm)
}
}
var called = false // avoid double call
return removeCss
function removeCss() {
if (called) return
called = true
delete store[css]
if (!is_client) return
head.removeChild(elm)
}
}
function nop(){ }