diff --git a/src/Text/Taggy/Combinators.hs b/src/Text/Taggy/Combinators.hs index 9b13fe1..0189e0d 100644 --- a/src/Text/Taggy/Combinators.hs +++ b/src/Text/Taggy/Combinators.hs @@ -1,7 +1,9 @@ -module Text.Taggy.Combinators (hasAttr, getAttr) where +module Text.Taggy.Combinators (hasAttr, getAttr, innerText) where import Prelude hiding (lookup) -import Text.Taggy.DOM (Element(..), AttrName, AttrValue) +import Data.Monoid (mconcat) +import Data.Text (Text) +import Text.Taggy.DOM (Element(..), Node(..), AttrName, AttrValue) import Data.HashMap.Strict (lookup, keys) hasAttr :: Element -> AttrName -> Bool @@ -9,3 +11,8 @@ hasAttr = flip elem . keys . eltAttrs getAttr :: Element -> AttrName -> Maybe AttrValue getAttr = flip lookup . eltAttrs + +innerText :: Element -> Text +innerText = mconcat . map decons . eltChildren + where decons (NodeElement e) = innerText e + decons (NodeContent x) = x diff --git a/tests/Text/Taggy/CombinatorsSpec.hs b/tests/Text/Taggy/CombinatorsSpec.hs index c714dc1..ea9d607 100644 --- a/tests/Text/Taggy/CombinatorsSpec.hs +++ b/tests/Text/Taggy/CombinatorsSpec.hs @@ -4,12 +4,12 @@ module Text.Taggy.CombinatorsSpec where import Text.Taggy.Combinators import Test.Hspec -import Text.Taggy.DOM -import Data.HashMap.Strict +import Text.Taggy spec :: Spec spec = do - let element = Element "html" (fromList [("xmlns", "http://www.w3.org/1999/xhtml")]) [] + let element = (\(NodeElement e) -> e) . head . domify . taggyWith False $ + "foobaz" describe "hasAttr" $ do it "Tests whether an attribute is present." $ do (element `hasAttr` "xmlns") `shouldBe` True @@ -19,3 +19,6 @@ spec = do (element `getAttr` "xmlns") `shouldBe` Just "http://www.w3.org/1999/xhtml" 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." $ + innerText element `shouldBe` "foobaz"