Git Product home page Git Product logo

jq-console's Introduction

jq-console

A jQuery terminal plugin written in CoffeeScript.

This project was spawned because of our need for a simple web terminal plugin for the repl.it project. It tries to simulate a low level terminal by providing (almost) raw input/output streams as well as input and output states.

Version 2.0 adds baked-in support for rich multi-line prompting and operation queueing.

Tested Browsers

The plugin has been tested on the following browsers:

  • IE 9+
  • Chrome
  • Firefox
  • Opera
  • iOS Safari and Chrome
  • Android Chrome

Getting Started

Echo example

    /* The console container element */
    #console {
      position: absolute;
      width: 400px;
      height: 500px;
      background-color:black;
    }
    /* The inner console element. */
    .jqconsole {
        padding: 10px;
    }
    /* The cursor. */
    .jqconsole-cursor {
        background-color: gray;
    }
    /* The cursor color when the console looses focus. */
    .jqconsole-blurred .jqconsole-cursor {
        background-color: #666;
    }
    /* The current prompt text color */
    .jqconsole-prompt {
        color: #0d0;
    }
    /* The command history */
    .jqconsole-old-prompt {
        color: #0b0;
        font-weight: normal;
    }
    /* The text color when in input mode. */
    .jqconsole-input {
        color: #dd0;
    }
    /* Previously entered input. */
    .jqconsole-old-input {
        color: #bb0;
        font-weight: normal;
    }
    /* The text color of the output. */
    .jqconsole-output {
        color: white;
    }
    <div id="console"></div>
    <script src="jquery.js" type="text/javascript" charset="utf-8"></script>
    <script src="jqconsole.js" type="text/javascript" charset="utf-8"></script>
    <script>
      $(function () {
        var jqconsole = $('#console').jqconsole('Hi\n', '>>>');
        var startPrompt = function () {
          // Start the prompt with history enabled.
          jqconsole.Prompt(true, function (input) {
            // Output input with the class jqconsole-output.
            jqconsole.Write(input + '\n', 'jqconsole-output');
            // Restart the prompt.
            startPrompt();
          });
        };
        startPrompt();
      });
    </script>
<iframe src="demo/echo.html" style="width:400px;height:500px"> </iframe>

Instantiating

    $(div).jqconsole(welcomeString, promptLabel, continueLabel, disableAutoFocus);
  • div is the div element or selector. Note that this element must be explicity sized and positioned absolute or relative.
  • welcomeString is the string to be shown when the terminal is first rendered.
  • promptLabel is the label to be shown before the input when using Prompt().
  • continueLabel is the label to be shown before the continued lines of the input when using Prompt().
  • disableAutoFocus is a boolean indicating whether we should disable the default auto-focus behavior.

Configuration

There isn't much initial configuration needed, because the user must supply options and callbacks with each state change. There are a few config methods provided to create custom shortcuts and change indentation width:

jqconsole.RegisterShortcut

Registers a callback for a keyboard shortcut. Takes two arguments:

  • (int|string) keyCode: The code of the key pressing which (when Ctrl is held) will trigger this shortcut. If a string is provided, the ASCII code of the first character is taken.

  • function callback: A function called when the shortcut is pressed; "this" will point to the JQConsole object.

Example:

    // Ctrl+R: resets the console.
    jqconsole.RegisterShortcut('R', function() {
      this.Reset();
    });

jqconsole.SetIndentWidth

Sets the number of spaces inserted when indenting and removed when unindenting. Takes one argument:

  • int width: The number of spaces in each indentation level.

Example:

    // Sets the indent width to 4 spaces.
    jqconsole.SetIndentWidth(4);

jqconsole.RegisterMatching

Registers an opening and closing characters to match and wraps each of the opening and closing characters with a span with the specified class. Takes one parameters:

  • char open: The opening character of a "block".
  • char close: The closing character of a "block".
  • string class: The css class that is applied to the matched characters.

Example:

    jqconsole.RegisterMatching('{', '}', 'brackets');

Usage

Unlike most terminal plugins, jq-console gives you complete low-level control over the execution; you have to call the appropriate methods to start input or output:

jqconsole.Input:

Asks user for input. If another input or prompt operation is currently underway, the new input operation is enqueued and will be called when the current operation and all previously enqueued operations finish. Takes one argument:

  • function input_callback: A function called with the user's input when the user presses Enter and the input operation is complete.

Example:

    // Echo the input.
    jqconsole.Input(function(input) {
      jqconsole.Write(input);
    });

jqconsole.Prompt

Asks user for input. If another input or prompt operation is currently underway the new prompt operation is enqueued and will be called when the current peration and all previously enqueued operations finish. Takes four arguments:

  • bool history_enabled: Whether this input should use history. If true, the user can select the input from history, and their input will also be added as a new history item.

  • function result_callback: A function called with the user's input when the user presses Enter and the prompt operation is complete.

  • function multiline_callback: If specified, this function is called when the user presses Enter to check whether the input should continue to the next line. The function must return one of the following values:

    • false: the input operation is completed.

    • 0: the input continues to the next line with the current indent.

    • N (int): the input continues to the next line, and the current indent is adjusted by N, e.g. -2 to unindent two levels.

  • bool async_multiline: Whether the multiline callback function should be treated as an asynchronous operation and be passed a continuation function that should be called with one of the return values mentioned above: false/0/N.

Example:

    jqconsole.Prompt(true, function(input) {
      // Alert the user with the command.
      alert(input);
    }, function (input) {
      // Continue if the last character is a backslash.
      return /\\$/.test(input);
    });

jqconsole.AbortPrompt

Aborts the current prompt operation and returns to output mode or the next queued input/prompt operation. Takes no arguments.

Example:

    jqconsole.Prompt(true, function(input) {
      alert(input);
    });
    // Give the user 2 seconds to enter the command.
    setTimeout(function() {
      jqconsole.AbortPrompt();
    }, 2000);

jqconsole.Write

Writes the given text to the console in a <span>, with an optional class. If a prompt is currently being shown, the text is inserted before it. Takes two arguments:

  • string text: The text to write.

  • string cls: The class to give the span containing the text. Optional.

  • bool escape: Whether the text to write should be html escaped. Optional, defaults to true.

Examples:

    jqconsole.Write(output, 'my-output-class')
    jqconsole.Write(err.message, 'my-error-class')

jqconsole.Append

Append the given node to the DOM. If a prompt is currently being shown, the text is inserted before it. Takes a single argument:

  • (string|Element) node: The DOM Element or html string to append to the console just before the prompt.

Example:

    // Add a div with the text 'hello' on a red background using jquery
    jqconsole.Append($('<div>hello</div>').css('background-color', 'red'));

    // We can also use document.createElement
    node = document.createElement("div");
    content = document.createTextNode("hello");
    node.appendChild(content);
    jqconsole.Append(node);

jqconsole.SetPromptText

Sets the text currently in the input prompt. Takes one parameter:

  • string text: The text to put in the prompt.

Examples:

    jqconsole.SetPromptText('ls')
    jqconsole.SetPromptText('print [i ** 2 for i in range(10)]')

jqconsole.SetPromptLabel

Replaces the main prompt label. Takes two parameters:

  • string main_label: String to replace the main prompt label.
  • string continuation_label: String to replace the continuation prompt label. Optional.

Examples:

    jqconsole.SetPromptLabel('$')
    jqconsole.SetPromptLabel(' $','..')

jqconsole.ClearPromptText

Clears all the text currently in the input prompt. Takes one parameter:

  • bool clear_label: If specified and true, also clears the main prompt label (e.g. ">>>").

Example:

    jqconsole.ClearPromptText()

jqconsole.GetPromptText

Returns the contents of the prompt. Takes one parameter:

  • bool full: If specified and true, also includes the prompt labels (e.g. ">>>").

Examples:

    var currentCommand = jqconsole.GetPromptText()
    var logEntry = jqconsole.GetPromptText(true)

jqconsole.Reset

Resets the console to its initial state, cancelling all current and pending operations. Takes no parameters.

Example:

    jqconsole.Reset()

jqconsole.SetKeyPressHandler

Sets a custom key press handler to be executed before the internal jqconsole handler. If it returns false then jqconsole will ignore the event. This gives you control over what events jqconsole can handle and for you to do your custom work.

  • function handler: An event handler function returning true or false.

Example:

      // Don't allow the character 'x' for no reason :P
      jqconsole.SetKeyPressHanlder(function(e) {
        if (String.fromCharCode(e.which) === 'x') {
          return false;
        }
      });

jqconsole.SetControlKeyHandler

Allows you to handle key events that are not characters (keydown events). You can return false to prevent the default. See demo for full example.

  • function handler: An event handler function returning true or false.

Example:

      // Show auto-complete on tab keys
      jqconsole.SetKeyPressHanlder(function(e) {
        if (e.which === 9) {
          $('.suggestions').show();
          return false;
        }
      });

jqconsole.GetColumn

Returns the 0-based number of the column on which the cursor currently is. Takes no parameters.

Example:

    // Show the current line and column in a status area.
    $('#status').text(jqconsole.GetLine() + ', ' + jqconsole.GetColumn())

jqconsole.GetLine

Returns the 0-based number of the line on which the cursor currently is. Takes no parameters.

Example:

    // Show the current line and column in a status area.
    $('#status').text(jqconsole.GetLine() + ', ' + jqconsole.GetColumn())

jqconsole.Focus

Forces the focus onto the console so events can be captured. Takes no parameters.

Example:

    // Redirect focus to the console whenever the user clicks anywhere.
    $(window).click(function() {
      jqconsole.Focus();
    })

jqconsole.GetIndentWidth

Returns the number of spaces inserted when indenting. Takes no parameters.

Example:

    jqconsole.SetIndentWidth(4);
    console.assert(jqconsole.GetIndentWidth() == 4);

jqconsole.UnRegisterMatching

Deletes a certain matching settings set by jqconsole.RegisterMatching. Takes two paramaters:

  • char open: The opening character of a "block".
  • char close: The closing character of a "block".

Example:

    jqconsole.UnRegisterMatching('{', '}');

jqconsole.Dump

Returns the text content of the console.

jqconsole.GetState

Returns the current state of the console. Could be one of the following:

  • Input: "input"
  • Output: "output"
  • Prompt: "prompt"

Example:

    jqconsole.GetState(); //output

jqconsole.MoveToStart

Moves the cursor to the start of the current line. Takes one parameter:

  • bool all_lines: If true moves the cursor to the beginning of the first line in the current prompt. Defaults to false.

Example:

    // Move to line start Ctrl+A.
    jqconsole.RegisterShortcut('A', function() {
      jqconsole.MoveToStart();
      handler();
    });

jqconsole.MoveToEnd

Moves the cursor to the end of the current line. Takes one parameter:

  • bool all_lines: If true moves the cursor to the end of the first line in the current prompt. Defaults to false.

Example:

    // Move to line end Ctrl+E.
    jqconsole.RegisterShortcut('E', function() {
      jqconsole.MoveToEnd();
      handler();
    });

jqconsole.Disable

Disables input and focus on the console.

jqconsole.Enable

Enables input and focus on the console.

jqconsole.IsDisabled

Returns true if the console is disabled.

jqconsole.GetHistory

Returns the contents of the history buffer.

jqconsole.SetHistory

Set the history buffer to the given array.

Takes one parameter:

  • array history: The history buffer to use.

Example:

    jqconsole.SetHistory(['a = 3', 'a + 3']);

jqconsole.ResetHistory

Resets the console history.

jqconsole.ResetMatchings

Resets the character matching configuration.

jqconsole.ResetShortcuts

Resets the shortcut configuration.

jqconsole.Clear

Clears the console's content excluding the current prompt

Default Key Config

The console responds to the followind keys and key combinations by default:

  • Delete: Delete the following character.
  • Ctrl+Delete: Delete the following word.
  • Backspace: Delete the preceding character.
  • Ctrl+Backspace: Delete the preceding word.
  • Ctrl+Left: Move one word to the left.
  • Ctrl+Right: Move one word to the right.
  • Home: Move to the beginning of the current line.
  • Ctrl+Home: Move to the beginnig of the first line.
  • End: Move to the end of the current line.
  • Ctrl+End: Move to the end of the last line.
  • Shift+Up, Ctrl+Up: Move cursor to the line above the current one.
  • Shift+Down, Ctrl+Down: Move cursor to the line below the current one.
  • Tab: Indent.
  • Shift+Tab: Unindent.
  • Up: Previous history item.
  • Down: Next history item.
  • Enter: Finish input/prompt operation. See Input() and Prompt() for details.
  • Shift+Enter: New line.
  • Page Up: Scroll console one page up.
  • Page Down: Scroll console one page down.

ANSI escape code SGR support

jq-console implements a large subset of the ANSI escape code graphics. Using the .Write method you could add style to the console using the following syntax:

ASCII 27 (decimal) or 0x1b (hex) [ SGR code m

Example:

jqconsole.Write('\033[31mRed Text');

Note that the third parameter escape must be true which defaults to it.

You'll need to include the ansi.css file for default effects or create your own using the css classes from the table below.

SGR

Reference.

Code Effect Class
0 Reset / Normal
1 Bold `jqconsole-ansi-bold`
2 Faint `jqconsole-ansi-lighter`
3 Italic `jqconsole-ansi-italic`
4 Line below text `jqconsole-ansi-underline`
5 Blink: 1s delay `jqconsole-ansi-blink`
6 Blink: 0.5s delay `jqconsole-ansi-blink-rapid`
8 Hide text `jqconsole-ansi-hidden`
9 Line through text `jqconsole-ansi-line-through`
10 Remove all fonts
11-19 Add custom font `jqconsole-ansi-fonts-{N}` where N is code - 10
20 Add Fraktur font (not implemented in ansi.css) `jqconsole-ansi-fraktur`
21 Remove Bold and Faint effects
22 Same as 21
23 Remove italic and fraktur effects
24 Remove underline effect
25 Remove blinking effect(s).
28 Reveal text
29 Remove line-through effect
30-37 Set foreground color to color from the color table below jqconsole-ansi-color-{COLOR} where {COLOR} is the color name
39 Restore default foreground color
40-47 Set background color to color from the color table below `jqconsole-ansi-background-color-{COLOR}` where {COLOR} is the color name
49 Restore default background color
51 Adds a frame around the text `jqconsole-ansi-framed`
53 Line above text jqconsole-ansi-overline
54 Remove frame effect
55 Remove over-line effect

Colors

Reference.

Code offset Color
0 Black
1 Red
2 Green
3 Yellow
4 Blue
5 Magenta
6 Cyan
7 White

CSS Classes

Several CSS classes are provided to help stylize the console:

  • jqconsole: The main console container.
  • jqconsole, jqconsole-blurred: The main console container, when not in focus.
  • jqconsole-cursor: The cursor.
  • jqconsole-header: The welcome message at the top of the console.
  • jqconsole-input: The prompt area during input. May have multiple lines.
  • jqconsole-old-input: Previously-entered inputs.
  • jqconsole-prompt: The prompt area during prompting. May have multiple lines.
  • jqconsole-old-prompt: Previously-entered prompts.
  • jqconsole-composition: The div encapsulating the composition of multi-byte characters.
  • jqconsole-prompt-text: the text entered in the current prompt

Of course, custom classes may be specified when using jqconsole.Write() for further customization.

Contributors

Max Shawabkeh Amjad Masad

License

MIT

jq-console's People

Contributors

amasad avatar arichiardi avatar arthuredelstein avatar bard avatar bonsaiben avatar chmp avatar coderaiser avatar eush77 avatar max99x avatar papac avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jq-console's Issues

license

Is it okay to use in my project , or a license is needed ? :)

Automatic completion?

I'm using this on a project that needs an in-browser javascript repl, and would like to add tab completion support.

After a quick search I didn't found any simple solution, so I will probably have to implement it from the scratch.

Could you give any hint/example of how this can be achieved?

Bug in History

It is unclear how this happens.
Sometimes when you hit enter on a command pulled from history, the next history access would be on the wrong index.

limit the number of lines?

Is it possible to limit the size of the buffer which will be filled after each write operation? I want to use jq-console for continuous show logging information and I am afraid to get problems with too many inserted strings. Can the oldest lines automatically be removed (e.g. if more lines than 1000)?

Thanks in advance

