style-to-object 0.1.0 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,7 +1,53 @@
1
- # Change Log
1
+ # Changelog
2
2
 
3
3
  All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
4
4
 
5
+ ### [0.2.3](https://github.com/remarkablemark/style-to-object/compare/v0.2.2...v0.2.3) (2019-06-22)
6
+
7
+
8
+ ### Build System
9
+
10
+ * **package:** add field "files" and remove `.npmignore` ([fdf3966](https://github.com/remarkablemark/style-to-object/commit/fdf3966))
11
+ * **package:** update script `build:min` to generate sourcemap ([a13be58](https://github.com/remarkablemark/style-to-object/commit/a13be58))
12
+ * **package:** upgrade devDependencies ([377bb40](https://github.com/remarkablemark/style-to-object/commit/377bb40))
13
+ * **rollup:** remove `uglify-es` from config as it's unneeded ([b0951e0](https://github.com/remarkablemark/style-to-object/commit/b0951e0))
14
+
15
+
16
+ ### Tests
17
+
18
+ * organize and rename describe blocks ([8d4c004](https://github.com/remarkablemark/style-to-object/commit/8d4c004))
19
+ * organize data (test suites) into cases, errors, and invalids ([513732b](https://github.com/remarkablemark/style-to-object/commit/513732b))
20
+ * rename `test/cases.js` to `test/data.js` ([75d084d](https://github.com/remarkablemark/style-to-object/commit/75d084d))
21
+ * **data:** add more test cases and errors ([c9242c7](https://github.com/remarkablemark/style-to-object/commit/c9242c7))
22
+ * **data:** refactor test data from object to array format ([1a07a38](https://github.com/remarkablemark/style-to-object/commit/1a07a38))
23
+
24
+
25
+
26
+ <a name="0.2.2"></a>
27
+ ## [0.2.2](https://github.com/remarkablemark/style-to-object/compare/v0.2.1...v0.2.2) (2018-09-13)
28
+
29
+
30
+
31
+ <a name="0.2.1"></a>
32
+ ## [0.2.1](https://github.com/remarkablemark/style-to-object/compare/v0.2.0...v0.2.1) (2018-05-09)
33
+
34
+
35
+ ### Bug Fixes
36
+
37
+ * **package:** upgrade css@2.2.3 which resolves security vulnerability ([d8b94c0](https://github.com/remarkablemark/style-to-object/commit/d8b94c0))
38
+
39
+
40
+
41
+ <a name="0.2.0"></a>
42
+ # [0.2.0](https://github.com/remarkablemark/style-to-object/compare/v0.1.0...v0.2.0) (2017-11-26)
43
+
44
+
45
+ ### Features
46
+
47
+ * **parser:** add optional argument iterator ([a3deea8](https://github.com/remarkablemark/style-to-object/commit/a3deea8))
48
+
49
+
50
+
5
51
  <a name="0.1.0"></a>
6
52
  # 0.1.0 (2017-11-23)
7
53
 
package/README.md CHANGED
@@ -6,27 +6,35 @@
6
6
  [![Build Status](https://travis-ci.org/remarkablemark/style-to-object.svg?branch=master)](https://travis-ci.org/remarkablemark/style-to-object)
7
7
  [![Coverage Status](https://coveralls.io/repos/github/remarkablemark/style-to-object/badge.svg?branch=master)](https://coveralls.io/github/remarkablemark/style-to-object?branch=master)
8
8
  [![Dependency status](https://david-dm.org/remarkablemark/style-to-object.svg)](https://david-dm.org/remarkablemark/style-to-object)
9
+ [![NPM downloads](https://img.shields.io/npm/dm/style-to-object.svg?style=flat-square)](https://www.npmjs.com/package/style-to-object)
9
10
 
10
11
  Parses inline style to object:
11
12
 
12
13
  ```js
13
14
  var parser = require('style-to-object');
14
15
  parser('color: #C0FFEE; background: #BADA55;');
15
- // { color: "#C0FFEE", background: "#BADA55" }
16
16
  ```
17
17
 
18
+ Output:
19
+
20
+ ```js
21
+ { color: '#C0FFEE', background: '#BADA55' }
22
+ ```
23
+
24
+ [JSFiddle](https://jsfiddle.net/remarkablemark/ykz2meot/) | [Repl.it](https://repl.it/@remarkablemark/style-to-object) | [Examples](https://github.com/remarkablemark/style-to-object/tree/master/examples)
25
+
18
26
  ## Installation
19
27
 
20
28
  [NPM](https://www.npmjs.com/package/style-to-object):
21
29
 
22
30
  ```sh
23
- npm install style-to-object --save
31
+ $ npm install style-to-object --save
24
32
  ```
25
33
 
26
34
  [Yarn](https://yarn.fyi/style-to-object):
27
35
 
28
36
  ```sh
29
- yarn add style-to-object
37
+ $ yarn add style-to-object
30
38
  ```
31
39
 
32
40
  [CDN](https://unpkg.com/style-to-object/):
@@ -34,7 +42,7 @@ yarn add style-to-object
34
42
  ```html
35
43
  <script src="https://unpkg.com/style-to-object@latest/dist/style-to-object.min.js"></script>
36
44
  <script>
37
- var parser = window.StyleToObject;
45
+ window.StyleToObject(/* string */);
38
46
  </script>
39
47
  ```
40
48
 
@@ -43,60 +51,152 @@ yarn add style-to-object
43
51
  Import the module:
44
52
 
45
53
  ```js
54
+ // CommonJS
55
+ const parse = require('style-to-object');
56
+
46
57
  // ES Modules
47
- import parser from 'style-to-object';
58
+ import parse from 'style-to-object';
48
59
  ```
49
60
 
50
61
  Parse single declaration:
51
62
 
52
63
  ```js
53
- parse(`
54
- color: #f00
55
- `);
56
- // { color: '#f00' }
64
+ parse('line-height: 42');
65
+ ```
66
+
67
+ Output:
68
+
69
+ ```js
70
+ { 'line-height': '42' }
57
71
  ```
58
72
 
59
73
  Parse multiple declarations:
60
74
 
61
75
  ```js
62
76
  parse(`
63
- color: #f00;
64
- z-index: 42;
77
+ border-color: #ACE;
78
+ z-index: 1337;
65
79
  `);
66
- // { color: '#f00', 'z-index': '42' }
80
+ ```
81
+
82
+ Output:
83
+
84
+ ```js
85
+ { 'border-color': '#ACE', 'z-index': '1337' }
67
86
  ```
68
87
 
69
88
  Parse unknown declarations:
70
89
 
71
90
  ```js
72
- parse(`
73
- foo: bar;
74
- `);
75
- // { foo: 'bar' }
91
+ parse('answer: 42;');
92
+ ```
93
+
94
+ Output:
95
+
96
+ ```js
97
+ { 'answer': '42' }
76
98
  ```
77
99
 
78
- Invalid declarations:
100
+ Invalid declarations/arguments:
79
101
 
80
102
  ```js
81
- parse(1); // null
82
- parse('top:'); // null
83
103
  parse(`
84
104
  top: ;
85
105
  right: 1em;
86
106
  `); // { right: '1em' }
107
+
108
+ parse(); // null
109
+ parse(null); // null
110
+ parse(1); // null
111
+ parse(true); // null
112
+ parse('top:'); // null
113
+ parse(':12px'); // null
114
+ parse(':'); // null
115
+ parse(';'); // null
116
+
87
117
  parse('top'); // throws Error
118
+ parse('/*'); // throws Error
119
+ ```
120
+
121
+ ### Iterator
122
+
123
+ If the 2nd argument is a function, then the parser will return `null`:
124
+
125
+ ```js
126
+ parse('color: #f00', function() {}); // null
127
+ ```
128
+
129
+ But the function will iterate through each declaration:
130
+
131
+ ```js
132
+ parser('color: #f00', function(name, value, declaration) {
133
+ console.log(name); // 'color'
134
+ console.log(value); // '#f00'
135
+ console.log(declaration); // { type: 'declaration', property: 'color', value: '#f00' }
136
+ });
137
+ ```
138
+
139
+ This makes it easy to customize the output:
140
+
141
+ ```js
142
+ const style = `
143
+ color: red;
144
+ background: blue;
145
+ `;
146
+ const output = [];
147
+ function iterator(name, value) {
148
+ output.push([name, value]);
149
+ }
150
+ parse(style, iterator);
151
+ console.log(output); // [['color', 'red'], ['background', 'blue']]
88
152
  ```
89
153
 
90
154
  ## Testing
91
155
 
156
+ Run tests:
157
+
92
158
  ```sh
93
159
  $ npm test
160
+ ```
161
+
162
+ Run tests in watch mode:
163
+
164
+ ```sh
165
+ $ npm run test:watch
166
+ ```
167
+
168
+ Run tests with coverage:
169
+
170
+ ```sh
171
+ $ npm run test:coverage
172
+ # npm run test:coverage:report
173
+ ```
174
+
175
+ Lint files:
176
+
177
+ ```sh
94
178
  $ npm run lint
95
179
  ```
96
180
 
181
+ Fix lint errors:
182
+
183
+ ```sh
184
+ $ npm run lint:fix
185
+ ```
186
+
187
+ ## Release
188
+
189
+ Only collaborators with credentials can release and publish:
190
+
191
+ ```sh
192
+ $ npm run release
193
+ $ git push --follow-tags && npm publish
194
+ ```
195
+
97
196
  ## Special Thanks
98
197
 
99
- - [css](https://github.com/reworkcss/css)
198
+ - [inline-style-parser](https://github.com/remarkablemark/inline-style-parser)
199
+ - [Contributors](https://github.com/remarkablemark/style-to-object/graphs/contributors)
100
200
 
101
201
  ## License
102
202
 
@@ -1,637 +1,308 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
3
- typeof define === 'function' && define.amd ? define(factory) :
4
- (global.StyleToObject = factory());
5
- }(this, (function () { 'use strict';
6
-
7
- // http://www.w3.org/TR/CSS21/grammar.html
8
- // https://github.com/visionmedia/css-parse/pull/49#issuecomment-30088027
9
- var commentre = /\/\*[^*]*\*+([^/*][^*]*\*+)*\//g;
10
-
11
- var parse = function(css, options){
12
- options = options || {};
13
-
14
- /**
15
- * Positional.
16
- */
17
-
18
- var lineno = 1;
19
- var column = 1;
20
-
21
- /**
22
- * Update lineno and column based on `str`.
23
- */
24
-
25
- function updatePosition(str) {
26
- var lines = str.match(/\n/g);
27
- if (lines) lineno += lines.length;
28
- var i = str.lastIndexOf('\n');
29
- column = ~i ? str.length - i : column + str.length;
30
- }
31
-
32
- /**
33
- * Mark position and patch `node.position`.
34
- */
35
-
36
- function position() {
37
- var start = { line: lineno, column: column };
38
- return function(node){
39
- node.position = new Position(start);
40
- whitespace();
41
- return node;
42
- };
43
- }
44
-
45
- /**
46
- * Store position information for a node
47
- */
48
-
49
- function Position(start) {
50
- this.start = start;
51
- this.end = { line: lineno, column: column };
52
- this.source = options.source;
53
- }
54
-
55
- /**
56
- * Non-enumerable source string
57
- */
58
-
59
- Position.prototype.content = css;
60
-
61
- /**
62
- * Error `msg`.
63
- */
64
-
65
- var errorsList = [];
66
-
67
- function error(msg) {
68
- var err = new Error(options.source + ':' + lineno + ':' + column + ': ' + msg);
69
- err.reason = msg;
70
- err.filename = options.source;
71
- err.line = lineno;
72
- err.column = column;
73
- err.source = css;
74
-
75
- if (options.silent) {
76
- errorsList.push(err);
77
- } else {
78
- throw err;
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
3
+ typeof define === 'function' && define.amd ? define(factory) :
4
+ (global = global || self, global.StyleToObject = factory());
5
+ }(this, function () { 'use strict';
6
+
7
+ // http://www.w3.org/TR/CSS21/grammar.html
8
+ // https://github.com/visionmedia/css-parse/pull/49#issuecomment-30088027
9
+ var COMMENT_REGEX = /\/\*[^*]*\*+([^/*][^*]*\*+)*\//g;
10
+
11
+ var NEWLINE_REGEX = /\n/g;
12
+ var WHITESPACE_REGEX = /^\s*/;
13
+
14
+ // declaration
15
+ var PROPERTY_REGEX = /^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/;
16
+ var COLON_REGEX = /^:\s*/;
17
+ var VALUE_REGEX = /^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/;
18
+ var SEMICOLON_REGEX = /^[;\s]*/;
19
+
20
+ // https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/Trim#Polyfill
21
+ var TRIM_REGEX = /^\s+|\s+$/g;
22
+
23
+ // strings
24
+ var NEWLINE = '\n';
25
+ var FORWARD_SLASH = '/';
26
+ var ASTERISK = '*';
27
+ var EMPTY_STRING = '';
28
+
29
+ // types
30
+ var TYPE_COMMENT = 'comment';
31
+ var TYPE_DECLARATION = 'declaration';
32
+
33
+ /**
34
+ * @param {String} style
35
+ * @param {Object} [options]
36
+ * @return {Object[]}
37
+ * @throws {TypeError}
38
+ * @throws {Error}
39
+ */
40
+ var inlineStyleParser = function(style, options) {
41
+ if (typeof style !== 'string') {
42
+ throw new TypeError('First argument must be a string');
79
43
  }
80
- }
81
-
82
- /**
83
- * Parse stylesheet.
84
- */
85
-
86
- function stylesheet() {
87
- var rulesList = rules();
88
-
89
- return {
90
- type: 'stylesheet',
91
- stylesheet: {
92
- rules: rulesList,
93
- parsingErrors: errorsList
94
- }
95
- };
96
- }
97
-
98
- /**
99
- * Opening brace.
100
- */
101
44
 
102
- function open() {
103
- return match(/^{\s*/);
104
- }
105
-
106
- /**
107
- * Closing brace.
108
- */
109
-
110
- function close() {
111
- return match(/^}/);
112
- }
113
-
114
- /**
115
- * Parse ruleset.
116
- */
117
-
118
- function rules() {
119
- var node;
120
- var rules = [];
121
- whitespace();
122
- comments(rules);
123
- while (css.length && css.charAt(0) != '}' && (node = atrule() || rule())) {
124
- if (node !== false) {
125
- rules.push(node);
126
- comments(rules);
127
- }
45
+ if (!style) return [];
46
+
47
+ options = options || {};
48
+
49
+ /**
50
+ * Positional.
51
+ */
52
+ var lineno = 1;
53
+ var column = 1;
54
+
55
+ /**
56
+ * Update lineno and column based on `str`.
57
+ *
58
+ * @param {String} str
59
+ */
60
+ function updatePosition(str) {
61
+ var lines = str.match(NEWLINE_REGEX);
62
+ if (lines) lineno += lines.length;
63
+ var i = str.lastIndexOf(NEWLINE);
64
+ column = ~i ? str.length - i : column + str.length;
128
65
  }
129
- return rules;
130
- }
131
66
 
132
- /**
133
- * Match `re` and return captures.
134
- */
135
-
136
- function match(re) {
137
- var m = re.exec(css);
138
- if (!m) return;
139
- var str = m[0];
140
- updatePosition(str);
141
- css = css.slice(str.length);
142
- return m;
143
- }
144
-
145
- /**
146
- * Parse whitespace.
147
- */
148
-
149
- function whitespace() {
150
- match(/^\s*/);
151
- }
67
+ /**
68
+ * Mark position and patch `node.position`.
69
+ *
70
+ * @return {Function}
71
+ */
72
+ function position() {
73
+ var start = { line: lineno, column: column };
74
+ return function(node) {
75
+ node.position = new Position(start);
76
+ whitespace();
77
+ return node;
78
+ };
79
+ }
152
80
 
153
- /**
154
- * Parse comments;
155
- */
81
+ /**
82
+ * Store position information for a node.
83
+ *
84
+ * @constructor
85
+ * @property {Object} start
86
+ * @property {Object} end
87
+ * @property {undefined|String} source
88
+ */
89
+ function Position(start) {
90
+ this.start = start;
91
+ this.end = { line: lineno, column: column };
92
+ this.source = options.source;
93
+ }
156
94
 
157
- function comments(rules) {
158
- var c;
159
- rules = rules || [];
160
- while (c = comment()) {
161
- if (c !== false) {
162
- rules.push(c);
95
+ /**
96
+ * Non-enumerable source string.
97
+ */
98
+ Position.prototype.content = style;
99
+
100
+ /**
101
+ * Error `msg`.
102
+ *
103
+ * @param {String} msg
104
+ * @throws {Error}
105
+ */
106
+ function error(msg) {
107
+ var err = new Error(
108
+ options.source + ':' + lineno + ':' + column + ': ' + msg
109
+ );
110
+ err.reason = msg;
111
+ err.filename = options.source;
112
+ err.line = lineno;
113
+ err.column = column;
114
+ err.source = style;
115
+
116
+ if (options.silent) ; else {
117
+ throw err;
163
118
  }
164
119
  }
165
- return rules;
166
- }
167
120
 
168
- /**
169
- * Parse comment.
170
- */
171
-
172
- function comment() {
173
- var pos = position();
174
- if ('/' != css.charAt(0) || '*' != css.charAt(1)) return;
175
-
176
- var i = 2;
177
- while ("" != css.charAt(i) && ('*' != css.charAt(i) || '/' != css.charAt(i + 1))) ++i;
178
- i += 2;
179
-
180
- if ("" === css.charAt(i-1)) {
181
- return error('End of comment missing');
121
+ /**
122
+ * Match `re` and return captures.
123
+ *
124
+ * @param {RegExp} re
125
+ * @return {undefined|Array}
126
+ */
127
+ function match(re) {
128
+ var m = re.exec(style);
129
+ if (!m) return;
130
+ var str = m[0];
131
+ updatePosition(str);
132
+ style = style.slice(str.length);
133
+ return m;
182
134
  }
183
135
 
184
- var str = css.slice(2, i - 2);
185
- column += 2;
186
- updatePosition(str);
187
- css = css.slice(i);
188
- column += 2;
189
-
190
- return pos({
191
- type: 'comment',
192
- comment: str
193
- });
194
- }
195
-
196
- /**
197
- * Parse selector.
198
- */
199
-
200
- function selector() {
201
- var m = match(/^([^{]+)/);
202
- if (!m) return;
203
- /* @fix Remove all comments from selectors
204
- * http://ostermiller.org/findcomment.html */
205
- return trim(m[0])
206
- .replace(/\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*\/+/g, '')
207
- .replace(/"(?:\\"|[^"])*"|'(?:\\'|[^'])*'/g, function(m) {
208
- return m.replace(/,/g, '\u200C');
209
- })
210
- .split(/\s*(?![^(]*\)),\s*/)
211
- .map(function(s) {
212
- return s.replace(/\u200C/g, ',');
213
- });
214
- }
215
-
216
- /**
217
- * Parse declaration.
218
- */
219
-
220
- function declaration() {
221
- var pos = position();
222
-
223
- // prop
224
- var prop = match(/^(\*?[-#\/\*\\\w]+(\[[0-9a-z_-]+\])?)\s*/);
225
- if (!prop) return;
226
- prop = trim(prop[0]);
227
-
228
- // :
229
- if (!match(/^:\s*/)) return error("property missing ':'");
230
-
231
- // val
232
- var val = match(/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^\)]*?\)|[^};])+)/);
233
-
234
- var ret = pos({
235
- type: 'declaration',
236
- property: prop.replace(commentre, ''),
237
- value: val ? trim(val[0]).replace(commentre, '') : ''
238
- });
239
-
240
- // ;
241
- match(/^[;\s]*/);
242
-
243
- return ret;
244
- }
245
-
246
- /**
247
- * Parse declarations.
248
- */
249
-
250
- function declarations() {
251
- var decls = [];
252
-
253
- if (!open()) return error("missing '{'");
254
- comments(decls);
136
+ /**
137
+ * Parse whitespace.
138
+ */
139
+ function whitespace() {
140
+ match(WHITESPACE_REGEX);
141
+ }
255
142
 
256
- // declarations
257
- var decl;
258
- while (decl = declaration()) {
259
- if (decl !== false) {
260
- decls.push(decl);
261
- comments(decls);
143
+ /**
144
+ * Parse comments.
145
+ *
146
+ * @param {Object[]} [rules]
147
+ * @return {Object[]}
148
+ */
149
+ function comments(rules) {
150
+ var c;
151
+ rules = rules || [];
152
+ while ((c = comment())) {
153
+ if (c !== false) {
154
+ rules.push(c);
155
+ }
262
156
  }
157
+ return rules;
263
158
  }
264
159
 
265
- if (!close()) return error("missing '}'");
266
- return decls;
267
- }
160
+ /**
161
+ * Parse comment.
162
+ *
163
+ * @return {Object}
164
+ * @throws {Error}
165
+ */
166
+ function comment() {
167
+ var pos = position();
168
+ if (FORWARD_SLASH != style.charAt(0) || ASTERISK != style.charAt(1)) return;
169
+
170
+ var i = 2;
171
+ while (
172
+ EMPTY_STRING != style.charAt(i) &&
173
+ (ASTERISK != style.charAt(i) || FORWARD_SLASH != style.charAt(i + 1))
174
+ ) {
175
+ ++i;
176
+ }
177
+ i += 2;
268
178
 
269
- /**
270
- * Parse keyframe.
271
- */
179
+ if (EMPTY_STRING === style.charAt(i - 1)) {
180
+ return error('End of comment missing');
181
+ }
272
182
 
273
- function keyframe() {
274
- var m;
275
- var vals = [];
276
- var pos = position();
183
+ var str = style.slice(2, i - 2);
184
+ column += 2;
185
+ updatePosition(str);
186
+ style = style.slice(i);
187
+ column += 2;
277
188
 
278
- while (m = match(/^((\d+\.\d+|\.\d+|\d+)%?|[a-z]+)\s*/)) {
279
- vals.push(m[1]);
280
- match(/^,\s*/);
189
+ return pos({
190
+ type: TYPE_COMMENT,
191
+ comment: str
192
+ });
281
193
  }
282
194
 
283
- if (!vals.length) return;
284
-
285
- return pos({
286
- type: 'keyframe',
287
- values: vals,
288
- declarations: declarations()
289
- });
290
- }
195
+ /**
196
+ * Parse declaration.
197
+ *
198
+ * @return {Object}
199
+ * @throws {Error}
200
+ */
201
+ function declaration() {
202
+ var pos = position();
291
203
 
292
- /**
293
- * Parse keyframes.
294
- */
204
+ // prop
205
+ var prop = match(PROPERTY_REGEX);
206
+ if (!prop) return;
207
+ comment();
295
208
 
296
- function atkeyframes() {
297
- var pos = position();
298
- var m = match(/^@([-\w]+)?keyframes\s*/);
209
+ // :
210
+ if (!match(COLON_REGEX)) return error("property missing ':'");
299
211
 
300
- if (!m) return;
301
- var vendor = m[1];
212
+ // val
213
+ var val = match(VALUE_REGEX);
302
214
 
303
- // identifier
304
- var m = match(/^([-\w]+)\s*/);
305
- if (!m) return error("@keyframes missing name");
306
- var name = m[1];
215
+ var ret = pos({
216
+ type: TYPE_DECLARATION,
217
+ property: trim(prop[0].replace(COMMENT_REGEX, EMPTY_STRING)),
218
+ value: val
219
+ ? trim(val[0].replace(COMMENT_REGEX, EMPTY_STRING))
220
+ : EMPTY_STRING
221
+ });
307
222
 
308
- if (!open()) return error("@keyframes missing '{'");
223
+ // ;
224
+ match(SEMICOLON_REGEX);
309
225
 
310
- var frame;
311
- var frames = comments();
312
- while (frame = keyframe()) {
313
- frames.push(frame);
314
- frames = frames.concat(comments());
226
+ return ret;
315
227
  }
316
228
 
317
- if (!close()) return error("@keyframes missing '}'");
318
-
319
- return pos({
320
- type: 'keyframes',
321
- name: name,
322
- vendor: vendor,
323
- keyframes: frames
324
- });
325
- }
326
-
327
- /**
328
- * Parse supports.
329
- */
330
-
331
- function atsupports() {
332
- var pos = position();
333
- var m = match(/^@supports *([^{]+)/);
334
-
335
- if (!m) return;
336
- var supports = trim(m[1]);
337
-
338
- if (!open()) return error("@supports missing '{'");
339
-
340
- var style = comments().concat(rules());
341
-
342
- if (!close()) return error("@supports missing '}'");
343
-
344
- return pos({
345
- type: 'supports',
346
- supports: supports,
347
- rules: style
348
- });
349
- }
350
-
351
- /**
352
- * Parse host.
353
- */
354
-
355
- function athost() {
356
- var pos = position();
357
- var m = match(/^@host\s*/);
358
-
359
- if (!m) return;
360
-
361
- if (!open()) return error("@host missing '{'");
362
-
363
- var style = comments().concat(rules());
364
-
365
- if (!close()) return error("@host missing '}'");
366
-
367
- return pos({
368
- type: 'host',
369
- rules: style
370
- });
371
- }
372
-
373
- /**
374
- * Parse media.
375
- */
376
-
377
- function atmedia() {
378
- var pos = position();
379
- var m = match(/^@media *([^{]+)/);
380
-
381
- if (!m) return;
382
- var media = trim(m[1]);
383
-
384
- if (!open()) return error("@media missing '{'");
385
-
386
- var style = comments().concat(rules());
387
-
388
- if (!close()) return error("@media missing '}'");
389
-
390
- return pos({
391
- type: 'media',
392
- media: media,
393
- rules: style
394
- });
395
- }
396
-
397
-
398
- /**
399
- * Parse custom-media.
400
- */
401
-
402
- function atcustommedia() {
403
- var pos = position();
404
- var m = match(/^@custom-media\s+(--[^\s]+)\s*([^{;]+);/);
405
- if (!m) return;
406
-
407
- return pos({
408
- type: 'custom-media',
409
- name: trim(m[1]),
410
- media: trim(m[2])
411
- });
412
- }
413
-
414
- /**
415
- * Parse paged media.
416
- */
417
-
418
- function atpage() {
419
- var pos = position();
420
- var m = match(/^@page */);
421
- if (!m) return;
422
-
423
- var sel = selector() || [];
424
-
425
- if (!open()) return error("@page missing '{'");
426
- var decls = comments();
229
+ /**
230
+ * Parse declarations.
231
+ *
232
+ * @return {Object[]}
233
+ */
234
+ function declarations() {
235
+ var decls = [];
236
+
237
+ comments(decls);
238
+
239
+ // declarations
240
+ var decl;
241
+ while ((decl = declaration())) {
242
+ if (decl !== false) {
243
+ decls.push(decl);
244
+ comments(decls);
245
+ }
246
+ }
427
247
 
428
- // declarations
429
- var decl;
430
- while (decl = declaration()) {
431
- decls.push(decl);
432
- decls = decls.concat(comments());
248
+ return decls;
433
249
  }
434
250
 
435
- if (!close()) return error("@page missing '}'");
436
-
437
- return pos({
438
- type: 'page',
439
- selectors: sel,
440
- declarations: decls
441
- });
442
- }
443
-
444
- /**
445
- * Parse document.
446
- */
447
-
448
- function atdocument() {
449
- var pos = position();
450
- var m = match(/^@([-\w]+)?document *([^{]+)/);
451
- if (!m) return;
452
-
453
- var vendor = trim(m[1]);
454
- var doc = trim(m[2]);
455
-
456
- if (!open()) return error("@document missing '{'");
457
-
458
- var style = comments().concat(rules());
459
-
460
- if (!close()) return error("@document missing '}'");
461
-
462
- return pos({
463
- type: 'document',
464
- document: doc,
465
- vendor: vendor,
466
- rules: style
467
- });
468
- }
251
+ whitespace();
252
+ return declarations();
253
+ };
469
254
 
470
255
  /**
471
- * Parse font-face.
256
+ * Trim `str`.
257
+ *
258
+ * @param {String} str
259
+ * @return {String}
472
260
  */
473
-
474
- function atfontface() {
475
- var pos = position();
476
- var m = match(/^@font-face\s*/);
477
- if (!m) return;
478
-
479
- if (!open()) return error("@font-face missing '{'");
480
- var decls = comments();
481
-
482
- // declarations
483
- var decl;
484
- while (decl = declaration()) {
485
- decls.push(decl);
486
- decls = decls.concat(comments());
487
- }
488
-
489
- if (!close()) return error("@font-face missing '}'");
490
-
491
- return pos({
492
- type: 'font-face',
493
- declarations: decls
494
- });
261
+ function trim(str) {
262
+ return str ? str.replace(TRIM_REGEX, EMPTY_STRING) : EMPTY_STRING;
495
263
  }
496
264
 
497
265
  /**
498
- * Parse import
499
- */
500
-
501
- var atimport = _compileAtrule('import');
502
-
503
- /**
504
- * Parse charset
505
- */
506
-
507
- var atcharset = _compileAtrule('charset');
508
-
509
- /**
510
- * Parse namespace
511
- */
512
-
513
- var atnamespace = _compileAtrule('namespace');
514
-
515
- /**
516
- * Parse non-block at-rules
517
- */
518
-
519
-
520
- function _compileAtrule(name) {
521
- var re = new RegExp('^@' + name + '\\s*([^;]+);');
522
- return function() {
523
- var pos = position();
524
- var m = match(re);
525
- if (!m) return;
526
- var ret = { type: name };
527
- ret[name] = m[1].trim();
528
- return pos(ret);
266
+ * Parses inline style to object.
267
+ *
268
+ * @example
269
+ * // returns { 'line-height': '42' }
270
+ * StyleToObject('line-height: 42;');
271
+ *
272
+ * @param {String} style - The inline style.
273
+ * @param {Function} [iterator] - The iterator function.
274
+ * @return {null|Object}
275
+ */
276
+ function StyleToObject(style, iterator) {
277
+ var output = null;
278
+ if (!style || typeof style !== 'string') {
279
+ return output;
529
280
  }
530
- }
531
-
532
- /**
533
- * Parse at rule.
534
- */
535
-
536
- function atrule() {
537
- if (css[0] != '@') return;
538
-
539
- return atkeyframes()
540
- || atmedia()
541
- || atcustommedia()
542
- || atsupports()
543
- || atimport()
544
- || atcharset()
545
- || atnamespace()
546
- || atdocument()
547
- || atpage()
548
- || athost()
549
- || atfontface();
550
- }
551
-
552
- /**
553
- * Parse rule.
554
- */
555
281
 
556
- function rule() {
557
- var pos = position();
558
- var sel = selector();
559
-
560
- if (!sel) return error('selector missing');
561
- comments();
562
-
563
- return pos({
564
- type: 'rule',
565
- selectors: sel,
566
- declarations: declarations()
567
- });
568
- }
569
-
570
- return addParent(stylesheet());
571
- };
572
-
573
- /**
574
- * Trim `str`.
575
- */
576
-
577
- function trim(str) {
578
- return str ? str.replace(/^\s+|\s+$/g, '') : '';
579
- }
580
-
581
- /**
582
- * Adds non-enumerable parent node reference to each node.
583
- */
584
-
585
- function addParent(obj, parent) {
586
- var isNode = obj && typeof obj.type === 'string';
587
- var childParent = isNode ? obj : parent;
588
-
589
- for (var k in obj) {
590
- var value = obj[k];
591
- if (Array.isArray(value)) {
592
- value.forEach(function(v) { addParent(v, childParent); });
593
- } else if (value && typeof value === 'object') {
594
- addParent(value, childParent);
282
+ var declaration;
283
+ var declarations = inlineStyleParser(style);
284
+ var hasIterator = typeof iterator === 'function';
285
+ var property;
286
+ var value;
287
+
288
+ for (var i = 0, len = declarations.length; i < len; i++) {
289
+ declaration = declarations[i];
290
+ property = declaration.property;
291
+ value = declaration.value;
292
+
293
+ if (hasIterator) {
294
+ iterator(property, value, declaration);
295
+ } else if (value) {
296
+ output || (output = {});
297
+ output[property] = value;
298
+ }
595
299
  }
596
- }
597
300
 
598
- if (isNode) {
599
- Object.defineProperty(obj, 'parent', {
600
- configurable: true,
601
- writable: true,
602
- enumerable: false,
603
- value: parent || null
604
- });
301
+ return output;
605
302
  }
606
303
 
607
- return obj;
608
- }
609
-
610
- /**
611
- * Parses inline style to object (server).
612
- *
613
- * Example: 'color:red' => { color: 'red' }
614
- *
615
- * @param {String} style
616
- * @return {Object|null}
617
- */
618
- var styleToObject = function parseInlineStyleServer(style) {
619
- if (!style || typeof style !== 'string') return null;
620
-
621
- // make sure to wrap declarations in placeholder
622
- var declarations = parse('p{' + style + '}').stylesheet.rules[0].declarations;
623
- var output = {};
624
-
625
- declarations.forEach(function(declaration) {
626
- var value = declaration.value;
627
- if (value) {
628
- output[declaration.property] = value;
629
- }
630
- });
631
-
632
- return output;
633
- };
304
+ var styleToObject = StyleToObject;
634
305
 
635
- return styleToObject;
306
+ return styleToObject;
636
307
 
637
- })));
308
+ }));
@@ -1 +1,2 @@
1
- !function(r,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):r.StyleToObject=e()}(this,function(){"use strict";function r(r){return r?r.replace(/^\s+|\s+$/g,""):""}function e(r,n){var t=r&&"string"==typeof r.type,i=t?r:n;for(var s in r){var a=r[s];Array.isArray(a)?a.forEach(function(r){e(r,i)}):a&&"object"==typeof a&&e(a,i)}return t&&Object.defineProperty(r,"parent",{configurable:!0,writable:!0,enumerable:!1,value:n||null}),r}var n=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g;return function(t){if(!t||"string"!=typeof t)return null;var i={};return function(t,i){function s(r){var e=r.match(/\n/g);e&&(A+=e.length);var n=r.lastIndexOf("\n");b=~n?r.length-n:b+r.length}function a(){var r={line:A,column:b};return function(e){return e.position=new u(r),l(),e}}function u(r){this.start=r,this.end={line:A,column:b},this.source=i.source}function o(r){var e=new Error(i.source+":"+A+":"+b+": "+r);if(e.reason=r,e.filename=i.source,e.line=A,e.column=b,e.source=t,!i.silent)throw e;k.push(e)}function c(){return m(/^{\s*/)}function f(){return m(/^}/)}function p(){var e,n=[];for(l(),v(n);t.length&&"}"!=t.charAt(0)&&(e=function(){if("@"==t[0])return function(){var r=a(),e=m(/^@([-\w]+)?keyframes\s*/);if(e){var n=e[1];if(!(e=m(/^([-\w]+)\s*/)))return o("@keyframes missing name");var t=e[1];if(!c())return o("@keyframes missing '{'");for(var i,s=v();i=h();)s.push(i),s=s.concat(v());return f()?r({type:"keyframes",name:t,vendor:n,keyframes:s}):o("@keyframes missing '}'")}}()||function(){var e=a(),t=m(/^@media *([^{]+)/);if(t){var i=r(t[1]);if(!c())return o("@media missing '{'");var s=v().concat(n());return f()?e({type:"media",media:i,rules:s}):o("@media missing '}'")}}()||function(){var e=a(),n=m(/^@custom-media\s+(--[^\s]+)\s*([^{;]+);/);if(n)return e({type:"custom-media",name:r(n[1]),media:r(n[2])})}()||function(){var e=a(),t=m(/^@supports *([^{]+)/);if(t){var i=r(t[1]);if(!c())return o("@supports missing '{'");var s=v().concat(n());return f()?e({type:"supports",supports:i,rules:s}):o("@supports missing '}'")}}()||E()||x()||j()||function(){var e=a(),t=m(/^@([-\w]+)?document *([^{]+)/);if(t){var i=r(t[1]),s=r(t[2]);if(!c())return o("@document missing '{'");var u=v().concat(n());return f()?e({type:"document",document:s,vendor:i,rules:u}):o("@document missing '}'")}}()||function(){var r=a();if(m(/^@page */)){var e=g()||[];if(!c())return o("@page missing '{'");for(var n,t=v();n=y();)t.push(n),t=t.concat(v());return f()?r({type:"page",selectors:e,declarations:t}):o("@page missing '}'")}}()||function(){var r=a();if(m(/^@host\s*/)){if(!c())return o("@host missing '{'");var e=v().concat(n());return f()?r({type:"host",rules:e}):o("@host missing '}'")}}()||function(){var r=a();if(m(/^@font-face\s*/)){if(!c())return o("@font-face missing '{'");for(var e,n=v();e=y();)n.push(e),n=n.concat(v());return f()?r({type:"font-face",declarations:n}):o("@font-face missing '}'")}}()}()||function(){var r=a(),e=g();return e?(v(),r({type:"rule",selectors:e,declarations:d()})):o("selector missing")}());)!1!==e&&(n.push(e),v(n));return n}function m(r){var e=r.exec(t);if(e){var n=e[0];return s(n),t=t.slice(n.length),e}}function l(){m(/^\s*/)}function v(r){var e;for(r=r||[];e=function(){var r=a();if("/"==t.charAt(0)&&"*"==t.charAt(1)){for(var e=2;""!=t.charAt(e)&&("*"!=t.charAt(e)||"/"!=t.charAt(e+1));)++e;if(e+=2,""===t.charAt(e-1))return o("End of comment missing");var n=t.slice(2,e-2);return b+=2,s(n),t=t.slice(e),b+=2,r({type:"comment",comment:n})}}();)!1!==e&&r.push(e);return r}function g(){var e=m(/^([^{]+)/);if(e)return r(e[0]).replace(/\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*\/+/g,"").replace(/"(?:\\"|[^"])*"|'(?:\\'|[^'])*'/g,function(r){return r.replace(/,/g,"‌")}).split(/\s*(?![^(]*\)),\s*/).map(function(r){return r.replace(/\u200C/g,",")})}function y(){var e=a(),t=m(/^(\*?[-#\/\*\\\w]+(\[[0-9a-z_-]+\])?)\s*/);if(t){if(t=r(t[0]),!m(/^:\s*/))return o("property missing ':'");var i=m(/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^\)]*?\)|[^};])+)/),s=e({type:"declaration",property:t.replace(n,""),value:i?r(i[0]).replace(n,""):""});return m(/^[;\s]*/),s}}function d(){var r=[];if(!c())return o("missing '{'");v(r);for(var e;e=y();)!1!==e&&(r.push(e),v(r));return f()?r:o("missing '}'")}function h(){for(var r,e=[],n=a();r=m(/^((\d+\.\d+|\.\d+|\d+)%?|[a-z]+)\s*/);)e.push(r[1]),m(/^,\s*/);if(e.length)return n({type:"keyframe",values:e,declarations:d()})}function w(r){var e=new RegExp("^@"+r+"\\s*([^;]+);");return function(){var n=a(),t=m(e);if(t){var i={type:r};return i[r]=t[1].trim(),n(i)}}}i=i||{};var A=1,b=1;u.prototype.content=t;var k=[],E=w("import"),x=w("charset"),j=w("namespace");return e({type:"stylesheet",stylesheet:{rules:p(),parsingErrors:k}})}("p{"+t+"}").stylesheet.rules[0].declarations.forEach(function(r){var e=r.value;e&&(i[r.property]=e)}),i}});
1
+ !function(n,r){"object"==typeof exports&&"undefined"!=typeof module?module.exports=r():"function"==typeof define&&define.amd?define(r):(n=n||self).StyleToObject=r()}(this,function(){"use strict";var m=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,g=/\n/g,y=/^\s*/,d=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,w=/^:\s*/,A=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,x=/^[;\s]*/,r=/^\s+|\s+$/g,b="";function E(n){return n?n.replace(r,b):b}return function(n,r){var t,e=null;if(!n||"string"!=typeof n)return e;for(var o,i,u=function(e,t){if("string"!=typeof e)throw new TypeError("First argument must be a string");if(!e)return[];t=t||{};var o=1,i=1;function u(n){var r=n.match(g);r&&(o+=r.length);var t=n.lastIndexOf("\n");i=~t?n.length-t:i+n.length}function c(){var r={line:o,column:i};return function(n){return n.position=new f(r),l(),n}}function f(n){this.start=n,this.end={line:o,column:i},this.source=t.source}function a(n){var r=new Error(t.source+":"+o+":"+i+": "+n);if(r.reason=n,r.filename=t.source,r.line=o,r.column=i,r.source=e,!t.silent)throw r}function s(n){var r=n.exec(e);if(r){var t=r[0];return u(t),e=e.slice(t.length),r}}function l(){s(y)}function p(n){var r;for(n=n||[];r=h();)!1!==r&&n.push(r);return n}function h(){var n=c();if("/"==e.charAt(0)&&"*"==e.charAt(1)){for(var r=2;b!=e.charAt(r)&&("*"!=e.charAt(r)||"/"!=e.charAt(r+1));)++r;if(r+=2,b===e.charAt(r-1))return a("End of comment missing");var t=e.slice(2,r-2);return i+=2,u(t),e=e.slice(r),i+=2,n({type:"comment",comment:t})}}function v(){var n=c(),r=s(d);if(r){if(h(),!s(w))return a("property missing ':'");var t=s(A),e=n({type:"declaration",property:E(r[0].replace(m,b)),value:t?E(t[0].replace(m,b)):b});return s(x),e}}return f.prototype.content=e,l(),function(){var n,r=[];for(p(r);n=v();)!1!==n&&(r.push(n),p(r));return r}()}(n),c="function"==typeof r,f=0,a=u.length;f<a;f++)o=(t=u[f]).property,i=t.value,c?r(o,i,t):i&&((e=e||{})[o]=i);return e}});
2
+ //# sourceMappingURL=style-to-object.min.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"style-to-object.min.js","sources":["../node_modules/inline-style-parser/index.js","../index.js"],"sourcesContent":["// http://www.w3.org/TR/CSS21/grammar.html\n// https://github.com/visionmedia/css-parse/pull/49#issuecomment-30088027\nvar COMMENT_REGEX = /\\/\\*[^*]*\\*+([^/*][^*]*\\*+)*\\//g;\n\nvar NEWLINE_REGEX = /\\n/g;\nvar WHITESPACE_REGEX = /^\\s*/;\n\n// declaration\nvar PROPERTY_REGEX = /^(\\*?[-#/*\\\\\\w]+(\\[[0-9a-z_-]+\\])?)\\s*/;\nvar COLON_REGEX = /^:\\s*/;\nvar VALUE_REGEX = /^((?:'(?:\\\\'|.)*?'|\"(?:\\\\\"|.)*?\"|\\([^)]*?\\)|[^};])+)/;\nvar SEMICOLON_REGEX = /^[;\\s]*/;\n\n// https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/Trim#Polyfill\nvar TRIM_REGEX = /^\\s+|\\s+$/g;\n\n// strings\nvar NEWLINE = '\\n';\nvar FORWARD_SLASH = '/';\nvar ASTERISK = '*';\nvar EMPTY_STRING = '';\n\n// types\nvar TYPE_COMMENT = 'comment';\nvar TYPE_DECLARATION = 'declaration';\n\n/**\n * @param {String} style\n * @param {Object} [options]\n * @return {Object[]}\n * @throws {TypeError}\n * @throws {Error}\n */\nmodule.exports = function(style, options) {\n if (typeof style !== 'string') {\n throw new TypeError('First argument must be a string');\n }\n\n if (!style) return [];\n\n options = options || {};\n\n /**\n * Positional.\n */\n var lineno = 1;\n var column = 1;\n\n /**\n * Update lineno and column based on `str`.\n *\n * @param {String} str\n */\n function updatePosition(str) {\n var lines = str.match(NEWLINE_REGEX);\n if (lines) lineno += lines.length;\n var i = str.lastIndexOf(NEWLINE);\n column = ~i ? str.length - i : column + str.length;\n }\n\n /**\n * Mark position and patch `node.position`.\n *\n * @return {Function}\n */\n function position() {\n var start = { line: lineno, column: column };\n return function(node) {\n node.position = new Position(start);\n whitespace();\n return node;\n };\n }\n\n /**\n * Store position information for a node.\n *\n * @constructor\n * @property {Object} start\n * @property {Object} end\n * @property {undefined|String} source\n */\n function Position(start) {\n this.start = start;\n this.end = { line: lineno, column: column };\n this.source = options.source;\n }\n\n /**\n * Non-enumerable source string.\n */\n Position.prototype.content = style;\n\n var errorsList = [];\n\n /**\n * Error `msg`.\n *\n * @param {String} msg\n * @throws {Error}\n */\n function error(msg) {\n var err = new Error(\n options.source + ':' + lineno + ':' + column + ': ' + msg\n );\n err.reason = msg;\n err.filename = options.source;\n err.line = lineno;\n err.column = column;\n err.source = style;\n\n if (options.silent) {\n errorsList.push(err);\n } else {\n throw err;\n }\n }\n\n /**\n * Match `re` and return captures.\n *\n * @param {RegExp} re\n * @return {undefined|Array}\n */\n function match(re) {\n var m = re.exec(style);\n if (!m) return;\n var str = m[0];\n updatePosition(str);\n style = style.slice(str.length);\n return m;\n }\n\n /**\n * Parse whitespace.\n */\n function whitespace() {\n match(WHITESPACE_REGEX);\n }\n\n /**\n * Parse comments.\n *\n * @param {Object[]} [rules]\n * @return {Object[]}\n */\n function comments(rules) {\n var c;\n rules = rules || [];\n while ((c = comment())) {\n if (c !== false) {\n rules.push(c);\n }\n }\n return rules;\n }\n\n /**\n * Parse comment.\n *\n * @return {Object}\n * @throws {Error}\n */\n function comment() {\n var pos = position();\n if (FORWARD_SLASH != style.charAt(0) || ASTERISK != style.charAt(1)) return;\n\n var i = 2;\n while (\n EMPTY_STRING != style.charAt(i) &&\n (ASTERISK != style.charAt(i) || FORWARD_SLASH != style.charAt(i + 1))\n ) {\n ++i;\n }\n i += 2;\n\n if (EMPTY_STRING === style.charAt(i - 1)) {\n return error('End of comment missing');\n }\n\n var str = style.slice(2, i - 2);\n column += 2;\n updatePosition(str);\n style = style.slice(i);\n column += 2;\n\n return pos({\n type: TYPE_COMMENT,\n comment: str\n });\n }\n\n /**\n * Parse declaration.\n *\n * @return {Object}\n * @throws {Error}\n */\n function declaration() {\n var pos = position();\n\n // prop\n var prop = match(PROPERTY_REGEX);\n if (!prop) return;\n comment();\n\n // :\n if (!match(COLON_REGEX)) return error(\"property missing ':'\");\n\n // val\n var val = match(VALUE_REGEX);\n\n var ret = pos({\n type: TYPE_DECLARATION,\n property: trim(prop[0].replace(COMMENT_REGEX, EMPTY_STRING)),\n value: val\n ? trim(val[0].replace(COMMENT_REGEX, EMPTY_STRING))\n : EMPTY_STRING\n });\n\n // ;\n match(SEMICOLON_REGEX);\n\n return ret;\n }\n\n /**\n * Parse declarations.\n *\n * @return {Object[]}\n */\n function declarations() {\n var decls = [];\n\n comments(decls);\n\n // declarations\n var decl;\n while ((decl = declaration())) {\n if (decl !== false) {\n decls.push(decl);\n comments(decls);\n }\n }\n\n return decls;\n }\n\n whitespace();\n return declarations();\n};\n\n/**\n * Trim `str`.\n *\n * @param {String} str\n * @return {String}\n */\nfunction trim(str) {\n return str ? str.replace(TRIM_REGEX, EMPTY_STRING) : EMPTY_STRING;\n}\n","var parse = require('inline-style-parser');\n\n/**\n * Parses inline style to object.\n *\n * @example\n * // returns { 'line-height': '42' }\n * StyleToObject('line-height: 42;');\n *\n * @param {String} style - The inline style.\n * @param {Function} [iterator] - The iterator function.\n * @return {null|Object}\n */\nfunction StyleToObject(style, iterator) {\n var output = null;\n if (!style || typeof style !== 'string') {\n return output;\n }\n\n var declaration;\n var declarations = parse(style);\n var hasIterator = typeof iterator === 'function';\n var property;\n var value;\n\n for (var i = 0, len = declarations.length; i < len; i++) {\n declaration = declarations[i];\n property = declaration.property;\n value = declaration.value;\n\n if (hasIterator) {\n iterator(property, value, declaration);\n } else if (value) {\n output || (output = {});\n output[property] = value;\n }\n }\n\n return output;\n}\n\nmodule.exports = StyleToObject;\n"],"names":["COMMENT_REGEX","NEWLINE_REGEX","WHITESPACE_REGEX","PROPERTY_REGEX","COLON_REGEX","VALUE_REGEX","SEMICOLON_REGEX","TRIM_REGEX","EMPTY_STRING","trim","str","replace","style","iterator","declaration","output","property","value","declarations","options","TypeError","lineno","column","updatePosition","lines","match","length","i","lastIndexOf","position","start","line","node","Position","whitespace","this","end","source","error","msg","err","Error","reason","filename","silent","re","m","exec","slice","comments","rules","c","comment","push","pos","charAt","type","prop","val","ret","prototype","content","decl","decls","parse","hasIterator","len"],"mappings":"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"}
package/index.js CHANGED
@@ -1,26 +1,42 @@
1
- var parse = require('css/lib/parse');
1
+ var parse = require('inline-style-parser');
2
2
 
3
3
  /**
4
- * Parses inline style to object (server).
4
+ * Parses inline style to object.
5
5
  *
6
- * Example: 'color:red' => { color: 'red' }
6
+ * @example
7
+ * // returns { 'line-height': '42' }
8
+ * StyleToObject('line-height: 42;');
7
9
  *
8
- * @param {String} style
9
- * @return {Object|null}
10
+ * @param {String} style - The inline style.
11
+ * @param {Function} [iterator] - The iterator function.
12
+ * @return {null|Object}
10
13
  */
11
- module.exports = function parseInlineStyleServer(style) {
12
- if (!style || typeof style !== 'string') return null;
14
+ function StyleToObject(style, iterator) {
15
+ var output = null;
16
+ if (!style || typeof style !== 'string') {
17
+ return output;
18
+ }
13
19
 
14
- // make sure to wrap declarations in placeholder
15
- var declarations = parse('p{' + style + '}').stylesheet.rules[0].declarations;
16
- var output = {};
20
+ var declaration;
21
+ var declarations = parse(style);
22
+ var hasIterator = typeof iterator === 'function';
23
+ var property;
24
+ var value;
17
25
 
18
- declarations.forEach(function(declaration) {
19
- var value = declaration.value;
20
- if (value) {
21
- output[declaration.property] = value;
26
+ for (var i = 0, len = declarations.length; i < len; i++) {
27
+ declaration = declarations[i];
28
+ property = declaration.property;
29
+ value = declaration.value;
30
+
31
+ if (hasIterator) {
32
+ iterator(property, value, declaration);
33
+ } else if (value) {
34
+ output || (output = {});
35
+ output[property] = value;
22
36
  }
23
- });
37
+ }
24
38
 
25
39
  return output;
26
- };
40
+ }
41
+
42
+ module.exports = StyleToObject;
package/package.json CHANGED
@@ -1,20 +1,23 @@
1
1
  {
2
2
  "name": "style-to-object",
3
- "version": "0.1.0",
3
+ "version": "0.2.3",
4
4
  "description": "Converts inline style to object.",
5
5
  "author": "Mark <mark@remarkablemark.org>",
6
6
  "main": "index.js",
7
7
  "scripts": {
8
+ "build": "npm run clean && npm run build:min && npm run build:unmin",
9
+ "build:min": "NODE_ENV=production rollup --config --file dist/style-to-object.min.js --sourcemap",
10
+ "build:unmin": "NODE_ENV=development rollup --config --file dist/style-to-object.js",
11
+ "clean": "rm -rf dist",
12
+ "coveralls": "nyc report --reporter=text-lcov | coveralls",
13
+ "lint": "eslint --ignore-path .gitignore .",
14
+ "lint:fix": "npm run lint -- --fix",
8
15
  "prepublishOnly": "npm run build",
9
- "release": "standard-version",
16
+ "release": "standard-version --no-verify",
10
17
  "test": "mocha",
11
- "lint": "eslint --ignore-path .gitignore .",
12
- "cover": "istanbul cover _mocha -- -R spec \"test/**/*.js\"",
13
- "coveralls": "cat coverage/lcov.info | coveralls",
14
- "clean": "rm -rf dist",
15
- "build": "npm run clean && npm run build:min && npm run build:unmin",
16
- "build:min": "NODE_ENV=production rollup --config --output.file dist/style-to-object.min.js",
17
- "build:unmin": "rollup --config --output.file dist/style-to-object.js"
18
+ "test:coverage": "nyc npm test",
19
+ "test:coverage:report": "nyc report --reporter=html",
20
+ "test:watch": "mocha --watch"
18
21
  },
19
22
  "repository": {
20
23
  "type": "git",
@@ -24,26 +27,36 @@
24
27
  "url": "https://github.com/remarkablemark/style-to-object/issues"
25
28
  },
26
29
  "keywords": [
30
+ "style-to-object",
27
31
  "inline",
28
- "css",
29
32
  "style",
33
+ "parser",
34
+ "css",
30
35
  "object",
31
36
  "pojo"
32
37
  ],
33
38
  "dependencies": {
34
- "css": "2.2.1"
39
+ "inline-style-parser": "0.1.1"
35
40
  },
36
41
  "devDependencies": {
37
- "coveralls": "3.0.0",
38
- "eslint": "4.11.0",
39
- "istanbul": "0.4.5",
40
- "mocha": "4.0.1",
41
- "rollup": "0.51.5",
42
- "rollup-plugin-commonjs": "8.2.6",
43
- "rollup-plugin-node-resolve": "3.0.0",
44
- "rollup-plugin-uglify": "2.0.1",
45
- "standard-version": "4.2.0",
46
- "uglify-es": "3.1.9"
42
+ "@commitlint/cli": "^8.0.0",
43
+ "@commitlint/config-conventional": "^8.0.0",
44
+ "coveralls": "^3.0.4",
45
+ "eslint": "^6.0.0",
46
+ "eslint-plugin-prettier": "^3.1.0",
47
+ "husky": "^2.4.1",
48
+ "lint-staged": "^8.2.1",
49
+ "mocha": "^6.1.4",
50
+ "nyc": "^14.1.1",
51
+ "prettier": "^1.18.2",
52
+ "rollup": "^1.16.2",
53
+ "rollup-plugin-commonjs": "^10.0.0",
54
+ "rollup-plugin-node-resolve": "^5.0.4",
55
+ "rollup-plugin-uglify": "^6.0.2",
56
+ "standard-version": "^6.0.1"
47
57
  },
58
+ "files": [
59
+ "/dist"
60
+ ],
48
61
  "license": "MIT"
49
62
  }