From 97857eb14927408ae70ef3d728af73f840462d25 Mon Sep 17 00:00:00 2001 From: Chong Wen Hao <58220142+8kdesign@users.noreply.github.com> Date: Tue, 12 Mar 2024 22:51:04 +0800 Subject: [PATCH] Added callback --- src/bundles/repl/functions.ts | 17 +++++++++++++++++ src/bundles/repl/index.ts | 1 + src/bundles/repl/programmable_repl.ts | 2 ++ 3 files changed, 20 insertions(+) diff --git a/src/bundles/repl/functions.ts b/src/bundles/repl/functions.ts index 914ceea70b..09843967bb 100644 --- a/src/bundles/repl/functions.ts +++ b/src/bundles/repl/functions.ts @@ -29,11 +29,28 @@ export function set_evaluator(evalFunc: Function) { throw new Error(`Wrong parameter type "${typeName}' in function "set_evaluator". It supposed to be a function and it's the entrance function of your metacircular evaulator.`); } INSTANCE.evalFunction = evalFunc; + INSTANCE.resultCallback = undefined; return { toReplString: () => '', }; } +/** + * Sets evaluator with jslang, then calls callback when results received. + * + * @param callback Callback with return value + */ +export function set_js_slang_evaluator_with_callback( + callback: (_: any) => void, +) { + INSTANCE.evalFunction = default_js_slang; + INSTANCE.resultCallback = callback; + return { + toReplString: () => '', + }; +} + + /** * Display message in Programmable Repl Tab diff --git a/src/bundles/repl/index.ts b/src/bundles/repl/index.ts index 456cccf5fb..6bff9d2641 100644 --- a/src/bundles/repl/index.ts +++ b/src/bundles/repl/index.ts @@ -39,6 +39,7 @@ export { set_evaluator, + set_js_slang_evaluator_with_callback, repl_display, set_background_image, set_font_size, diff --git a/src/bundles/repl/programmable_repl.ts b/src/bundles/repl/programmable_repl.ts index 77fa179729..dcc4b4ea9e 100644 --- a/src/bundles/repl/programmable_repl.ts +++ b/src/bundles/repl/programmable_repl.ts @@ -12,6 +12,7 @@ import { COLOR_RUN_CODE_RESULT, COLOR_ERROR_MESSAGE, DEFAULT_EDITOR_HEIGHT } fro export class ProgrammableRepl { public evalFunction: Function; + public resultCallback: ((result: any) => void) | undefined; public userCodeInEditor: string; public outputStrings: any[]; private _editorInstance; @@ -203,6 +204,7 @@ export class ProgrammableRepl { if (evalResult.status !== 'error') { this.pushOutputString('js-slang program finished with value:', COLOR_RUN_CODE_RESULT); // Here must use plain text output mode because evalResult.value contains strings from the users. + this.resultCallback?.(evalResult.value); this.pushOutputString(evalResult.value === undefined ? 'undefined' : evalResult.value.toString(), COLOR_RUN_CODE_RESULT); } else { const errors = context.errors;