Equation terminal
by jhylands
HTML
<div id="terminal_div">
Welcome to you mathermatical terminal
</div>
<div id="entry_div">
<input id="entry_box" type="text" />
</div>
CSS
#entry_div{
position:absolute;
bottom:40px;
left:0px;
width:100%;
}
#entry_box{
width:100%;
}
#terminal_div{
position:absolute;
bottom:70px;
width:100%;
left:0px;
/*https://stackoverflow.com/questions/18614301/keep-overflow-div-scrolled-to-bottom-unless-user-scrolls-up*/
display: flex;
flex-direction: column-reverse;
}
.equation{
float:left;
/*https://stackoverflow.com/questions/1733006/how-to-set-an-images-width-and-height-without-stretching-it*/
object-fit:scale-down;
}
JavaScript
function Terminal(){
//terminal object to handle history and state
this.index = 0; //indicating a new entry
this.history = [];
this.up = function(){
if(this.index < this.history.length){
this.index ++;
}
return this.history[this.history.length-this.index];
};
this.down = function(){
if(this.index<=1){
this.index=0;
return "";
}else{
this.index--;
return this.history[this.history.length-this.index];
}
};
this.add = function(equation){
this.history.push(equation);
}
this.reset_index = function(){
this.index = 0;
}
}
var terminal = new Terminal();
function e(id){
return document.getElementById(id);
}
function append_to_terminal(content){
var box = e("terminal_div");
box.innerHTML = content + box.innerHTML;
}
function make_image(equation){
var url = "https://latex.codecogs.com/gif.latex?" + encodeURIComponent(equation);
var html = '<img class="equation" src ="' + url + '" /><br />';
return html;
}
function evaluate(){
//carry out the work once the use presses the enter key
var entry_box = e("entry_box");
var equation = entry_box.value;
terminal.add(equation);
terminal.reset_index();
//render
append_to_terminal(make_image(equation));
//cleanup
entry_box.value = "";
}
e("entry_box").addEventListener('keypress', function (event) {
if (event.key === 'Enter') {
console.log("enter log");
evaluate();
}
});
e("entry_box").addEventListener('keydown', function (event) {
if(event.key === "ArrowUp"){
console.log("up");
e("entry_box").value = terminal.up();
}else if(event.key ==="ArrowDown"){
console.log("down");
e("entry_box").value = terminal.down();
}
});