Skip to content

Instantly share code, notes, and snippets.

@timetocode
Created April 10, 2013 01:13
Show Gist options
  • Save timetocode/5350943 to your computer and use it in GitHub Desktop.
Save timetocode/5350943 to your computer and use it in GitHub Desktop.
add console-like functionality to an html input, while staying decoupled follows a node.js module.exports style, so something like browserify is required before this console can be used as client-side javascript
# developer console
inputEle = null # the console's Prompt (an html input)
dispEle = null # the console's output (a div, span, etc)
submitAction = null # function to run on the input
enabled = false
exports.enable = () ->
# ensures html elements have been specified
# ensures that the console is not already active
if inputEle && dispEle && !enabled
enabled = true
captureInput() # capture keystrokes
exports.disable = () ->
enabled = false
if inputEle
inputEle.unbind 'keydown.console' # unbind only the '.console' namespace
inputEle = null
dispEle = null if dispEle
# specifies an html input to behave as the console prompt
exports.bindInputEle = (ele) ->
inputEle = ele
# specifies div that will display console output
exports.bindDispEle = (ele) ->
dispEle = ele
# specifies the action that will be run when the console submits input
# this action may return text or throw errors, and they will be displayed
exports.bindSubmitAction = (fn) ->
submitAction = fn
commands = [] # a log of commands issued to the console
pos = 0 # the position of the current command, used for scrolling through the log
captureInput = () ->
# '.console' is a namespace, so that we can unbind just this console handler later
inputEle.bind 'keydown.console', (e) ->
if e.keyCode is 38 # UP ARROW
# scroll 'up' aka backwards through previous console commands
if pos < commands.length
pos++
inputEle.val(commands[commands.length - pos])
if e.keyCode is 40 # DOWN ARROW
# scroll 'down' aka forwards through previous console commands
if pos > 0
pos--
inputEle.val(commands[commands.length - pos])
else
inputEle.val('') # clear the console prompt if we've scrolled to the end
if e.keyCode is 13 # ENTER
if inputEle.val() isnt ''
submitText = inputEle.val()
# remember this new command
commands.push submitText
# run the 'submitAction' supplying the text and display the return value or error
try
dispEle.html submitAction submitText
catch e
dispEle.html(e)
inputEle.val('') # clear the console after each command
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment