An Element combinator to filter on an element and its children.

This commit is contained in:
vi 2014-06-23 15:20:59 +08:00
parent b46ea8b696
commit 1f60b9c9b5
2 changed files with 16 additions and 3 deletions

View File

@ -1,4 +1,4 @@
module Text.Taggy.Combinators (hasAttr, getAttr, innerText) where
module Text.Taggy.Combinators (hasAttr, getAttr, innerText, (//)) where
import Prelude hiding (lookup)
import Data.Monoid (mconcat)
@ -16,3 +16,9 @@ innerText :: Element -> Text
innerText = mconcat . map decons . eltChildren
where decons (NodeElement e) = innerText e
decons (NodeContent x) = x
(//) :: Element -> (Element -> Bool) -> [Element]
(//) = flip filter . expand
where expand = concat . map decons . eltChildren
decons (NodeElement e) = e : expand e
decons _ = []

View File

@ -9,7 +9,7 @@ import Text.Taggy
spec :: Spec
spec = do
let element = (\(NodeElement e) -> e) . head . domify . taggyWith False $
"<html xmlns=\"http://www.w3.org/1999/xhtml\">foo<bar>baz</bar></html>"
"<html xmlns=\"http://www.w3.org/1999/xhtml\">foo<bar class=\"el\">baz</bar><qux class=\"el\"></qux></html>"
describe "hasAttr" $ do
it "Tests whether an attribute is present." $ do
(element `hasAttr` "xmlns") `shouldBe` True
@ -20,5 +20,12 @@ spec = do
it "Nothing's missing attributes." $
(element `getAttr` "style") `shouldBe` Nothing
describe "innerText" $ do
it "Should concatenate the NodeContent of the target element and all its children." $
it "Should concatenate the NodeContent of the target element and all its children." $
innerText element `shouldBe` "foobaz"
describe "(//)" $ do
it "Should return all children satisfying the predicate." $ do
let predicate = (==Just "el") . flip getAttr "class"
result = element // predicate
result `shouldSatisfy` not . null
result `shouldSatisfy` all predicate