Created
June 23, 2022 01:33
-
-
Save coreybutler/544b73e4d608bab97f0871136274daf9 to your computer and use it in GitHub Desktop.
A basic implementation of the shell in the browser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<title>Shell Example</title> | |
<style> | |
.answer { | |
padding: 12px 0; | |
font-weight: bold; | |
} | |
.command { | |
padding: 6px 0; | |
font-family: 'Courier New', Courier, monospace; | |
} | |
</style> | |
<script type="module"> | |
import { Shell, Command } from 'https://cdn.pika.dev/@author.io/shell' | |
// Define "sum" command | |
const SumCommand = new Command({ | |
name: 'sum', | |
alias: 'add', | |
description: 'Add numbers to a total', | |
handler (meta) { | |
let total = 0 | |
for (const value of meta.flags.unrecognized) { | |
const parsed = parseInt(value, 10) | |
if (!isNaN(value)) { | |
total += parsed | |
} | |
} | |
document.querySelector('.answer').innerHTML = total | |
console.log(total) | |
} | |
}) | |
const MultiplyCommand = new Command({ | |
name: 'multiply', | |
alias: 'times', | |
description: 'Multiply several numbers', | |
handler (meta) { | |
let total = 1 | |
for (const value of meta.flags.unrecognized) { | |
const parsed = parseInt(value, 10) | |
if (!isNaN(value)) { | |
total = total * parsed | |
} | |
} | |
document.querySelector('.answer').innerHTML = total | |
console.log(total) | |
} | |
}) | |
// Define the shell | |
const shell = new Shell({ | |
name: 'calc', | |
description: 'Basic calculator', | |
version: '1.0.0', | |
commands: [ | |
SumCommand, | |
MultiplyCommand | |
] | |
}) | |
// Expose the shell globally as "calc" | |
globalThis.calc = shell | |
console.log(shell.help) | |
function getInput() { | |
return document.querySelector('#input').value.replace(/[^0-9]/gi, ' ').replace(/\s+/gi, ' ') | |
} | |
// Create globally accessible functions for the buttons | |
globalThis.add = function() { | |
const cmd = `sum ${getInput()}` | |
document.querySelector('.command').innerHTML = `calc ${cmd}` | |
console.log(`await calc.exec('${cmd}')`) | |
shell.exec(cmd) | |
} | |
globalThis.multiply = function() { | |
const cmd = `multiply ${getInput()}` | |
document.querySelector('.command').innerHTML = `calc ${cmd}` | |
console.log(`await calc.exec('${cmd}')`) | |
shell.exec(cmd) | |
} | |
</script> | |
</head> | |
<body> | |
<input id="input" type="text" placeholder="1, 2, 3"/> | |
<br/> | |
<div class="answer"></div> | |
<button onclick="add()">Add</button> | |
<button onclick="multiply()">Multiply</button> | |
<div class="command"></div> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment