Run JavaScript: Support await and show errors

Adds a "Run as async function" checkbox that wraps the code in an async
function and displays the value returned by a `return` statement.

This also properly catches errors and displays them in the results pane.
This commit is contained in:
Dan Stillman 2019-01-22 01:29:05 -05:00
parent f918e27e46
commit 39eb2962a6
3 changed files with 63 additions and 6 deletions

View file

@ -10,12 +10,20 @@
<main>
<div class="textbox-container">
<label for="code">Code:</label>
<div class="textbox-header">
<label class="textbox-label" for="code">Code:</label>
<label id="run-as-async-label" for="run-as-async">
<input id="run-as-async" type="checkbox" onclick="update()">
Run as async function
</label>
</div>
<textarea id="code"></textarea>
</div>
<div class="textbox-container">
<label for="result">Result:</label>
<div class="textbox-header">
<label id="result-label" class="textbox-label" for="result"/>
</div>
<textarea id="result" readonly></textarea>
</div>
</main>

View file

@ -1,11 +1,35 @@
function run() {
function update() {
var isAsync = document.getElementById('run-as-async').checked;
var resultLabel = document.getElementById('result-label');
var val = isAsync ? 'Return value' : 'Result';
resultLabel.textContent = val + ':';
}
async function run() {
var win = Zotero.getMainWindow();
if (!win) {
return;
}
var code = document.getElementById('code').value;
var result = win.eval(code);
document.getElementById('result').value = Zotero.Utilities.varDump(result);
var isAsync = document.getElementById('run-as-async').checked;
var result;
var resultTextbox = document.getElementById('result');
try {
if (isAsync) {
code = '(async function () {' + code + '})()';
result = await win.eval(code);
}
else {
result = win.eval(code);
}
}
catch (e) {
resultTextbox.classList.add('error');
resultTextbox.value = e;
return;
}
resultTextbox.classList.remove('error');
resultTextbox.value = Zotero.Utilities.varDump(result);
}
window.addEventListener('keypress', function (event) {
@ -30,3 +54,5 @@ window.addEventListener('keypress', function (event) {
var shortcut = Zotero.isMac ? 'Cmd-R' : 'Ctrl+R';
document.getElementById('run-label').textContent = `(${shortcut})`;
update();

View file

@ -29,18 +29,41 @@ main {
flex-direction: column;
align-items: stretch;
flex-grow: 1;
font-size: 14px;
padding: 10px;
}
.textbox-header {
display: flex;
align-items: center;
justify-content: space-between;
line-height: 1.5;
}
.textbox-label {
font-size: 15px;
}
#run-as-async-label {
font-size: 13px;
}
label {
flex-grow: 0;
}
input[type=checkbox] {
margin-top: 0;
margin-bottom: 0;
}
textarea {
flex-grow: 1;
margin: 5px 0;
font-family: Monaco, Consolas, Inconsolata, monospace;
font-size: 12px;
resize: none;
}
textarea.error {
color: red;
}