utils.ts 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import React from 'react'
  2. export type AbstractNode = {
  3. name: string
  4. attributes: {
  5. [key: string]: string
  6. }
  7. children?: AbstractNode[]
  8. }
  9. export type Attrs = {
  10. [key: string]: string
  11. }
  12. export function normalizeAttrs(attrs: Attrs = {}): Attrs {
  13. return Object.keys(attrs).reduce((acc: Attrs, key) => {
  14. const val = attrs[key]
  15. switch (key) {
  16. case 'class':
  17. acc.className = val
  18. delete acc.class
  19. break
  20. default:
  21. acc[key] = val
  22. }
  23. return acc
  24. }, {})
  25. }
  26. export function generate(
  27. node: AbstractNode,
  28. key: string,
  29. rootProps?: { [key: string]: any } | false,
  30. ): any {
  31. if (!rootProps) {
  32. return React.createElement(
  33. node.name,
  34. { key, ...normalizeAttrs(node.attributes) },
  35. (node.children || []).map((child, index) => generate(child, `${key}-${node.name}-${index}`)),
  36. )
  37. }
  38. return React.createElement(
  39. node.name,
  40. {
  41. key,
  42. ...normalizeAttrs(node.attributes),
  43. ...rootProps,
  44. },
  45. (node.children || []).map((child, index) => generate(child, `${key}-${node.name}-${index}`)),
  46. )
  47. }