Skip to content

Commit

Permalink
allow parsing attributes without values
Browse files Browse the repository at this point in the history
  • Loading branch information
AngelMunoz committed Feb 5, 2024
1 parent d6d6c40 commit 18f9a57
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
15 changes: 12 additions & 3 deletions src/Hox/SelectorParser.fs
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,24 @@ let private pClass: Parser<SelectorValue, unit> =
>>= fun cls -> preturn(Class cls)

let private pAttribute: Parser<SelectorValue, unit> =
let name = manyChars(letter <|> digit <|> pchar '-')
let name =
letter .>>. manyChars(letter <|> digit <|> pchar '-')
>>= fun (initial, rest) -> preturn $"{initial}{rest}"

let eq = pchar '='
let value = manySatisfy(fun ch -> ch <> ']')

pchar '[' >>. name .>> eq .>>. value
pchar '[' >>. name .>> opt eq .>>. opt value
.>> unicodeSpaces
.>> pchar ']'
.>> unicodeSpaces
>>= fun (name, value) -> preturn(Attribute { name = name; value = value })
>>= fun (name, value) ->
preturn(
Attribute {
name = name
value = defaultArg value System.String.Empty
}
)

let private pSelector: Parser<Element, unit> =
unicodeSpaces >>. tagName .>> unicodeSpaces
Expand Down
16 changes: 16 additions & 0 deletions tests/Hox.Tests/Parser.fs
Original file line number Diff line number Diff line change
Expand Up @@ -249,3 +249,19 @@ let ``Attributes can have arbitrary content within '[' ']'``() =
"""~!@#$%^&*()_+QWERTYUIOP{}|ASDFGHJKL:"ZXCVBNM<>?1234567890-=qwertyuiop\asdfghjkl;'zxcvbnm,./"""),
attributes
)

[<Fact>]
let ``Can parse selector without value``() =
let expected = {
tag = "div"
attributes = LinkedList [ Attribute { name = "data-foo"; value = "" } ]
children = LinkedList []
}

let actual = Parsers.selector "div[data-foo]"
Assert.Equal(expected.tag, actual.tag)

match actual.attributes.First.Value with
| Attribute { name = "data-foo"; value = "" } -> ()
| _ ->
Assert.Fail("Expected an attribute with the name 'data-foo' and value ''")

0 comments on commit 18f9a57

Please sign in to comment.