You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

generate.ts 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import Rectangle from './rectangle'
  2. import Circle from './circle'
  3. import Ellipse from './ellipse'
  4. import Polyline from './polyline'
  5. import Dot from './dot'
  6. import Ray from './ray'
  7. import Line from './line'
  8. import Vector from './vector'
  9. import Utils from './utils'
  10. import { NumberControl, VectorControl, codeControls, controls } from './control'
  11. import { codeShapes } from './index'
  12. import { CodeControl, Data, Shape } from 'types'
  13. const baseScope = {
  14. Dot,
  15. Circle,
  16. Ellipse,
  17. Ray,
  18. Line,
  19. Polyline,
  20. Rectangle,
  21. Vector,
  22. Utils,
  23. VectorControl,
  24. NumberControl,
  25. }
  26. /**
  27. * Evaluate code, collecting generated shapes in the shape set. Return the
  28. * collected shapes as an array.
  29. * @param code
  30. */
  31. export function generateFromCode(
  32. data: Data,
  33. code: string
  34. ): {
  35. shapes: Shape[]
  36. controls: CodeControl[]
  37. } {
  38. codeControls.clear()
  39. codeShapes.clear()
  40. ;(window as any).isUpdatingCode = false
  41. ;(window as any).currentPageId = data.currentPageId
  42. const { currentPageId } = data
  43. const scope = { ...baseScope, controls, currentPageId }
  44. new Function(...Object.keys(scope), `${code}`)(...Object.values(scope))
  45. const generatedShapes = Array.from(codeShapes.values()).map(
  46. (instance) => instance.shape
  47. )
  48. const generatedControls = Array.from(codeControls.values())
  49. return { shapes: generatedShapes, controls: generatedControls }
  50. }
  51. /**
  52. * Evaluate code, collecting generated shapes in the shape set. Return the
  53. * collected shapes as an array.
  54. * @param code
  55. */
  56. export function updateFromCode(
  57. data: Data,
  58. code: string
  59. ): {
  60. shapes: Shape[]
  61. } {
  62. codeShapes.clear()
  63. ;(window as any).isUpdatingCode = true
  64. ;(window as any).currentPageId = data.currentPageId
  65. const { currentPageId } = data
  66. const scope = {
  67. ...baseScope,
  68. currentPageId,
  69. controls: Object.fromEntries(
  70. Object.entries(controls).map(([_, control]) => [
  71. control.label,
  72. control.value,
  73. ])
  74. ),
  75. }
  76. new Function(...Object.keys(scope), `${code}`)(...Object.values(scope))
  77. const generatedShapes = Array.from(codeShapes.values()).map(
  78. (instance) => instance.shape
  79. )
  80. return { shapes: generatedShapes }
  81. }