forked from radmen/css.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
89 lines (79 loc) · 1.98 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
/*
css.js - Dynamic stylesheets
https://github.com/radmen/css.js
Copyright (c) 2012 Radoslaw Mejer <[email protected]>
*/
function extend(extendedVar, object) {
for (var key in object) {
if (object.hasOwnProperty(key)) {
extendedVar[key] = object[key];
}
}
};
function Selector(name, sheet) {
this.name = name;
this.sheet = sheet;
this.props = {};
this.node = document.createTextNode('');
}
Selector.prototype.getName = function() {
return this.name;
};
Selector.prototype.properties = function(properties) {
if (!properties) {
return this.props;
}
extend(this.props, properties);
var parts = [];
for (var name in this.props) {
if (this.props.hasOwnProperty(name)) {
parts.push(name + ":" + this.props[name]);
}
}
this.node.nodeValue = this.name + " { " + (parts.join(';')) + "; }";
return this;
};
Selector.prototype.remove = function() {
return this.sheet.remove(this);
};
function Sheet() {
this.node = document.createElement('style');
this.node.type = 'text/css';
this.selectors = {};
document.head.appendChild(this.node);
}
Sheet.prototype.selector = function(name, properties) {
var selector;
if (!this.selectors[name]) {
selector = this.selectors[name] = new Selector(name, this);
this.node.appendChild(selector.node);
} else {
selector = this.selectors[name];
}
if (properties) {
selector.properties(properties);
return this;
}
return selector;
};
Sheet.prototype.remove = function(selector) {
if (!selector) {
this.node.parentNode.removeChild(this.node);
delete this.properties;
return null;
}
if (typeof selector === 'string' && this.selectors[selector]) {
this.node.removeChild(this.selectors[selector].node);
delete this.selectors[selector];
}
if (typeof selector === 'object') {
this.node.removeChild(selector.node);
delete this.selectors[selector.getName()];
}
return this;
};
module.exports = {
newSheet: function() {
return new Sheet();
}
};