...Rolf

Bake in word-wrap

or add to documentation

  white-space: pre-wrap;
  word-wrap: break-word;

Problem with ANSI SGR colors

If I call the following

jqconsole.Write('\u001b[31mRED\u001b[32mGREEN\u001b[34mBLUE\u001b[31mRED');

I get the last word RED in blue color instead of red. Why can I switch colors only 3 times? Thanks in advance.

...Rolf

Echo example in angular.js?

Hi. Thanks for the great tool.

I'm trying to find the "Echo Example" from the readme done in Angular. I was hoping someone might be able to point one out, as I've been unable to find anything.

The Prompt function takes 4, not 3 arguments

The README.md says that the Prompt function "Takes three arguments", but it actually takes four:

JQConsole.prototype.Prompt = function(history_enabled, result_callback, multiline_callback, async_multiline)

Emit events.

Would be useful if the console emit events for stuff like:

  • Focused (started editing).
  • Blurred (stopped editing).
  • State changed.

Touch device support

Currently jqconsole does not pop up the keyboard when focused on touch devices. This needs to be fixed. As per our discussion, it seems the straightforward solution is to have the hidden input textarea covering the console with 0 opacity on touch devices. We shouldn't use that for non-touch browsers since this invisible textarea prevents mouse selection.

Non-US keyboard doesn't work on Windows Chrome/IE

Characters requiring AltGr (e.g. left square bracket = AltGr+8) on Finnish keyboard don't seem to work at all on IE11 or Chrome 36 running on Windows 7. Chrome 36 on Linux does work, and Firefox works both on Windows and Linux.

Characters composed of multiple keys don't work

It appears jqconsole doesn't deal correctly with characters that are composed of multiple keystrokes. E.g., it eats the AltGr button combinations that are typically used to insert unicode characters. This wouldn't be a problem, but on some keyboard layouts, important punctuation (e.g. square brackets) cannot be used without these key combinations.

Buffer/Defer output.

Implement debounce.Write method to optimize for high frequency outputs which can be DOM expensive.
Also would be nice to have a hard limit on the buffered characters which will enforce writing the buffered out.

Make jq-console minifier friendly.

Currently jq-console code is filled with redundant inline strings (e.g. span). Declaring them as variables would possibly have a huge effect on minified size.

Having multiple consoles on one page causes the page to jump around

Having multiple instances of the console in one page causes the page to jump around when the consoles get created. Because of this, when the document is loaded, the place where the last console was created is shown instead of the beginning of the document. Also, by creating a console and then clicking on the page causes the page to scroll to apparently random console.

How can I stop it from doing this?

Problem adjusting font-family

First: Thanks a lot for this great library!
Problem: In the #console {...} I have tried both of these:
font: 18px dejavu sans mono, menlo, monaco, monospace;
font-family: Menlo;
I get the right size, but not the font I want. Seems I just get my browser's default monospace.
I have tried Safari, Chrome, Firefox and Opera, on Mac.

Keyboard doesn't works in Google Chrome for Android

* Browser: Chrome 18.0.1025469
* SO: Android 4.1.2; Transformer Build/JZ054K

Steps to reproduce:

  1. Using the specs above, try to open android keyboard, touching the console;
  2. Close the keyboard, you can try to write some commands and close;
  3. Then, try to open the keyboard again.

What happens:

  • The keyboard open, but is not possible to write content to the console.

Introduce echo control

Currently, the library always echoes key strokes on the prompt.

I was able to prevent this using the following code, but it would be great if it was optional.

console.$prompt_left = $('<div></div>');

Shortcuts doesn't work on Opera.

Opera considers cntrl to be Meta, at least on mac. For future proofing allow shortcuts to be composed of cntrl or meta keys + char.

Add matching characters highlighting

Add a feature where users can choose to give classes of their choice to match characters i.e. { }
Should be able to add and delete matchings.

Example:
jqconsole.Match('(', ')', 'parans')

Add:
jqconsole.Match( (Character) open, (Character) close, (String) html_class)

Delete:
jqconsole.Match((Character) open, (Character) close)

Instead of giving extra API for deleting a matching the user should be able to call the same method but omit out the html_class argument.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.