Last active
December 10, 2015 20:49
-
-
Save cyjake/4490971 to your computer and use it in GitHub Desktop.
A CSS Parser written in JavaScript as a SeaJS module. Parses css text into objects.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Usage: | |
// | |
// seajs.use('style_parser', function(parser) { | |
// var console.log(parser.parse('body { padding: 0; margin: 0 }')) | |
// }) | |
// | |
// will output: | |
// { | |
// "body": { | |
// "padding": 0, | |
// "margin": 0 | |
// } | |
// } | |
// | |
// The statements part should be in arrays to make sure the original order is kept. | |
// But for me in objects is enough. | |
// @author: http://cyj.me | |
define(function(require, exports, module) { | |
module.exports = { | |
parse: function(str) { | |
var chr = str[0] | |
var i = 0 | |
var result = {} | |
function whitespace() { | |
while (/\s/.test(chr)) { | |
step() | |
} | |
} | |
function selector() { | |
var sel = '' | |
whitespace() | |
while ('{' !== chr) { | |
sel += chr | |
step() | |
} | |
step() | |
return chop(sel) | |
} | |
function block() { | |
var obj = {} | |
while ('}' !== chr) { | |
obj[property()] = value() | |
whitespace() | |
} | |
step() | |
return obj | |
} | |
function property() { | |
var prop = '' | |
whitespace() | |
while (':' !== chr) { | |
prop += chr | |
step() | |
} | |
step() | |
return chop(prop) | |
} | |
function value() { | |
var val = '' | |
whitespace() | |
while (!/[;\n]/.test(chr)) { | |
val += chr | |
step() | |
} | |
step() | |
return chop(val) | |
} | |
function chop(str) { | |
return str.replace(/\s+$/, '') | |
} | |
function step() { | |
return chr = str[++i] | |
} | |
// Just change this and the block() while loop | |
// if you prefer statements in array rather than object. | |
while (chr) { | |
result[selector()] = block() | |
whitespace() | |
} | |
return result | |
} | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment