Updates code editor

This commit is contained in:
Steve Ruiz 2021-05-17 11:01:11 +01:00
parent e21748f7b7
commit abd310aa2e
24 changed files with 792 additions and 227 deletions

View file

@ -7,9 +7,11 @@ import Ray from "./ray"
import Line from "./line"
import Vector from "./vector"
import Utils from "./utils"
import { NumberControl, VectorControl, codeControls, controls } from "./control"
import { codeShapes } from "./index"
import { CodeControl } from "types"
const scope = {
const baseScope = {
Dot,
Circle,
Ellipse,
@ -19,6 +21,8 @@ const scope = {
Rectangle,
Vector,
Utils,
VectorControl,
NumberControl,
}
/**
@ -26,8 +30,12 @@ const scope = {
* collected shapes as an array.
* @param code
*/
export function getShapesFromCode(code: string) {
export function generateFromCode(code: string) {
codeControls.clear()
codeShapes.clear()
;(window as any).isUpdatingCode = false
const scope = { ...baseScope, controls }
new Function(...Object.keys(scope), `${code}`)(...Object.values(scope))
@ -36,5 +44,39 @@ export function getShapesFromCode(code: string) {
return instance.shape
})
return generatedShapes
const generatedControls = Array.from(codeControls.values())
return { shapes: generatedShapes, controls: generatedControls }
}
/**
* Evaluate code, collecting generated shapes in the shape set. Return the
* collected shapes as an array.
* @param code
*/
export function updateFromCode(
code: string,
controls: Record<string, CodeControl>
) {
codeShapes.clear()
;(window as any).isUpdatingCode = true
const scope = {
...baseScope,
controls: Object.fromEntries(
Object.entries(controls).map(([id, control]) => [
control.label,
control.value,
])
),
}
new Function(...Object.keys(scope), `${code}`)(...Object.values(scope))
const generatedShapes = Array.from(codeShapes.values()).map((instance) => {
instance.shape.isGenerated = true
return instance.shape
})
return { shapes: generatedShapes }
}