New jsinterpreter demo includes wait block. Both demos have improved UI for clarity. (#1001)

Refactor of interpreter demo
 * Renamed demos/interpreter/index.html as demos/interpreter/step-execution.html (including redirect), and added demos/interpreter/async-execution.html.
 * Refactored code to automatically generate/parse the blocks, eliminating the need for a "Parse JavaScript" button. Code is still shown in alert upon stepping to the first statement. Print statements now write to output <textarea> instead of modal dialogs.
This commit is contained in:
Andrew n marshall
2017-05-01 17:28:34 -07:00
committed by GitHub
parent db26c4c541
commit fb020f1c06
5 changed files with 587 additions and 195 deletions

View File

@@ -107,8 +107,9 @@
</a>
</td>
<td>
<div><a href="interpreter/index.html">JS Interpreter</a></div>
<div>Step by step execution in JavaScript.</div>
<div style="font-weight: bold">JS Interpreter</div>
<div>Demo #1: <a href="interpreter/step-execution.html">Step by step execution in JavaScript.</a></div>
<div>Demo #2: <a href="interpreter/async-execution.html">Asynchronous execution in JavaScript.</a></div>
</td>
</tr>

View File

@@ -0,0 +1,262 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Blockly Demo: Asynchronous Execution with JS Interpreter</title>
<script src="acorn_interpreter.js"></script>
<script src="../../blockly_compressed.js"></script>
<script src="../../blocks_compressed.js"></script>
<script src="../../javascript_compressed.js"></script>
<script src="../../msg/js/en.js"></script>
<script src="wait_block.js"></script>
<style>
body {
background-color: #fff;
font-family: sans-serif;
}
h1 {
font-weight: normal;
font-size: 140%;
}
</style>
</head>
<body>
<h1><a href="https://developers.google.com/blockly/">Blockly</a> &gt;
<a href="../index.html">Demos</a> &gt; Asynchronous Execution with JS Interpreter</h1>
<p>This is a demo of executing code asychronously (e.g., waiting for delays or user input) using the JavaScript interpreter.</p>
<p>&rarr; <a href="https://developers.google.com/blockly/guides/configure-blockly/web/running-javascript#js_interpreter">More info on running code with JS Interpreter</a></p>
<p>
<button onclick="runCode()" id="runButton">Run JavaScript</button>
</p>
<div style="width: 100%">
<div id="blocklyDiv"
style="display: inline-block; height: 480px; width: 58%"></div>
<textarea id="output" disabled="disabled"
style="display: inline-block; height: 480px; width: 38%;">
</textarea>
</div>
<xml id="toolbox" style="display: none">
<category name="Logic">
<block type="controls_if"></block>
<block type="logic_compare"></block>
<block type="logic_operation"></block>
<block type="logic_negate"></block>
<block type="logic_boolean"></block>
</category>
<category name="Loops">
<block type="controls_repeat_ext">
<value name="TIMES">
<block type="math_number">
<field name="NUM">10</field>
</block>
</value>
</block>
<block type="controls_whileUntil"></block>
</category>
<category name="Math">
<block type="math_number"></block>
<block type="math_arithmetic"></block>
<block type="math_single"></block>
</category>
<category name="Text">
<block type="text"></block>
<block type="text_length"></block>
<block type="text_print"></block>
<block type="text_prompt_ext">
<value name="TEXT">
<block type="text"></block>
</value>
</block>
</category>
<category name="Variables" custom="VARIABLE"></category>
<category name="Functions" custom="PROCEDURE"></category>
</xml>
<xml id="startBlocks" style="display: none">
<block type="variables_set" id="set_n_initial" inline="true" x="20" y="20">
<field name="VAR">n</field>
<value name="VALUE">
<block type="math_number">
<field name="NUM">1</field>
</block>
</value>
<next>
<block type="controls_repeat_ext" id="repeat" inline="true">
<value name="TIMES">
<block type="math_number">
<field name="NUM">4</field>
</block>
</value>
<statement name="DO">
<block type="wait_seconds" id="wait">
<field name="SECONDS">1.0</field>
<next>
<block type="variables_set" id="set_n_update" inline="true">
<field name="VAR">n</field>
<value name="VALUE">
<block type="math_arithmetic" inline="true">
<field name="OP">MULTIPLY</field>
<value name="A">
<block type="variables_get">
<field name="VAR">n</field>
</block>
</value>
<value name="B">
<block type="math_number">
<field name="NUM">2</field>
</block>
</value>
</block>
</value>
<next>
<block type="text_print" id="print" inline="false">
<value name="TEXT">
<block type="variables_get">
<field name="VAR">n</field>
</block>
</value>
</block>
</next>
</block>
</next>
</block>
</statement>
</block>
</next>
</block>
</xml>
<script>
var workspace = Blockly.inject('blocklyDiv',
{media: '../../media/',
toolbox: document.getElementById('toolbox')});
Blockly.Xml.domToWorkspace(document.getElementById('startBlocks'),
workspace);
// Exit is used to signal the end of a script.
Blockly.JavaScript.addReservedWords('exit');
var outputArea = document.getElementById('output');
var runButton = document.getElementById('runButton');
var myInterpreter = null;
var runner;
function initApi(interpreter, scope) {
// Add an API function for the alert() block, generated for "text_print" blocks.
var wrapper = function(text) {
text = text ? text.toString() : '';
outputArea.value = outputArea.value + '\n' + text;
};
interpreter.setProperty(scope, 'alert',
interpreter.createNativeFunction(wrapper));
// Add an API function for the prompt() block.
var wrapper = function(text) {
text = text ? text.toString() : '';
return interpreter.createPrimitive(prompt(text));
};
interpreter.setProperty(scope, 'prompt',
interpreter.createNativeFunction(wrapper));
// Add an API for the wait block. See wait_block.js
initInterpreterWaitForSeconds(interpreter, scope);
// Add an API function for highlighting blocks.
var wrapper = function(id) {
id = id ? id.toString() : '';
return interpreter.createPrimitive(highlightBlock(id));
};
interpreter.setProperty(scope, 'highlightBlock',
interpreter.createNativeFunction(wrapper));
}
var highlightPause = false;
var latestCode = '';
function highlightBlock(id) {
workspace.highlightBlock(id);
highlightPause = true;
}
function resetStepUi(clearOutput) {
workspace.highlightBlock(null);
highlightPause = false;
runButton.disabled = '';
if (clearOutput) {
outputArea.value = 'Program output:\n=================';
}
}
function generateCodeAndLoadIntoInterpreter() {
// Generate JavaScript code and parse it.
Blockly.JavaScript.STATEMENT_PREFIX = 'highlightBlock(%1);\n';
Blockly.JavaScript.addReservedWords('highlightBlock');
latestCode = Blockly.JavaScript.workspaceToCode(workspace);
resetStepUi(true);
}
function resetInterpreter() {
myInterpreter = null;
if (runner) {
clearTimeout(runner);
runner = null;
}
}
function runCode() {
if (!myInterpreter) {
// First statement of this code.
// Clear the program output.
resetStepUi(true);
runButton.disabled = 'disabled';
// And then show generated code in an alert.
// In a timeout to allow the outputArea.value to reset first.
setTimeout(function() {
alert('Ready to execute the following code\n' +
'===================================\n' +
latestCode);
// Begin execution
highlightPause = false;
myInterpreter = new Interpreter(latestCode, initApi);
runner = function() {
if (myInterpreter) {
var hasMore = myInterpreter.run();
if (hasMore) {
// Execution is currently blocked by some async call.
// Try again later.
setTimeout(runner, 10);
} else {
// Program is complete.
outputArea.value += '\n\n<< Program complete >>';
resetInterpreter();
resetStepUi(false);
}
}
};
runner();
}, 1);
return;
}
}
// Load the interpreter now, and upon future changes.
generateCodeAndLoadIntoInterpreter();
workspace.addChangeListener(function(event) {
if (!(event instanceof Blockly.Events.Ui)) {
// Something changed. Parser needs to be reloaded.
resetInterpreter();
generateCodeAndLoadIntoInterpreter();
}
});
</script>
</body>
</html>

View File

@@ -1,200 +1,11 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Blockly Demo: JS Interpreter</title>
<script src="acorn_interpreter.js"></script>
<script src="../../blockly_compressed.js"></script>
<script src="../../blocks_compressed.js"></script>
<script src="../../javascript_compressed.js"></script>
<script src="../../msg/js/en.js"></script>
<style>
body {
background-color: #fff;
font-family: sans-serif;
}
h1 {
font-weight: normal;
font-size: 140%;
}
</style>
<meta charset="utf-8"/>
<title>Redirecting...</title>
<meta http-equiv="refresh" content="0;URL='step-execution.html'"/>
</head>
<body>
<h1><a href="https://developers.google.com/blockly/">Blockly</a> &gt;
<a href="../index.html">Demos</a> &gt; JS Interpreter</h1>
<p>This is a simple demo of executing code with a sandboxed JavaScript interpreter.</p>
<p>&rarr; More info on <a href="https://developers.google.com/blockly/guides/configure-blockly/web/running-javascript#js_interpreter">JS Interpreter</a>&hellip;</p>
<p>
<button onclick="parseCode()">Parse JavaScript</button>
<button onclick="stepCode()" id="stepButton" disabled="disabled">Step JavaScript</button>
</p>
<div id="blocklyDiv" style="height: 480px; width: 600px;"></div>
<xml id="toolbox" style="display: none">
<category name="Logic">
<block type="controls_if"></block>
<block type="logic_compare"></block>
<block type="logic_operation"></block>
<block type="logic_negate"></block>
<block type="logic_boolean"></block>
</category>
<category name="Loops">
<block type="controls_repeat_ext">
<value name="TIMES">
<block type="math_number">
<field name="NUM">10</field>
</block>
</value>
</block>
<block type="controls_whileUntil"></block>
</category>
<category name="Math">
<block type="math_number"></block>
<block type="math_arithmetic"></block>
<block type="math_single"></block>
</category>
<category name="Text">
<block type="text"></block>
<block type="text_length"></block>
<block type="text_print"></block>
<block type="text_prompt_ext">
<value name="TEXT">
<block type="text"></block>
</value>
</block>
</category>
<category name="Variables" custom="VARIABLE"></category>
<category name="Functions" custom="PROCEDURE"></category>
</xml>
<xml id="startBlocks" style="display: none">
<block type="variables_set" inline="true" x="20" y="20">
<field name="VAR">n</field>
<value name="VALUE">
<block type="math_number">
<field name="NUM">1</field>
</block>
</value>
<next>
<block type="controls_repeat_ext" inline="true">
<value name="TIMES">
<block type="math_number">
<field name="NUM">4</field>
</block>
</value>
<statement name="DO">
<block type="variables_set" inline="true">
<field name="VAR">n</field>
<value name="VALUE">
<block type="math_arithmetic" inline="true">
<field name="OP">MULTIPLY</field>
<value name="A">
<block type="variables_get">
<field name="VAR">n</field>
</block>
</value>
<value name="B">
<block type="math_number">
<field name="NUM">2</field>
</block>
</value>
</block>
</value>
</block>
</statement>
<next>
<block type="text_print" inline="false">
<value name="TEXT">
<block type="variables_get">
<field name="VAR">n</field>
</block>
</value>
</block>
</next>
</block>
</next>
</block>
</xml>
<script>
var workspace = Blockly.inject('blocklyDiv',
{media: '../../media/',
toolbox: document.getElementById('toolbox')});
Blockly.Xml.domToWorkspace(document.getElementById('startBlocks'),
workspace);
var myInterpreter = null;
function initApi(interpreter, scope) {
// Add an API function for the alert() block.
var wrapper = function(text) {
text = text ? text.toString() : '';
return interpreter.createPrimitive(alert(text));
};
interpreter.setProperty(scope, 'alert',
interpreter.createNativeFunction(wrapper));
// Add an API function for the prompt() block.
var wrapper = function(text) {
text = text ? text.toString() : '';
return interpreter.createPrimitive(prompt(text));
};
interpreter.setProperty(scope, 'prompt',
interpreter.createNativeFunction(wrapper));
// Add an API function for highlighting blocks.
var wrapper = function(id) {
id = id ? id.toString() : '';
return interpreter.createPrimitive(highlightBlock(id));
};
interpreter.setProperty(scope, 'highlightBlock',
interpreter.createNativeFunction(wrapper));
}
var highlightPause = false;
function highlightBlock(id) {
workspace.highlightBlock(id);
highlightPause = true;
}
function parseCode() {
// Generate JavaScript code and parse it.
Blockly.JavaScript.STATEMENT_PREFIX = 'highlightBlock(%1);\n';
Blockly.JavaScript.addReservedWords('highlightBlock');
var code = Blockly.JavaScript.workspaceToCode(workspace);
myInterpreter = new Interpreter(code, initApi);
alert('Ready to execute this code:\n\n' + code);
document.getElementById('stepButton').disabled = '';
highlightPause = false;
workspace.highlightBlock(null);
}
function stepCode() {
try {
var ok = myInterpreter.step();
} finally {
if (!ok) {
// Program complete, no more code to execute.
document.getElementById('stepButton').disabled = 'disabled';
workspace.highlightBlock(null);
return;
}
}
if (highlightPause) {
// A block has been highlighted. Pause execution here.
highlightPause = false;
} else {
// Keep executing until a highlight statement is reached.
stepCode();
}
}
</script>
Redirecting to <a href="step-execution.html">step execution jsinterpreter demo</a>.
</body>
</html>

View File

@@ -0,0 +1,251 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Blockly Demo: Step Execution with JS Interpreter</title>
<script src="acorn_interpreter.js"></script>
<script src="../../blockly_compressed.js"></script>
<script src="../../blocks_compressed.js"></script>
<script src="../../javascript_compressed.js"></script>
<script src="../../msg/js/en.js"></script>
<style>
body {
background-color: #fff;
font-family: sans-serif;
}
h1 {
font-weight: normal;
font-size: 140%;
}
</style>
</head>
<body>
<h1><a href="https://developers.google.com/blockly/">Blockly</a> &gt;
<a href="../index.html">Demos</a> &gt; Step Execution with JS Interpreter</h1>
<p>This is a demo of executing code step-by-step with a sandboxed JavaScript interpreter.</p>
<p>The generator's <code>Blockly.JavaScript.STATEMENT_PREFIX</code> is assigned <code>'highlightBlock(%1);\n'</code>,
where <code>%1</code> is the block id. The call to <code>highlightBlock()</code> will highlight the identified block
and set the variable <code>highlightPause</code> to <code>true</code>.</p>
<p>"Parse JavaScript" will generate the code and load it into the interpreter. Then, each press of the
"Step JavaScript" button will run the interpreter one step until the <code>highlightPause</code> is true.
That is, until <code>highlightBlock()</code> has highlighted the block that will be executed on the next step.</p>
<p>&rarr; <a href="https://developers.google.com/blockly/guides/configure-blockly/web/running-javascript#js_interpreter">More info on running code with JS Interpreter</a></p>
<p>
<button onclick="stepCode()" id="stepButton">Step JavaScript</button>
</p>
<div style="width: 100%">
<div id="blocklyDiv"
style="display: inline-block; height: 480px; width: 58%"></div>
<textarea id="output" disabled="disabled"
style="display: inline-block; height: 480px; width: 38%;">
</textarea>
</div>
<xml id="toolbox" style="display: none">
<category name="Logic">
<block type="controls_if"></block>
<block type="logic_compare"></block>
<block type="logic_operation"></block>
<block type="logic_negate"></block>
<block type="logic_boolean"></block>
</category>
<category name="Loops">
<block type="controls_repeat_ext">
<value name="TIMES">
<block type="math_number">
<field name="NUM">10</field>
</block>
</value>
</block>
<block type="controls_whileUntil"></block>
</category>
<category name="Math">
<block type="math_number"></block>
<block type="math_arithmetic"></block>
<block type="math_single"></block>
</category>
<category name="Text">
<block type="text"></block>
<block type="text_length"></block>
<block type="text_print"></block>
<block type="text_prompt_ext">
<value name="TEXT">
<block type="text"></block>
</value>
</block>
</category>
<category name="Variables" custom="VARIABLE"></category>
<category name="Functions" custom="PROCEDURE"></category>
</xml>
<xml id="startBlocks" style="display: none">
<block type="variables_set" id="set_n_initial" inline="true" x="20" y="20">
<field name="VAR">n</field>
<value name="VALUE">
<block type="math_number">
<field name="NUM">1</field>
</block>
</value>
<next>
<block type="controls_repeat_ext" id="repeat" inline="true">
<value name="TIMES">
<block type="math_number">
<field name="NUM">4</field>
</block>
</value>
<statement name="DO">
<block type="variables_set" id="set_n_update" inline="true">
<field name="VAR">n</field>
<value name="VALUE">
<block type="math_arithmetic" inline="true">
<field name="OP">MULTIPLY</field>
<value name="A">
<block type="variables_get">
<field name="VAR">n</field>
</block>
</value>
<value name="B">
<block type="math_number">
<field name="NUM">2</field>
</block>
</value>
</block>
</value>
<next>
<block type="text_print" id="print">
<value name="TEXT">
<block type="variables_get">
<field name="VAR">n</field>
</block>
</value>
</block>
</next>
</block>
</statement>
</block>
</next>
</block>
</xml>
<script>
var workspace = Blockly.inject('blocklyDiv',
{media: '../../media/',
toolbox: document.getElementById('toolbox')});
Blockly.Xml.domToWorkspace(document.getElementById('startBlocks'),
workspace);
var outputArea = document.getElementById('output');
var stepButton = document.getElementById('stepButton');
var myInterpreter = null;
function initApi(interpreter, scope) {
// Add an API function for the alert() block, generated for "text_print" blocks.
interpreter.setProperty(scope, 'alert',
interpreter.createNativeFunction(function(text) {
text = text ? text.toString() : '';
outputArea.value += '\n' + text;
}));
// Add an API function for the prompt() block.
var wrapper = function(text) {
text = text ? text.toString() : '';
return interpreter.createPrimitive(prompt(text));
};
interpreter.setProperty(scope, 'prompt',
interpreter.createNativeFunction(wrapper));
// Add an API function for highlighting blocks.
var wrapper = function(id) {
id = id ? id.toString() : '';
return interpreter.createPrimitive(highlightBlock(id));
};
interpreter.setProperty(scope, 'highlightBlock',
interpreter.createNativeFunction(wrapper));
}
var highlightPause = false;
var latestCode = '';
function highlightBlock(id) {
workspace.highlightBlock(id);
highlightPause = true;
}
function resetStepUi(clearOutput) {
workspace.highlightBlock(null);
highlightPause = false;
if (clearOutput) {
outputArea.value = 'Program output:\n=================';
}
}
function generateCodeAndLoadIntoInterpreter() {
// Generate JavaScript code and parse it.
Blockly.JavaScript.STATEMENT_PREFIX = 'highlightBlock(%1);\n';
Blockly.JavaScript.addReservedWords('highlightBlock');
latestCode = Blockly.JavaScript.workspaceToCode(workspace);
resetStepUi(true);
}
function stepCode() {
if (!myInterpreter) {
// First statement of this code.
// Clear the program output.
resetStepUi(true);
myInterpreter = new Interpreter(latestCode, initApi);
// And then show generated code in an alert.
// In a timeout to allow the outputArea.value to reset first.
setTimeout(function() {
alert('Ready to execute the following code\n' +
'===================================\n' + latestCode);
highlightPause = true;
stepCode();
}, 1);
return;
}
highlightPause = false;
do {
try {
var hasMoreCode = myInterpreter.step();
} finally {
if (!hasMoreCode) {
// Program complete, no more code to execute.
outputArea.value += '\n\n<< Program complete >>';
myInterpreter = null;
resetStepUi(false);
// Cool down, to discourage accidentally restarting the program.
stepButton.disabled = 'disabled';
setTimeout(function() {
stepButton.disabled = '';
}, 2000);
return;
}
}
// Keep executing until a highlight statement is reached,
// or the code completes or errors.
} while (hasMoreCode && !highlightPause);
}
// Load the interpreter now, and upon future changes.
generateCodeAndLoadIntoInterpreter();
workspace.addChangeListener(function(event) {
if (!(event instanceof Blockly.Events.Ui)) {
// Something changed. Parser needs to be reloaded.
generateCodeAndLoadIntoInterpreter();
}
});
</script>
</body>
</html>

View File

@@ -0,0 +1,67 @@
/**
* @license
* Visual Blocks Editor
*
* Copyright 2017 Google Inc.
* https://developers.google.com/blockly/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Example "wait" block that will pause the interpreter for a
* number of seconds. Because wait is a blocking behavior, such blocks will
* only work in interpreted environments.
*
* See https://neil.fraser.name/software/JS-Interpreter/docs.html
*/
Blockly.defineBlocksWithJsonArray([{
"type": "wait_seconds",
"message0": " wait %1 seconds",
"args0": [{
"type": "field_number",
"name": "SECONDS",
"min": 0,
"max": 600,
"value": 1
}],
"previousStatement": null,
"nextStatement": null,
"colour": "%{BKY_LOOPS_HUE}"
}]);
/**
* Generator for wait block creates call to new method
* <code>waitForSeconds()</code>.
*/
Blockly.JavaScript['wait_seconds'] = function(block) {
var seconds = Number(block.getFieldValue('SECONDS'));
var code = 'waitForSeconds(' + seconds + ');\n';
return code;
};
/**
* Register the interpreter asynchronous function
* <code>waitForSeconds()</code>.
*/
function initInterpreterWaitForSeconds(interpreter, scope) {
// Ensure function name does not conflict with variable names.
Blockly.JavaScript.addReservedWords('waitForSeconds');
var wrapper = interpreter.createAsyncFunction(
function(timeInSeconds, callback) {
// Delay the call to the callback.
setTimeout(callback, timeInSeconds * 1000);
});
interpreter.setProperty(scope, 'waitForSeconds', wrapper);
}