您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

generate.ts 2.1KB

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