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 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 } 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(code: string) {
  32. codeControls.clear()
  33. codeShapes.clear()
  34. ;(window as any).isUpdatingCode = false
  35. const scope = { ...baseScope, controls }
  36. new Function(...Object.keys(scope), `${code}`)(...Object.values(scope))
  37. const generatedShapes = Array.from(codeShapes.values()).map(
  38. (instance) => instance.shape
  39. )
  40. const generatedControls = Array.from(codeControls.values())
  41. return { shapes: generatedShapes, controls: generatedControls }
  42. }
  43. /**
  44. * Evaluate code, collecting generated shapes in the shape set. Return the
  45. * collected shapes as an array.
  46. * @param code
  47. */
  48. export function updateFromCode(
  49. code: string,
  50. controls: Record<string, CodeControl>
  51. ) {
  52. codeShapes.clear()
  53. ;(window as any).isUpdatingCode = true
  54. const scope = {
  55. ...baseScope,
  56. controls: Object.fromEntries(
  57. Object.entries(controls).map(([id, control]) => [
  58. control.label,
  59. control.value,
  60. ])
  61. ),
  62. }
  63. new Function(...Object.keys(scope), `${code}`)(...Object.values(scope))
  64. const generatedShapes = Array.from(codeShapes.values()).map(
  65. (instance) => instance.shape
  66. )
  67. return { shapes: generatedShapes }
  68. }