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.2KB

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