Created
January 25, 2018 23:02
-
-
Save s1sw/0b3544acfbda0fe2bbb206e4266ba50b to your computer and use it in GitHub Desktop.
A simple fake terminal in Javascript. Requires ES6 and jQuery, but could easily be changed to not use these.
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
/* global $ */ | |
window.terminalCommands = {}; | |
var terminalElement = undefined; | |
var templateCommand = undefined; | |
var currentCommandElement = undefined; | |
function writeOutput(outputString) { | |
var outputElement = document.createElement("div"); | |
outputElement.innerHTML = outputString; | |
terminalElement.append(outputElement); | |
} | |
function createNewCurrentCommandElement() { | |
if(currentCommandElement !== undefined) { | |
currentCommandElement.off("keypress"); | |
currentCommandElement.children(".terminal-input").attr("contenteditable", "false"); | |
} | |
currentCommandElement = templateCommand.clone(true); | |
currentCommandElement.attr("id", ""); | |
currentCommandElement.keypress(onCommandEntryKeypress); | |
terminalElement.append(currentCommandElement); | |
currentCommandElement.children(".terminal-input").focus(); | |
} | |
function onCommandEntered(commandString) { | |
console.log(commandString); | |
var args = commandString.split(" "); | |
var command = args[0]; | |
args = args.splice(1); | |
var outputString; | |
if(window.terminalCommands.hasOwnProperty(commandString)) { | |
outputString = window.terminalCommands[commandString](args); | |
} | |
else { | |
outputString = commandString + ": command not found"; | |
} | |
writeOutput(outputString); | |
createNewCurrentCommandElement(); | |
} | |
function onCommandEntryKeypress(event) { | |
if(event.which == 13) { | |
event.preventDefault(); | |
onCommandEntered(currentCommandElement.children(".terminal-input").text()); | |
} | |
} | |
$(document).ready(() => { | |
terminalElement = $("#terminal"); | |
templateCommand = terminalElement.children("#command-template"); | |
createNewCurrentCommandElement(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment