Skip to content

Commit

Permalink
API: Allow compiling just plots
Browse files Browse the repository at this point in the history
  • Loading branch information
TheBizzle committed Nov 27, 2023
1 parent f7bf406 commit ff42c74
Showing 1 changed file with 42 additions and 4 deletions.
46 changes: 42 additions & 4 deletions compiler/js/src/main/scala/BrowserCompiler.scala
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,11 @@ import json.JsonWriter
import json.JsonWriter.string2TortoiseJs
import json.TortoiseJson
import json.TortoiseJson._
import json.WidgetToJson

import org.nlogo.tortoise.macros.json.Jsonify

import org.nlogo.core.CompilerException
import org.nlogo.core.{ CompilerException, Plot }
import org.nlogo.core.model.ModelReader

import org.nlogo.parse.CompilerUtilities
Expand Down Expand Up @@ -63,16 +64,18 @@ class BrowserCompiler {
}

@JSExport
def fromNlogo(contents: String, commandJson: NativeJson): NativeJson = {
def fromNlogo(contents: String, commandJson: NativeJson, compilationRequest: NativeJson): NativeJson = {

val compilationResult =
for {
commands <- readArray[String](commandJson, "commands")
compiledModel = CompiledModel.fromNlogoContents(contents, compiler)
tortoiseReq <- readNative[JsObject](compilationRequest)
parsedRequest <- CompilationRequest.read(tortoiseReq).leftMap(_.map(FailureString))
compiledModel = CompiledModel.fromNlogoContents(contents, compiler, parsedRequest.widgets)
compilation <- transformErrorsAndUpdateModel(compiledModel, compileExtras(commands, Seq()))
} yield compilation

JsonLibrary.toNative(compilationResult.toJsonObj)
JsonLibrary.toNative(compilationResult.leftMap(_.map(fail => fail: TortoiseFailure)).toJsonObj)

}

Expand Down Expand Up @@ -102,6 +105,41 @@ class BrowserCompiler {
, compiler.extensionManager
)

@JSExport
def compilePlots(plotJSON: NativeJson): NativeJson = {

def conv[E, T](t: ValidationNel[E, T])
(f: (E) => TortoiseFailure): ValidationNel[TortoiseFailure, T] =
t.leftMap(_.map(f))

def convStr[T](t: ValidationNel[String, T]) =
conv(t)(x => FailureException(new Exception(x)))

def convComp[T](t: ValidationNel[CompilerException, T]) =
conv(t)(x => FailureCompilerException(x))

val results: ValidationNel[TortoiseFailure, String] =
for {
tortoiseJSON <- readNative[JsArray](plotJSON)
widgets <- convStr(WidgetToJson.readWidgetsJson(tortoiseJSON))
plots = widgets.collect { case p: Plot => p }
plotJS <- convComp(CompiledModel.plotsToJS(plots, lastCompiledModel))
} yield plotJS

val json =
results.fold(
es => JsObject(fields(
"success" -> JsBool(false),
"result" -> JsArray(es.list.toList.map((f: TortoiseFailure) => f.toJsonObj)))),
success => JsObject(fields(
"success" -> JsBool(true),
"result" -> JsString(success)))
)

JsonLibrary.toNative(json)

}

@JSExport
def compileCommand(command: String): NativeJson = {
val results: CompiledStringV = lastCompiledModel.compileCommand(command)
Expand Down

0 comments on commit ff42c74

Please sign in to comment.