Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

converters from/to XmlNode #229

Merged
merged 5 commits into from
Aug 24, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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>"""