Search code examples
ocamljs-of-ocaml

Inserting Tyxml_js.Svg values in js_of_ocaml's Dom_svg


Let's say I create an SVG rect, using Tyxml's syntax:

let rect_elt = <:svg< <rect></rect> >>

How can I insert it inside the DOM using the API of js_of_ocaml ?

I want to do something like that:

let _ =
  let rect_elt = <:svg< <rect></rect> >> in
  let svg_elt = Dom_svg.getElementById "graph-svg" in
  svg_elt##appendChild(rect_elt)

But I don't know how to do the proper type conversions.


Solution

  • Ok so in order to convert to (resp. from) Dom_svg, one has to create an instance of Tyxml_cast.MakeTo (resp. MakeOf):

    module To_dom = Tyxml_cast.MakeTo(struct
      type 'a elt = 'a Tyxml_js.Svg.elt
      let elt = Tyxml_js.Svg.toelt
    end)
    
    module Of_dom = Tyxml_cast.MakeOf(struct
      type 'a elt = 'a Tyxml_js.Svg.elt
      let elt = Tyxml_js.Svg.tot
    end)
    

    and use it as follow:

    let _ =
      let svg_elt = Dom_svg.getElementById "some-svg" in
      let rect_node = <:svg< <rect></rect> >>
        |> To_dom.of_node in
      svg_elt##appendChild(rect_node)