Skip to content

Instantly share code, notes, and snippets.

@panthershark
Created April 29, 2019 17:04
Show Gist options
  • Save panthershark/d6e4fee5b5d07ee500683cd989ae69a8 to your computer and use it in GitHub Desktop.
Save panthershark/d6e4fee5b5d07ee500683cd989ae69a8 to your computer and use it in GitHub Desktop.
Elm - HTML injection
module CommunityViews.HtmlUtil exposing
( mapAnchorElement
, toHtml
)
{-| Utility functions to work with html.
@docs mapHrefRecursive
@docs postBodyToVirtualDom
-}
-- uses hecrj/html-parser
import Html exposing (Html, text)
import Html.Parser exposing (Node(..))
import Html.Parser.Util exposing (toVirtualDom)
{-| parsed an html string, transforms hrefs in links, and converts to vdom which can be used in views.
-}
toHtml : Maybe (String -> String) -> String -> Result String (List (Html msg))
toHtml mf html =
case Html.Parser.run html of
Ok nodes ->
case mf of
Just func ->
Ok <| toVirtualDom <| List.map (mapAnchorElement func) nodes
Nothing ->
Ok <| toVirtualDom nodes
Err _ ->
Err "Invalid Html"
-- INTERNALS
mapHrefAttribute : (String -> String) -> ( String, String ) -> ( String, String )
mapHrefAttribute func x =
if Tuple.first x == "href" then
Tuple.mapSecond func x
else
x
mapAnchorElement : (String -> String) -> Node -> Node
mapAnchorElement func node =
case node of
Comment _ ->
node
Text _ ->
node
Element "a" attributes child_nodes ->
let
mapped =
List.map (mapHrefAttribute func) attributes
in
Element "a" mapped child_nodes
Element n attributes child_nodes ->
Element n attributes <| List.map (mapAnchorElement func) child_nodes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment