Yes @shiningflint elm-svg-parser is definitely the way to go. I’ve done almost exactly the same thing as you’re asking for. A false start that made things miserable for a little while was to use img
tags and use ports with something like GitHub - iconic/SVGInjector: Fast, caching, dynamic inline SVG DOM injection library. Although this makes loading images nearly trivial, this plays poorly with the virtual DOM.
Instead I would recommend loading the SVG as a string through Http
and biting the bullet for the additional record-keeping that will entail then passing it through the SvgParser
. Don’t use SvgParser.parse
, because you’ll end up directly with Html
which cannot be inspected and therefore you can’t traverse over the SVG nodes and add click handlers as necessary.
Instead you want to use SvgParser.parseToNode
, which gives you SvgNode
s that you can then play with. Unfortunately SvgParser
doesn’t expose a function to go from SvgNode
to Html a
, so you’ll want to copy part of SvgParser.parse
in particular
case svgNode of
SvgElement element ->
if element.name == "svg" then
Ok <|
svg (List.map toAttribute element.attributes)
(List.map nodeToSvg element.children)
else
Err "Top element is not svg"
_ ->
Err "Top element is not svg"
and put that in a separate function to get SvgNode -> Html msg
.
To add the onclick handler you can modify the above snippet of code to inspect certain attribute strings and translate them to actual onClick MyCustomType
Html.Attribute
s (e.g. you could have have the SvgAttribute
("myOnClick", "onClickValue")
and then wrap toAttribute
with something that checks for "myOnClick"
and "onClickValue"
and calls onClick OnClickValue
.