utils.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. key = key.replace(/([-]\w)/g, (g: string) => g[1].toUpperCase())
  16. switch (key) {
  17. case 'class':
  18. acc.className = val
  19. delete acc.class
  20. break
  21. default:
  22. acc[key] = val
  23. }
  24. return acc
  25. }, {})
  26. }
  27. export function generate(
  28. node: AbstractNode,
  29. key: string,
  30. rootProps?: { [key: string]: any } | false,
  31. ): any {
  32. if (!rootProps) {
  33. return React.createElement(
  34. node.name,
  35. { key, ...normalizeAttrs(node.attributes) },
  36. (node.children || []).map((child, index) => generate(child, `${key}-${node.name}-${index}`)),
  37. )
  38. }
  39. return React.createElement(
  40. node.name,
  41. {
  42. key,
  43. ...normalizeAttrs(node.attributes),
  44. ...rootProps,
  45. },
  46. (node.children || []).map((child, index) => generate(child, `${key}-${node.name}-${index}`)),
  47. )
  48. }