UNPKG

2.09 kBJavaScriptView Raw
1import * as is from './is';
2import Style from './style';
3import { dash2camel } from './util';
4
5// a dummy stylesheet object that doesn't need a reference to the core
6// (useful for init)
7let Stylesheet = function(){
8 if( !(this instanceof Stylesheet) ){
9 return new Stylesheet();
10 }
11
12 this.length = 0;
13};
14
15let sheetfn = Stylesheet.prototype;
16
17sheetfn.instanceString = function(){
18 return 'stylesheet';
19};
20
21// just store the selector to be parsed later
22sheetfn.selector = function( selector ){
23 let i = this.length++;
24
25 this[ i ] = {
26 selector: selector,
27 properties: []
28 };
29
30 return this; // chaining
31};
32
33// just store the property to be parsed later
34sheetfn.css = function( name, value ){
35 let i = this.length - 1;
36
37 if( is.string( name ) ){
38 this[ i ].properties.push( {
39 name: name,
40 value: value
41 } );
42 } else if( is.plainObject( name ) ){
43 let map = name;
44 let propNames = Object.keys( map );
45
46 for( let j = 0; j < propNames.length; j++ ){
47 let key = propNames[ j ];
48 let mapVal = map[ key ];
49
50 if( mapVal == null ){ continue; }
51
52 let prop = Style.properties[key] || Style.properties[dash2camel(key)];
53
54 if( prop == null ){ continue; }
55
56 let name = prop.name;
57 let value = mapVal;
58
59 this[ i ].properties.push( {
60 name: name,
61 value: value
62 } );
63 }
64 }
65
66 return this; // chaining
67};
68
69sheetfn.style = sheetfn.css;
70
71// generate a real style object from the dummy stylesheet
72sheetfn.generateStyle = function( cy ){
73 let style = new Style( cy );
74
75 return this.appendToStyle( style );
76};
77
78// append a dummy stylesheet object on a real style object
79sheetfn.appendToStyle = function( style ){
80 for( let i = 0; i < this.length; i++ ){
81 let context = this[ i ];
82 let selector = context.selector;
83 let props = context.properties;
84
85 style.selector( selector ); // apply selector
86
87 for( let j = 0; j < props.length; j++ ){
88 let prop = props[ j ];
89
90 style.css( prop.name, prop.value ); // apply property
91 }
92 }
93
94 return style;
95};
96
97export default Stylesheet;