Tree.k 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. invoke {
  2. function props_to_string (props: Hash) -> String {
  3. return (
  4. props -> map_entry -> .{ ' ${1}="${2}"' << [.name, str(.value)] }
  5. -> join('')
  6. )
  7. }
  8. function div (props: Hash, children: List) -> String {
  9. return '<div${1}>${2}</div>' << [
  10. props_to_string(props),
  11. children -> map -> .{
  12. when {
  13. .child is Iterable: .child,
  14. otherwise: [.child]
  15. }
  16. }
  17. -> flat
  18. -> map -> .{ str .child }
  19. -> join('')
  20. ]
  21. }
  22. let d1 = tree { div {} }
  23. let d1_ = |-> div {}
  24. assert d1 == d1_
  25. assert d1 == '<div></div>'
  26. let d2 = |-> div { x=1; y=2 }
  27. let ok = lambda(x) { return x == '<div x="1" y="2"></div>' }
  28. assert ok(d2)
  29. assert ok() -> tree { div { x=1; y=2 } }
  30. let d3 = |-> div {
  31. div { = 'Hello'; = ' '; = 'World' }
  32. div { = 'Change The World' }
  33. }
  34. assert d3 == '<div><div>Hello World</div><div>Change The World</div></div>'
  35. let d4 = tree {
  36. div {
  37. id = 'root'
  38. class = 'container'
  39. div {
  40. id = 'header'
  41. tip = 'Header'
  42. }
  43. = 'List:'
  44. = [ |-> div {
  45. 'data-count' = i
  46. div {
  47. = i+1
  48. }
  49. }, for i in seq(3) ]
  50. }
  51. }
  52. assert d4 == '<div id="root" class="container"><div id="header" tip="Header"></div>List:<div data-count="0"><div>1</div></div><div data-count="1"><div>2</div></div><div data-count="2"><div>3</div></div></div>'
  53. }