Last active
May 23, 2019 02:56
-
-
Save fusepilot/8f26b25386010d4f085e to your computer and use it in GitHub Desktop.
Peg.js Simple CSS Attribute Parsing
This file contains hidden or 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
/* | |
* CSS like attribute parsing. | |
* | |
* Parses strings like `comp[name=myComp] > layer[name=myLayer light=true selected]` to objects. | |
*/ | |
{ | |
function mergeProps(array){ | |
var merged = {}; | |
for (var i = 0; i < array.length; i++) { | |
var pair = array[i] | |
for (var key in pair) { | |
merged[key] = pair[key] | |
} | |
} | |
return merged; | |
} | |
} | |
Start | |
= Selectors | |
Properties | |
= '[' props:Property+ ']' { return mergeProps(props) } | |
Property | |
= ValuePair | |
/ ValueSingle | |
ValueSingle | |
= name:[a-zA-Z]+ _? { var o = {}; var key = name.join(''); o[key] = true; return o; } | |
ValuePair | |
= name:[a-zA-Z]+ "=" value:Value _? { var o = {}; var key = name.join(''); o[key] = value; return o; } | |
Selector | |
= type:[a-zA-Z]+ props:Properties children:ChildrenSelectors? _? { return { type: type.join(''), props: props, children: children } } | |
Selectors | |
= Selector+ | |
Value | |
= BooleanLiteral | |
/ StringLiteral | |
BooleanLiteral | |
= TrueToken { return true } | |
/ FalseToken { return false } | |
StringLiteral | |
= chars:[a-zA-Z]+ { return chars.join('') } | |
ChildrenSelectors | |
= _ ">" _ children:Selectors { return children } | |
TrueToken = "true" _? | |
FalseToken = "false" _? | |
_ "whitespace" | |
= [ \t\n\r]* |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment