import { AttributeValue } from "@opticss/element-analysis" ; import * as nearley from "nearley" ; const grammar = require ( "./grammar/attrvalue" ) ; export interface AttributeFlags { [ attrName ] : boolean ; } const WHITESPACE_ATTRIBUTES = { "class" : true , } ; const TEXT_ATTRIBUTES = { "title" : true , "media" : true , "content" : true , "style" : true , } ; export class AttributeValueParser { whitespaceAttributes : AttributeFlags ; textAttributes : AttributeFlags ; plainHtml : boolean ; constructor ( plainHtml = false , textAttributes = { } , whitespaceAttributes = { } ) { this . textAttributes = { ... TEXT_ATTRIBUTES , ... textAttributes } ; this . whitespaceAttributes = { ... WHITESPACE_ATTRIBUTES , ... whitespaceAttributes } ; this . plainHtml = plainHtml ; } parse ( attrNamespace , attrName , value ) { let attrKey = attrName ; if ( attrNamespace ) attrKey = `${ attrNamespace }:${ attrKey }` ; let whitespaceDelimited = this . whitespaceAttributes [ attrKey ] ; if ( whitespaceDelimited ) { value = value . trim ( ) ; } if ( attrName . match ( /^on/ ) || value . startsWith ( "javascript:" ) ) { return { absent : true } ; } if ( this . textAttributes [ attrKey ] || ( ! whitespaceDelimited && this . plainHtml ) ) { return { constant : value } ; } let grammarObj = nearley . Grammar . fromCompiled ( grammar ) ; grammarObj . start = whitespaceDelimited ? "whitespaceDelimitedAttribute" : "attribute" ; let parser = new nearley . Parser ( grammarObj ) ; parser . feed ( value ) ; let res = parser . finish ( ) ; return res [ 0 ] ; } }