Giter Club home page Giter Club logo

clui's Introduction

clui

This is a Node.js toolkit for quickly building nice looking command line interfaces which can respond to changing terminal sizes. It also includes the following easy to use components:

  • Gauges
  • Progress Bars
  • Sparklines
  • Spinners

Updates

Changelog

October 8, 2014 - Adding Line.contents() for fetching the contents of a line as a string.

June 2, 2014 - Fixed a crash caused by inability to locate the required trim helper in the latest version of cli-color. (And locked down the version of the cli-color dependency to stop this from ever happening again.) Also removed lodash as a dependency in favor of vanilla JS, to keep installs faster and smaller than ever.

LineBuffer(options)

Creates an object for buffering a group of text lines and then outputting them. When printing lines using LineBuffer it will crop off extra width and height so that the lines will fit into a specific space.

Options

The following options can be passed in on creation of the LineBuffer

  • x - The X location of where to draw the lines in this buffer.
  • y - The Y location of where the draw the lines.
  • width - How wide the buffer is in columns. Any lines longer than this will be cropped. You can specify either an integer value or 'console' in order to let the width of the console determine the width of the LineBuffer.
  • height - How high the buffer is in rows. You can either pass in an integer value or 'console' to let the height on the console determine the height of the LineBuffer.
  • scroll - Where the user is scrolled to in the buffer

Functions

  • height() - Return the height of the LineBuffer, in case you specified it as 'console'
  • width() - Return the width of the LineBuffer, in case you specified it as 'console'
  • addLine(Line) - Put a Line object into the LineBuffer.
  • fill() - If you don't have enough lines in the buffer this will fill the rest of the lines with empty space.
  • output() - Draw the LineBuffer to screen.

Example

var CLI = require('clui'),
    clc = require('cli-color');

var Line          = CLI.Line,
    LineBuffer    = CLI.LineBuffer;

var outputBuffer = new LineBuffer({
  x: 0,
  y: 0,
  width: 'console',
  height: 'console'
});

var message = new Line(outputBuffer)
  .column('Title Placehole', 20, [clc.green])
  .fill()
  .store();

var blankLine = new Line(outputBuffer)
  .fill()
  .store();

var header = new Line(outputBuffer)
  .column('Suscipit', 20, [clc.cyan])
  .column('Voluptatem', 20, [clc.cyan])
  .column('Nesciunt', 20, [clc.cyan])
  .column('Laudantium', 11, [clc.cyan])
  .fill()
  .store();

var line;
for(var l = 0; l < 20; l++)
{
  line = new Line(outputBuffer)
    .column((Math.random()*100).toFixed(3), 20)
    .column((Math.random()*100).toFixed(3), 20)
    .column((Math.random()*100).toFixed(3), 20)
    .column((Math.random()*100).toFixed(3), 11)
    .fill()
    .store();
}

outputBuffer.output();

Line(outputBuffer)

This chainable object can be used to generate a line of text with columns, padding, and fill. The parameter outputBuffer can be provided to save the line of text into a LineBuffer object for future outputting, or you can use LineBuffer.addLine() to add a Line object into a LineBuffer.

Alternatively if you do not wish to make use of a LineBuffer you can just use Line.output() to output the Line immediately rather than buffering it.

Chainable Functions

  • padding(width) - Output width characters of blank space.
  • column(text, width, styles) - Output text within a column of the specified width. If the text is longer than width it will be truncated, otherwise extra padding will be added until it is width characters long. The styles variable is a list of cli-color styles to apply to this column.
  • fill() - At the end of a line fill the rest of the columns to the right edge of the terminal with whitespace to erase any content there.
  • output() - Print the generated line of text to the console.
  • contents() - Return the contents of this line as a string.

Example

var clui = require('clui'),
    clc = require('cli-color'),
    Line = clui.Line;

var headers = new Line()
  .padding(2)
  .column('Column One', 20, [clc.cyan])
  .column('Column Two', 20, [clc.cyan])
  .column('Column Three', 20, [clc.cyan])
  .column('Column Four', 20, [clc.cyan])
  .fill()
  .output();

var line = new Line()
  .padding(2)
  .column((Math.random()*100).toFixed(3), 20)
  .column((Math.random()*100).toFixed(3), 20)
  .column((Math.random()*100).toFixed(3), 20)
  .column((Math.random()*100).toFixed(3), 20)
  .fill()
  .output();

Gauge(value, maxValue, gaugeWidth, dangerZone, suffix)

Picture of two gauges

Draw a basic horizontal gauge to the screen.

Parameters

  • value - The current value of the metric being displayed by this gauge
  • maxValue - The highest possible value of the metric being displayed
  • gaugeWidth - How many columns wide to draw the gauge
  • dangerZone - The point after which the value will be drawn in red because it is too high
  • suffix - A value to output after the gauge itself.

Example

var os   = require('os'),
    clui = require('clui');

var Gauge = clui.Gauge;

var total = os.totalmem();
var free = os.freemem();
var used = total - free;
var human = Math.ceil(used / 1000000) + ' MB';

console.log(Gauge(used, total, 20, total * 0.8, human));

Sparkline(values, suffix)

Picture of two sparklines

A simple command line sparkline that draws a series of values, and highlights the peak for the period. It also automatically outputs the current value and the peak value at the end of the sparkline.

Parameters

  • values - An array of values to go into the sparkline
  • suffix - A suffix to use when drawing the current and max values at the end of sparkline

Example

var Sparkline = require('clui').Sparkline;
var reqsPerSec = [10,12,3,7,12,9,23,10,9,19,16,18,12,12];

console.log(Sparkline(reqsPerSec, 'reqs/sec'));

Progress(length)

Picture of a few progress bars

Parameters

  • length - The desired length of the progress bar in characters.

Methods

  • update(currentValue, maxValue) - Returns the progress bar min/max content to write to stdout. Allows for dynamic max values.
  • update(percent) - Returns the progress bar content as a percentage to write to stdout. 0.0 > value < 1.0.

Example

var clui = require('clui');

var Progress = clui.Progress;

var thisProgressBar = new Progress(20);
console.log(thisProgressBar.update(10, 30));

// or

var thisPercentBar = new Progress(20);
console.log(thisPercentBar.update(0.4));

Spinner(statusText)

Picture of a spinner

Parameters

  • statusText - The default status text to display while the spinner is spinning.
  • style - Array of graphical characters used to draw the spinner. By default, on Windows: ['|', '/', '-', ''], on other platforms: ['◜','◠','◝','◞','◡','◟']

Methods

  • start() - Show the spinner on the screen.
  • message(statusMessage) - Update the status message that follows the spinner.
  • stop() - Erase the spinner from the screen.

Note: The spinner is slightly different from other Clui controls in that it outputs directly to the screen, instead of just returning a string that you output yourself.

Example

var CLI = require('clui'),
    Spinner = CLI.Spinner;

var countdown = new Spinner('Exiting in 10 seconds...  ', ['⣾','⣽','⣻','⢿','⡿','⣟','⣯','⣷']);

countdown.start();

var number = 10;
setInterval(function () {
  number--;
  countdown.message('Exiting in ' + number + ' seconds...  ');
  if (number === 0) {
    process.stdout.write('\n');
    process.exit(0);
  }
}, 1000);

License

Copyright (C) 2014 Nathan Peck (https://github.com/nathanpeck)

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.

clui's People

Contributors

artokun avatar bouiboui avatar fay-jai avatar foxyblocks avatar nathanpeck avatar sevastos avatar tte avatar ysangkok 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

clui's Issues

Recommended: Migrate to TypeScript

Excess new lines when using Line.output

Line#output calls process.stdout.write with an added new line. This causes, at least on Windows, there to be two new lines after every line because process.stdout.write outputs with a new line already. Could this excess new line either be removed or be controlled by an option for if it's there or not?

For instance, the constructor for Line could be:

// Chainable wrapper for line content
Line: function (defaultBuffer, opts) {
  var lineContent = "";
  var self = this;
  if (defaultBuffer instanceof helpers.LineBuffer) {
      self.defaultBuffer = defaultBuffer;
  }

  // Allow the user to send in options as the first argument if they aren't
  // supplying a default buffer.
  self.options = self.defaultBuffer ?
      opts:
      defaultBuffer;

  self.options = self.options || {};

  // Default new line option to true to maintain old behavior.
  if (!self.options.hasOwnProperty('newLine')) {
      self.options.newLine = true;
  }

And then the output could look like:

// Output a line directly to the screen.
this.output = function () {
  process.stdout.write(lineContent + (self.options.newLine ? '\n' : ''));
  return self;
};

I'm not sure which way you want to go with this, but I would love the ability to suppress that newline. I'm happy to created a pull request for it if you want, once you specify which way you want to go with things.

How do I print items of two arrays, side by side?

What I tried, with no success:

var line = new Line();

let foo = arr1.toString("\n")
let bar = arr2.toString("\n")

line.padding(2)
      .column(foo, 40)
      .column(bar, 40)
      .fill();

line.output();

Printed content is either trimmed or mixed.

How to update progress bar in place?

There is an existing example that updates progress bar in place: https://github.com/nathanpeck/clui/blob/master/examples/progress.js (60 lines in total)

There is much simpler example directly in the readme: https://github.com/nathanpeck/clui/blob/master/README.md (4 lines only)

var clui = require('clui');

var Progress = clui.Progress;

var thisProgressBar = new Progress(20);
console.log(thisProgressBar.update(10, 30));

So I've added setInterval so that it updates the progress. I've also added line to clear the console and new console.log with each interval:

var clui = require('clui');

var Progress = clui.Progress;

var value = 50;

var thisProgressBar = new Progress(20);

console.log(thisProgressBar.update(value, 100));

var intervalId = setInterval(function() {
	value++;
	// console.log("Updated value: " + value);

	process.stdout.write('\033c'); // clearing the console
	console.log(thisProgressBar.update(value, 100));

	if (value === 100) {
		clearInterval(intervalId);
	}
}, 500)

In the example with countdown spinner I don't have clear the console and do console.log, see example: https://github.com/nathanpeck/clui/blob/master/README.md#spinnerstatustext

Ideally I would like to do just thisProgressBar.update(value, 100) and the progress bar should be updated in places easily...

(without clearing the existing console - I may have so many other progress bars and elements running)

Right alignment

Being able to align to the right would be really handy, especially for numeric values.

I noticed that Line.column won't accept numbers either, maybe it could look at the type of the data passed in and left align for text, and right align for numbers?

Cursor and Flicker on clear

When I have a progress bar that update, I do:

clear();
// Redraw progress bar with new values here

My question is:

  1. How to hide the cursor (toggle cursor on or off)
  2. The clear/redraw is causing a flicker effect on the screen. How can this be prevented, like:

Rather use offset x/y positions to update characters, than to do a clear / redraw?

Spinner with manual ticking

I wan't to tick manually the spinner.

For sample

var countdown  = new CLI.Spinner('Running...  ', ['⣾','⣽','⣻','⢿','⡿','⣟','⣯','⣷']);
countdown.start();

let's run automatic. But i want to "move" the spinner programatically like

var countdown  = new CLI.Spinner('Running...  ', ['⣾','⣽','⣻','⢿','⡿','⣟','⣯','⣷']);

setInterval(function() {
    countdown.tick();
}, 1000); // each second, the spinner moves...

Is this module deprecated/unmaintained?

No response for over a year in the opened issues, documentation errors and other commits in a while. Is this module being maintained?

If not, you should notify users about it in readme and in the NPM, I see a lot of active downloads for this module in its profile and a lot of developers may might experience troubles in future updates in NodeJS itself.

screen shot 2017-06-12 at 16 40 24

Cannot find module cli-color/trim

After install, despite the module cli-color is properly installed via npm, I get the error message:
Cannot find module 'cli-color/trim'.
In fact the 'cli-color' module doesn't have such a library.

Spinner didn't clear previous message if it is too long

Hi, thanks for your great clui module, i like it a lot. 👍

Anyway, here's one issue i found when i tried the spinner.

If you update the message using spinner.message('some very very long message');
then spinner.message('short message'), you will see that your output will get tangled up. Because the short message is printed over the old message, i think it should clear the line before spitting out the new message.

**BTW, your documentationi says spinner.update(), but there's no such method, i see the code then I notice it's spinner.message().

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.