Skip to content

Commit

Permalink
feat: parse single quote attributes (#125)
Browse files Browse the repository at this point in the history
  • Loading branch information
joerdav authored and a-h committed Sep 24, 2023
1 parent d57760c commit 6066db2
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
19 changes: 14 additions & 5 deletions parser/v2/elementparser.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,8 +96,9 @@ var (

// Constant attribute.
var (
attributeConstantValueParser = parse.StringUntil(parse.Rune('"'))
constantAttributeParser = parse.Func(func(pi *parse.Input) (attr ConstantAttribute, ok bool, err error) {
attributeConstantValueParser = parse.StringUntil(parse.Rune('"'))
attributeConstantValueSingleQuoteParser = parse.StringUntil(parse.Rune('\''))
constantAttributeParser = parse.Func(func(pi *parse.Input) (attr ConstantAttribute, ok bool, err error) {
start := pi.Index()

// Optional whitespace leader.
Expand All @@ -112,21 +113,29 @@ var (
}

// ="
if _, ok, err = parse.String(`="`).Parse(pi); err != nil || !ok {
result, ok, err := parse.Or(parse.String(`="`), parse.String(`='`)).Parse(pi)
if err != nil || !ok {
pi.Seek(start)
return
}

valueParser := attributeConstantValueParser
closeParser := parse.String(`"`)
if result.B.OK {
valueParser = attributeConstantValueSingleQuoteParser
closeParser = parse.String(`'`)
}

// Attribute value.
if attr.Value, ok, err = attributeConstantValueParser.Parse(pi); err != nil || !ok {
if attr.Value, ok, err = valueParser.Parse(pi); err != nil || !ok {
pi.Seek(start)
return
}

attr.Value = html.UnescapeString(attr.Value)

// " - closing quote.
if _, ok, err = Must(parse.String(`"`), fmt.Sprintf("missing closing quote on attribute %q", attr.Name)).Parse(pi); err != nil || !ok {
if _, ok, err = Must(closeParser, fmt.Sprintf("missing closing quote on attribute %q", attr.Name)).Parse(pi); err != nil || !ok {
pi.Seek(start)
return
}
Expand Down
9 changes: 9 additions & 0 deletions parser/v2/elementparser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,15 @@ if test {
Value: "test",
},
},
{
name: "single quote constant attribute",
input: ` href='"test"'`,
parser: StripType(constantAttributeParser),
expected: ConstantAttribute{
Name: "href",
Value: `"test"`,
},
},
{
name: "attribute name with hyphens",
input: ` data-turbo-permanent="value"`,
Expand Down

0 comments on commit 6066db2

Please sign in to comment.