Skip to content

Commit

Permalink
ag-solo: reconnect to websocket on close
Browse files Browse the repository at this point in the history
fixes Agoric#13
  • Loading branch information
michaelfig committed Jun 20, 2019
1 parent 71be0a4 commit 11d5ec8
Showing 1 changed file with 44 additions and 2 deletions.
46 changes: 44 additions & 2 deletions lib/ag-solo/html/main.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
/* global WebSocket fetch document window */
const RECONNECT_BACKOFF_SECONDS = 3;
// Functions to run to reset the HTML state to what it was.
const resetFns = [];
let inpBackground;

function run() {
const disableFns = []; // Functions to run when the input should be disabled.
resetFns.push(() => (document.querySelector('#history').innerHTML = ''));

let nextHistNum = 0;
const historyNumberElements = document.querySelectorAll('.historyNumber');

Expand Down Expand Up @@ -30,13 +37,30 @@ function run() {

ws.addEventListener('error', ev => {
console.log(`ws.error ${ev}`);
ws.close();
});

ws.addEventListener('open', _ev => {
console.log(`ws.open!`);
while (resetFns.length > 0) {
const fn = resetFns.shift();
try {
fn();
} catch (e) {
console.error(`error resetting`, e);
}
}
call({ type: 'rebroadcastHistory' });
});

ws.addEventListener('close', _ev => {
for (const fn of disableFns) {
fn();
}
console.log(`Reconnecting in ${RECONNECT_BACKOFF_SECONDS} seconds`);
setTimeout(run, RECONNECT_BACKOFF_SECONDS * 1000);
});

function addEntry(histnum, command, display) {
const c = document.createElement('div');
c.setAttribute('id', `command-${histnum}`);
Expand Down Expand Up @@ -140,13 +164,31 @@ function run() {
call({ type: 'doEval', number, body: command });
}

inp.addEventListener('keypress', ev => {
function inputKeypress(ev) {
if (ev.keyCode === 13) {
submitEval();
}
});
}
inp.addEventListener('keypress', inputKeypress);
disableFns.push(() => inp.removeEventListener('keypress', inputKeypress));

if (inpBackground === undefined) {
inpBackground = inp.style.background;
}
disableFns.push(() => (inp.style.background = '#ff0000'));
resetFns.push(() => (inp.style.background = inpBackground));

inp.focus();

document.getElementById('go').onclick = submitEval;
disableFns.push(() =>
document.getElementById('go').setAttribute('disabled', 'disabled'),
);
resetFns.push(() =>
document.getElementById('go').removeAttribute('disabled'),
);

call({ type: 'getCanvasState' }).then(msg => handleMessage(msg));
}

run();

0 comments on commit 11d5ec8

Please sign in to comment.