Skip to content

Instantly share code, notes, and snippets.

@christianjuth
Created February 6, 2017 04:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christianjuth/441308a1ffa7629660e5afd7deaff3f4 to your computer and use it in GitHub Desktop.
Save christianjuth/441308a1ffa7629660e5afd7deaff3f4 to your computer and use it in GitHub Desktop.
Working Terminal
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://fonts.googleapis.com/css?family=Open+Sans|Roboto:900|Pacifico" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<link rel='stylesheet' href='style.css'/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src='script.js'></script>
</head>
<body>
<div class="terminal" draggable="true">
<textarea class="terminal-input"></textarea>
</div>
<a href="http://www.christianjuth.com" target="_blank" class="brand">Christian Juth</a>
</body>
</html>
class Terminal
constructor: (options)->
$this = this
{@prefix, @selector, @greeting, @hardDrive, @workingDirectory} = options
@workingDirectory = @workingDirectory.replace(/^\//, "")
if @greeting && @greeting != ""
@selector.val("#{@greeting}\n")
@selector.val("#{@selector.val()}#{@prefix}")
@history = []
@historySelected = -1
@exit = false
@selector.click ->
val = $this.selector.val()
$this.selector.val("")
$this.selector.val(val)
# handel keyboard events
@selector.keydown (e)->
if $this.exit == true
e.preventDefault()
else
content = $this.selector.val()
cL = content
cL = cL.substr(content.lastIndexOf("\n")+1)
rawLine = cL
cL = cL.replace(/\s+/g, " ");
cL = cL.replace($this.prefix,"")
currentLine = cL
# delete pressed
if e.which == 8 && rawLine.length <= $this.prefix.length
e.preventDefault()
else if e.which == 37
carretPosition = $this.selector.prop("selectionStart")
# find unselectable text
text = $this.selector.val()
text = text.replace(/\r?\n?[^\r\n]*$/,"")
text = "#{text}\n#{$this.prefix}"
if carretPosition <= text.length
e.preventDefault()
# enter pressed
else if e.which == 13
e.preventDefault()
$this.historySelected = -1
output = null
# add new blank line to terminal
$this.selector.val("#{$this.selector.val()}\n")
if currentLine.replace(/^\s+/g,"") != ""
$this.history.push(currentLine)
# execute each command separated by &&
currentLine.split("&&").forEach (stringInput)->
input = stringInput.replace(/^\s+/g,"").split(" ")
command = input.shift()
arg = input
# if command exists
if $this["#{command}Command"]
output = $this["#{command}Command"](arg)
# else throw error
else if command != ""
output = "-bash: #{command}: command not found"
# if command has output print
if output
$this.selector.val("#{$this.selector.val()}#{output}\n")
# when finished add new input line
# to terminal and scroll into place
if $this.exit == false
$this.selector.val("#{$this.selector.val()}#{$this.prefix}")
$this.selector.scrollTop($this.selector[0].scrollHeight);
# up arrow pressed
else if e.which == 38
e.preventDefault()
# if backwards history exsists
if $this.historySelected < $this.history.length - 1
# check number of lines
if $this.selector.val().split("\n").length > 1
prefix = "\n#{$this.prefix}"
else
prefix = $this.prefix
$this.selector.val($this.selector.val().replace(/\r?\n?[^\r\n]*$/, prefix))
i = $this.historySelected + 1
$this.selector.val("#{$this.selector.val()}#{$this.history[$this.history.length - 1 - i]}")
$this.historySelected = i
# down arror pressed
else if e.which == 40
e.preventDefault()
# check number of lines
if $this.selector.val().split("\n").length > 1
prefix = "\n#{$this.prefix}"
else
prefix = $this.prefix
$this.selector.val($this.selector.val().replace(/\r?\n?[^\r\n]*$/, prefix))
if $this.historySelected > 0
i = $this.historySelected - 1
$this.selector.val("#{$this.selector.val()}#{$this.history[$this.history.length - 1 - i]}")
$this.historySelected = i
# return to input line
else
$this.historySelected = -1
$this.selector.val($this.selector.val())
# ----- Terminal Commands ------
helpCommand: ->
["clear",
"echo [text]",
"exit",
"date",
"time",
"history",
"ls",
"cd [path]",
"pwd",
"cat [file]",
"head [file]",
"tail [file]"].sort().join("\n")
clearCommand: ->
@selector.val("")
null
echoCommand: (arg)->
arg[0]
dateCommand: ->
new Date()
pwdCommand: ->
"/#{@workingDirectory.replace(/\/$/,"")}"
lsCommand: (directory)->
$this = this
directory = directory[0]
wd = []
@fromDifferntLocation directory, ->
wd = $this.getWorkingDirectory()
wd = Object.keys(wd)
wd.join(" ")
cdCommand: (destination)->
destination = destination[0]
# we means working directory
unless @changeDirectory(destination)
"cd: #{destination}: No such directory"
rmCommand: (rmPath)->
$this = this
rmPath = rmPath[0]
path = rmPath.split("/")
fileName = path.splice(-1)
path = path.join("/")
wd = {}
if path == ""
path = "/"
@fromDifferntLocation path, ->
wd = $this.getWorkingDirectory()
if wd[fileName]?
delete wd[fileName]
null
else
"rm: #{rmPath}: No such file or directory"
catCommand: (path)->
path = path[0]
file = @getFile(path)
if file? && file != ""
file
else if file == ""
" "
else
"cat: #{path}: No such file"
headCommand: (path)->
path = path[0]
file = @getFile(path)
if file? && file != ""
file.split("\n").slice(0,4).join("\n")
else if file == ""
" "
else
"cat: #{path}: No such file"
tailCommand: (path)->
path = path[0]
file = @getFile(path)
if file && file != ""
length = file.length
file.split("\n").slice(-4,length).join("\n")
else if file == ""
" "
else
"cat: #{path}: No such file"
timeCommand: ->
(new Date()).toTimeString()
exitCommand: ->
@exit = true
"[Process completed]"
historyCommand: ->
$this = this
message = ""
history = @history.slice(-10)
history.forEach (historyItem, i)->
message = "#{message}#{history.length - i - 1} #{historyItem}\n"
message.replace(/\n$/,"")
# ------ Privet Functions -------
getFile: (path = "")->
$this = this
path = path.split("/")
fileName = path.splice(-1)
file = ""
path = path.join("/")
if path == ""
path = "/"
@fromDifferntLocation path, ->
file = $this.getWorkingDirectory()[fileName]
if typeof file != "object"
file
else
false
changeDirectory: (destination)->
# if get ~/ get from root
if destination == "~/"
wd = ""
destination = ""
@workingDirectory = wd
else if /^~\//.test(destination)
# wd means workingDirectory
wd = ""
destination = destination.replace(/^~\//,"")
# get relative path
else
wd = @workingDirectory.replace(/(\/$)/,"")
# if destination is current folder return
if destination.replace(/((^\/|\/$))/,"") == ""
return true
# fix [""] glitch
if wd != ""
wd = wd.split("/")
else
wd = []
destination = destination.replace(/\/$/,"").split("/")
destination.forEach (destination)->
if destination == ".."
wd.splice(-1)
else
wd.push(destination)
# verify folder
hardDrive = @hardDrive
error = false
wd.forEach (cd)->
if hardDrive[cd]? && typeof hardDrive[cd] == "object"
hardDrive = hardDrive[cd]
else
error = true
return false
unless error
@workingDirectory = wd.join("/").replace(/((^\/|\/$))/,"")
else
false
fromDifferntLocation: (path = "", callback)->
startingDir = "~/#{@workingDirectory}"
if @changeDirectory(path)
callback()
@changeDirectory(startingDir)
else
false
getWorkingDirectory: ->
wd = @workingDirectory
hardDrive = @hardDrive
if wd != ""
wd = wd.split("/")
wd.forEach (cd)->
hardDrive = hardDrive[cd]
hardDrive
$(document).ready ->
dateTime = (new Date()).toLocaleDateString('se')
terminal = new Terminal({
prefix: "MacBook:~ $ ",
greeting: "Type 'help' for commands",
selector: $(".terminal-input")
hardDrive: {
"User": {
"Desktop": {},
"Documents": {
"Welcome.txt": "Welcome to fake terminal by Christian Juth. Type 'help' for a list of commands.",
"License.txt": """
Copyright 2017 Christian Juth
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
},
"Movies": {},
"Music": {
"iTunes": {
"Album Artwork": {},
"iTunes Media": {
"Music": {},
"Movies": {}
}
}
},
"Pictures": {
"profile-picture": "?i?cU?@.rt?Rwђ0?N??@?Z]>r?*???|dk` 8?&%,??d,?f???eI?u?$?jY?????6?~_??2?N(^??1,.???e?????W?F?'????:??i??)??DND??vzp?Q?5?D`?C??
?????w??~?0A2?͌??-P??e?????????&??KІ?x7???y?tD?^05?Ȃ?\?$?5#]Ml?D`,?Kָ?rh?+??q??Ғ/??????F?L,FVfV?/??????.5˛)@7??Dղ?p??????ׁ?`>???׌75????.?J??t???)??^???.??Q*+??z?ǧ?QP??????Z?Q+n_XI`?7ìH9(K???dB??\Ax????/]e??Ky1??I3?N????.??ձ3Wa??d+u??F?L??+"
}
},
"Applications": {},
"System": {}
},
workingDirectory: "User"
})
html,
body{
height: 100%;
margin: 0;
padding: 0;
overflow: visible;
display: flex;
align-items: center;
justify-content: center;
background-color: #3498db;
}
.terminal{
position: relative;
background-color: #111;
height: 300px;
width: 500px;
border-top: 21px solid #ecf0f1;
border-radius: 5px;
-webkit-box-shadow: 0px 13px 49px -24px rgba(0,0,0,0.75);
-moz-box-shadow: 0px 13px 49px -24px rgba(0,0,0,0.75);
box-shadow: 0px 13px 49px -24px rgba(0,0,0,0.75);
}
.terminal:before{
content: " ";
display: block;
position: absolute;
background-color: #e74c3c;
color: #fff;
height: 12px;
width: 12px;
border-radius: 100%;
top: -16px;
left: 4px;
}
.terminal:after{
content: "- bash -";
display: block;
position: absolute;
top: -19px;
width: 100%;
text-align: center;
}
.terminal-input{
height: 100%;
width: 100%;
background-color: #111;
padding: 10px;
border: 0;
color: #fff;
font-size: 14px;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.terminal-input,
.terminal-input:focus{
outline: none;
resize: none;
border-radius: 5px;
font-family: Courier;
}
textarea::-webkit-input-placeholder{
width: 10px;
text-shadow: none;
-webkit-text-fill-color: #f00;
}
.brand,
.brand:visited{
position: absolute;
padding: 0;
margin: 0;
bottom: 5px;
right: 10px;
text-decoration: none;
color: rgba(0,0,0,0.4);
font-size: 14px;
font-family: 'Pacifico', cursive;
}
.brand:hover{
text-decoration: underline;
}
/* --- Codecademy preview ---- */
@media screen and (max-width: 300px) and (max-height: 200px){
.brand,
.brand:visited{
display: none;
}
.terminal{
padding: 0;
height: 80px;
width: 230px;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment