Skip to content

Commit

Permalink
converters from/to XmlNode (#229)
Browse files Browse the repository at this point in the history
* converters from/to XmlNode

* fix: text and verbatim from VNode to xmlnode

* Update karax/xdom.nim

* Update karax/xdom.nim

* change converters to procs

Co-authored-by: untoreh <francesco.giannelli@yahoo.it>
Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
  • Loading branch information
3 people authored Aug 24, 2022
1 parent b438ca9 commit 0f15372
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 0 deletions.
39 changes: 39 additions & 0 deletions karax/xdom.nim
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import std/[xmltree, htmlparser, strtabs, strutils]
import ./vdom

proc toXmlNode*(el: VNode): XmlNode =
case el.kind
of VNodeKind.verbatim:
parseHtml($el)
of VNodeKind.text:
newText(el.text)
else:
let xAttrs = @[].toXmlAttributes
for k, v in el.attrs:
xAttrs[k] = v
var kids: seq[XmlNode]
if el.len > 0:
for k in el:
kids.add k.toXmlNode
newXmlTree($el.kind, kids, attributes = xAttrs)

proc toVNode*(el: XmlNode): VNode =
try:
case el.kind
of xnElement:
let kind = parseEnum[VNodeKind](el.tag)
var vnAttrs: seq[(string, string)]
if not el.attrs.isnil:
for k, v in el.attrs:
vnAttrs.add (k, v)
var kids: seq[VNode]
if el.len > 0:
for k in el:
kids.add k.toVNode
tree(kind, vnAttrs, kids)
of xnText:
vn($el)
else:
verbatim($el)
except ValueError: # karax doesn't support the node tag
verbatim($el)
1 change: 1 addition & 0 deletions tests/tester.nim
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ proc main =
exec("nim js examples/carousel/carousel.nim")
exec("nim js -d:nodejs -r tests/difftest.nim")
exec("nim c tests/nativehtmlgen.nim")
exec("nim c tests/xmlNodeConversionTests.nim")

for test in os.walkFiles("examples/*.nim"):
exec("nim js " & test)
Expand Down
19 changes: 19 additions & 0 deletions tests/xmlNodeConversionTests.nim
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import std/xmltree
import "../karax"/[vdom, xdom]

let xn = newXmlTree("div", @[], attributes = [("a", "b")].toXmlAttributes)
let vn = tree(tdiv, attrs = (@[("a", "b"), ("c", "d")]))
vn.add newVNode(a)
vn[0].add vn("bbb")
vn.add verbatim("<app>abc</app>")
xn.add newXmlTree("i", @[], attributes = [("a", "b")].toXmlAttributes)

let vnX = vn.toXmlNode

doassert vnX[0].len == 1 and vnX[1][0].kind == xnText
doassert $vnX[1].tag == "app"
doassert $vnX == """<div c="d" a="b">
<a>bbb</a>
<app>abc</app>
</div>"""
doassert $xn.toVNode == """<div a="b"><i a="b"></i></div>"""

0 comments on commit 0f15372

Please sign in to comment.