diff --git a/deps/console-menu/LICENSE.txt b/deps/console-menu/LICENSE.txt new file mode 100644 index 0000000..562866f --- /dev/null +++ b/deps/console-menu/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2016 Jason Ginchereau + +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. diff --git a/deps/console-menu/README.md b/deps/console-menu/README.md new file mode 100644 index 0000000..818fc5a --- /dev/null +++ b/deps/console-menu/README.md @@ -0,0 +1,54 @@ +# console-menu +Displays a menu of items in the console and asynchronously waits for the user to select an item. Each item title is prefixed by a hotkey. An item may be selected by typing a hotkey or by using Down/Up arrows followed by Enter. +``` +.--------------. +| Example menu | ++--------------+ +| [a] Item A | +| b) Item B | +| c) Item C | +| d) Item D | +| e) Item E | +'--\/----------' +``` +The menu may be scrollable (hinted by `/\` and `\/` indicators). PageUp, PageDown, Home, and End keys are also supported. + +## Usage +The `menu` function takes two parameters: an `items` array and an `options` object. + +Each item must be an object with the following properties: + * `separator` (boolean): If true, this is a separator item that inserts a blank line into the menu. (All other properties are ignored on separator items.) + * `title` (string): Item title text. + * `hotkey` (character): Unique item hotkey; must be a single letter, number, or other character. If omitted, the item is only selectable via arrow keys + Enter. + * `selected` (boolean) True if this item should initially selected. If unspecified then the first item is initially selected. + +Items may have additional user-defined properties, which will be included in the returned result. + +The following options are supported: + * `header` (string): Optional header text for the menu. + * `border` (boolean): True to draw a border around the menu. False for a simpler-looking menu. + * `pageSize` (integer): Max number of items to show at a time; additional items cause the menu to be scrollable. Omitting this value (or specifying 0) disables scrolling. + * `helpMessage` (string): Message text to show under the menu. + +The return value is a `Promise` that resolves to the chosen item object, or to `null` if the menu was cancelled by pressing Esc or Ctrl-C. + +## Example +```JavaScript +var menu = require('console-menu'); +menu([ + { hotkey: '1', title: 'One' }, + { hotkey: '2', title: 'Two', selected: true }, + { hotkey: '3', title: 'Three' }, + { separator: true }, + { hotkey: '?', title: 'Help' }, +], { + header: 'Example menu', + border: true, +}).then(item => { + if (item) { + console.log('You chose: ' + JSON.stringify(item)); + } else { + console.log('You cancelled the menu.'); + } +}); +``` diff --git a/deps/console-menu/console-menu.js b/deps/console-menu/console-menu.js new file mode 100644 index 0000000..0361d8c --- /dev/null +++ b/deps/console-menu/console-menu.js @@ -0,0 +1,191 @@ +const os = require('os'); +const readline = require('readline'); +const keypress = require('keypress'); + +const defaultHelpMessage = + 'Type a hotkey or use Down/Up arrows then Enter to choose an item.'; + +/** + * Displays a menu of items in the console and asynchronously waits for the user to select an item. + * + * @param {any} items Array of menu items, where each item is an object that includes a title + * property and optional hotkey property. (Items may include additional user-defined properties.) + * @param {any} options Dictionary of options for the menu: + * - header {string}: Header text for the menu. + * - border {boolean}: True to draw a border around the menu. + * - pageSize {integer}: Max number of items to show at a time. Additional items cause the menu + * to be scrollable. + * - helpMessage {string}: Message text to show under the menu. + * @returns A promise that resolves to the chosen item, or to null if the menu was cancelled. + */ +function menu(items, options) { + if (!items || !Array.isArray(items) || items.length < 1) { + throw new TypeError('A nonempty items array is required.'); + } + options = options || {}; + + var count = items.length; + var selectedIndex = items.findIndex(item => item.selected); + if (selectedIndex < 0) { + selectedIndex = 0; + while (selectedIndex < count && items[selectedIndex].separator) selectedIndex++; + } + + var scrollOffset = 0; + printMenu(items, options, selectedIndex, scrollOffset); + + return new Promise((resolve, reject) => { + process.stdin.setRawMode(true); + process.stdin.resume(); + keypress(process.stdin); + + var handleMenuKeypress = (ch, key) => { + var selection = null; + if (isEnter(key)) { + selection = items[selectedIndex]; + } else if (ch) { + selection = items.find(item => item.hotkey && item.hotkey === ch) || + items.find(item => item.hotkey && + item.hotkey.toLowerCase() === ch.toLowerCase()); + } + + var newIndex = null; + if (selection || isCancelCommand(key)) { + process.stdin.removeListener('keypress', handleMenuKeypress); + process.stdin.setRawMode(false); + resetCursor(options, selectedIndex, scrollOffset); + readline.clearScreenDown(process.stdout); + process.stdin.pause(); + resolve(selection); + } else if (isUpCommand(key) && selectedIndex > 0) { + newIndex = selectedIndex - 1; + while (newIndex >= 0 && items[newIndex].separator) newIndex--; + } else if (isDownCommand(key) && selectedIndex < count - 1) { + newIndex = selectedIndex + 1; + while (newIndex < count && items[newIndex].separator) newIndex++; + } else if (isPageUpCommand(key) && selectedIndex > 0) { + newIndex = (options.pageSize ? Math.max(0, selectedIndex - options.pageSize) : 0); + while (newIndex < count && items[newIndex].separator) newIndex++; + } else if (isPageDownCommand(key) && selectedIndex < count - 1) { + newIndex = (options.pageSize + ? Math.min(count - 1, selectedIndex + options.pageSize) : count - 1); + while (newIndex >= 0 && items[newIndex].separator) newIndex--; + } else if (isGoToFirstCommand(key) && selectedIndex > 0) { + newIndex = 0; + while (newIndex < count && items[newIndex].separator) newIndex++; + } else if (isGoToLastCommand(key) && selectedIndex < count - 1) { + newIndex = count - 1; + while (newIndex >= 0 && items[newIndex].separator) newIndex--; + } + + if (newIndex !== null && newIndex >= 0 && newIndex < count) { + resetCursor(options, selectedIndex, scrollOffset); + + selectedIndex = newIndex; + + // Adjust the scroll offset when the selection moves off the page. + if (selectedIndex < scrollOffset) { + scrollOffset = (isPageUpCommand(key) + ? Math.max(0, scrollOffset - options.pageSize) : selectedIndex); + } else if (options.pageSize && selectedIndex >= scrollOffset + options.pageSize) { + scrollOffset = (isPageDownCommand(key) + ? Math.min(count - options.pageSize, scrollOffset + options.pageSize) + : selectedIndex - options.pageSize + 1); + } + + printMenu(items, options, selectedIndex, scrollOffset); + } + }; + + process.stdin.addListener('keypress', handleMenuKeypress); + }); +} + +function isEnter(key) { return key && (key.name === 'enter' || key.name === 'return'); } +function isUpCommand(key) { return key && key.name === 'up'; } +function isDownCommand(key) { return key && key.name === 'down'; } +function isPageUpCommand(key) { return key && key.name === 'pageup'; } +function isPageDownCommand(key) { return key && key.name === 'pagedown'; } +function isGoToFirstCommand(key) { return key && key.name === 'home'; } +function isGoToLastCommand(key) { return key && key.name === 'end'; } +function isCancelCommand(key) { + return key && ((key.ctrl && key.name == 'c') || key.name === 'escape'); +} + +function resetCursor(options, selectedIndex, scrollOffset) { + readline.moveCursor(process.stdout, -3, + - (options.header ? 1 : 0) + - (options.border ? (options.header ? 2 : 1) : 0) + - selectedIndex + scrollOffset); +} + +function printMenu(items, options, selectedIndex, scrollOffset) { + var repeat = (s, n) => { + return Array(n + 1).join(s); + }; + + var width = 0; + for (var i = 0; i < items.length; i++) { + if (items[i].title && 4 + items[i].title.length > width) { + width = 4 + items[i].title.length; + } + } + + var prefix = (options.border ? '|' : ''); + var suffix = (options.border ? ' |' : ''); + + if (options.header && options.header.length > width) { + width = options.header.length; + } + + if (options.border) { + if (!options.header && options.pageSize && scrollOffset > 0) { + process.stdout.write('.--/\\' + repeat('-', width - 2) + '.' + os.EOL); + } else { + process.stdout.write('.' + repeat('-', width + 2) + '.' + os.EOL); + } + } + + if (options.header) { + process.stdout.write(prefix + (options.border ? ' ' : '') + options.header + + repeat(' ', width - options.header.length) + suffix + os.EOL); + if (options.border) { + if (options.pageSize && scrollOffset > 0) { + process.stdout.write('+--/\\' + repeat('-', width - 2) + '+' + os.EOL); + } else { + process.stdout.write('+' + repeat('-', width + 2) + '+' + os.EOL); + } + } + } + + var scrollEnd = options.pageSize + ? Math.min(items.length, scrollOffset + options.pageSize) + : items.length; + for (var i = scrollOffset; i < scrollEnd; i++) { + if (items[i].separator) { + process.stdout.write(prefix + ' ' + repeat(' ', width) + suffix + os.EOL); + } else { + var hotkey = items[i].hotkey || '*'; + var title = items[i].title || ''; + var label = (i === selectedIndex + ? '[' + hotkey + ']' : ' ' + hotkey + ')'); + process.stdout.write(prefix + ' ' + label + ' ' + title + + repeat(' ', width - title.length - 4) + suffix + os.EOL); + } + } + + if (options.border) { + if (options.pageSize && scrollEnd < items.length) { + process.stdout.write('\'--\\/' + repeat('-', width - 2) + '\'' + os.EOL); + } else { + process.stdout.write('\'' + repeat('-', width + 2) + '\'' + os.EOL); + } + } + + process.stdout.write(options.helpMessage || defaultHelpMessage); + readline.moveCursor(process.stdout, + -(options.helpMessage || defaultHelpMessage).length + prefix.length + 2, + -(options.border ? 1 : 0) - (scrollEnd - scrollOffset) + selectedIndex - scrollOffset); +} + +module.exports = menu; diff --git a/deps/console-menu/node_modules/keypress/README.md b/deps/console-menu/node_modules/keypress/README.md new file mode 100644 index 0000000..a768e8f --- /dev/null +++ b/deps/console-menu/node_modules/keypress/README.md @@ -0,0 +1,101 @@ +keypress +======== +### Make any Node ReadableStream emit "keypress" events + + +Previous to Node `v0.8.x`, there was an undocumented `"keypress"` event that +`process.stdin` would emit when it was a TTY. Some people discovered this hidden +gem, and started using it in their own code. + +Now in Node `v0.8.x`, this `"keypress"` event does not get emitted by default, +but rather only when it is being used in conjuction with the `readline` (or by +extension, the `repl`) module. + +This module is the exact logic from the node `v0.8.x` releases ripped out into its +own module. + +__Bonus:__ Now with mouse support! + +Installation +------------ + +Install with `npm`: + +``` bash +$ npm install keypress +``` + +Or add it to the `"dependencies"` section of your _package.json_ file. + + +Example +------- + +#### Listening for "keypress" events + +``` js +var keypress = require('keypress'); + +// make `process.stdin` begin emitting "keypress" events +keypress(process.stdin); + +// listen for the "keypress" event +process.stdin.on('keypress', function (ch, key) { + console.log('got "keypress"', key); + if (key && key.ctrl && key.name == 'c') { + process.stdin.pause(); + } +}); + +process.stdin.setRawMode(true); +process.stdin.resume(); +``` + +#### Listening for "mousepress" events + +``` js +var keypress = require('keypress'); + +// make `process.stdin` begin emitting "mousepress" (and "keypress") events +keypress(process.stdin); + +// you must enable the mouse events before they will begin firing +keypress.enableMouse(process.stdout); + +process.stdin.on('mousepress', function (info) { + console.log('got "mousepress" event at %d x %d', info.x, info.y); +}); + +process.on('exit', function () { + // disable mouse on exit, so that the state + // is back to normal for the terminal + keypress.disableMouse(process.stdout); +}); +``` + + +License +------- + +(The MIT License) + +Copyright (c) 2012 Nathan Rajlich <nathan@tootallnate.net> + +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. diff --git a/deps/console-menu/node_modules/keypress/index.js b/deps/console-menu/node_modules/keypress/index.js new file mode 100644 index 0000000..5539dd6 --- /dev/null +++ b/deps/console-menu/node_modules/keypress/index.js @@ -0,0 +1,408 @@ + +/** + * Module dependencies. + */ + +var EventEmitter = require('events').EventEmitter; + +/** + * Module exports. + */ + +var exports = module.exports = keypress; + +/** + * This module offers the internal "keypress" functionality from node-core's + * `readline` module, for your own programs and modules to use. + * + * The `keypress` function accepts a readable Stream instance and makes it + * emit "keypress" events. + * + * Usage: + * + * ``` js + * require('keypress')(process.stdin); + * + * process.stdin.on('keypress', function (ch, key) { + * console.log(ch, key); + * if (key.ctrl && key.name == 'c') { + * process.stdin.pause(); + * } + * }); + * proces.stdin.resume(); + * ``` + * + * @param {Stream} stream + * @api public + */ + +function keypress(stream) { + if (isEmittingKeypress(stream)) return; + + var StringDecoder = require('string_decoder').StringDecoder; // lazy load + stream._keypressDecoder = new StringDecoder('utf8'); + + function onData(b) { + if (listenerCount(stream, 'keypress') > 0) { + var r = stream._keypressDecoder.write(b); + if (r) emitKey(stream, r); + } else { + // Nobody's watching anyway + stream.removeListener('data', onData); + stream.on('newListener', onNewListener); + } + } + + function onNewListener(event) { + if (event == 'keypress') { + stream.on('data', onData); + stream.removeListener('newListener', onNewListener); + } + } + + if (listenerCount(stream, 'keypress') > 0) { + stream.on('data', onData); + } else { + stream.on('newListener', onNewListener); + } +} + +/** + * Returns `true` if the stream is already emitting "keypress" events. + * `false` otherwise. + * + * @param {Stream} stream readable stream + * @return {Boolean} `true` if the stream is emitting "keypress" events + * @api private + */ + +function isEmittingKeypress(stream) { + var rtn = !!stream._keypressDecoder; + if (!rtn) { + // XXX: for older versions of node (v0.6.x, v0.8.x) we want to remove the + // existing "data" and "newListener" keypress events since they won't include + // this `keypress` module extensions (like "mousepress" events). + stream.listeners('data').slice(0).forEach(function(l) { + if (l.name == 'onData' && /emitKey/.test(l.toString())) { + stream.removeListener('data', l); + } + }); + stream.listeners('newListener').slice(0).forEach(function(l) { + if (l.name == 'onNewListener' && /keypress/.test(l.toString())) { + stream.removeListener('newListener', l); + } + }); + } + return rtn; +} + +/** + * Enables "mousepress" events on the *input* stream. Note that `stream` must be + * an *output* stream (i.e. a Writable Stream instance), usually `process.stdout`. + * + * @param {Stream} stream writable stream instance + * @api public + */ + +exports.enableMouse = function (stream) { + stream.write('\x1b[?1000h'); +}; + +/** + * Disables "mousepress" events from being sent to the *input* stream. + * Note that `stream` must be an *output* stream (i.e. a Writable Stream instance), + * usually `process.stdout`. + * + * @param {Stream} stream writable stream instance + * @api public + */ + +exports.disableMouse = function (stream) { + stream.write('\x1b[?1000l'); +}; + +/** + * `EventEmitter.listenerCount()` polyfill, for backwards compat. + * + * @param {Emitter} emitter event emitter instance + * @param {String} event event name + * @return {Number} number of listeners for `event` + * @api public + */ + +var listenerCount = EventEmitter.listenerCount; +if (!listenerCount) { + listenerCount = function(emitter, event) { + return emitter.listeners(event).length; + }; +} + + +/////////////////////////////////////////////////////////////////////// +// Below this function is code from node-core's `readline.js` module // +/////////////////////////////////////////////////////////////////////// + + +/* + Some patterns seen in terminal key escape codes, derived from combos seen + at http://www.midnight-commander.org/browser/lib/tty/key.c + + ESC letter + ESC [ letter + ESC [ modifier letter + ESC [ 1 ; modifier letter + ESC [ num char + ESC [ num ; modifier char + ESC O letter + ESC O modifier letter + ESC O 1 ; modifier letter + ESC N letter + ESC [ [ num ; modifier char + ESC [ [ 1 ; modifier letter + ESC ESC [ num char + ESC ESC O letter + + - char is usually ~ but $ and ^ also happen with rxvt + - modifier is 1 + + (shift * 1) + + (left_alt * 2) + + (ctrl * 4) + + (right_alt * 8) + - two leading ESCs apparently mean the same as one leading ESC +*/ + +// Regexes used for ansi escape code splitting +var metaKeyCodeRe = /^(?:\x1b)([a-zA-Z0-9])$/; +var functionKeyCodeRe = + /^(?:\x1b+)(O|N|\[|\[\[)(?:(\d+)(?:;(\d+))?([~^$])|(?:1;)?(\d+)?([a-zA-Z]))/; + +function emitKey(stream, s) { + var ch, + key = { + name: undefined, + ctrl: false, + meta: false, + shift: false + }, + parts; + + if (Buffer.isBuffer(s)) { + if (s[0] > 127 && s[1] === undefined) { + s[0] -= 128; + s = '\x1b' + s.toString(stream.encoding || 'utf-8'); + } else { + s = s.toString(stream.encoding || 'utf-8'); + } + } + + key.sequence = s; + + if (s === '\r') { + // carriage return + key.name = 'return'; + + } else if (s === '\n') { + // enter, should have been called linefeed + key.name = 'enter'; + + } else if (s === '\t') { + // tab + key.name = 'tab'; + + } else if (s === '\b' || s === '\x7f' || + s === '\x1b\x7f' || s === '\x1b\b') { + // backspace or ctrl+h + key.name = 'backspace'; + key.meta = (s.charAt(0) === '\x1b'); + + } else if (s === '\x1b' || s === '\x1b\x1b') { + // escape key + key.name = 'escape'; + key.meta = (s.length === 2); + + } else if (s === ' ' || s === '\x1b ') { + key.name = 'space'; + key.meta = (s.length === 2); + + } else if (s <= '\x1a') { + // ctrl+letter + key.name = String.fromCharCode(s.charCodeAt(0) + 'a'.charCodeAt(0) - 1); + key.ctrl = true; + + } else if (s.length === 1 && s >= 'a' && s <= 'z') { + // lowercase letter + key.name = s; + + } else if (s.length === 1 && s >= 'A' && s <= 'Z') { + // shift+letter + key.name = s.toLowerCase(); + key.shift = true; + + } else if (parts = metaKeyCodeRe.exec(s)) { + // meta+character key + key.name = parts[1].toLowerCase(); + key.meta = true; + key.shift = /^[A-Z]$/.test(parts[1]); + + } else if (parts = functionKeyCodeRe.exec(s)) { + // ansi escape sequence + + // reassemble the key code leaving out leading \x1b's, + // the modifier key bitflag and any meaningless "1;" sequence + var code = (parts[1] || '') + (parts[2] || '') + + (parts[4] || '') + (parts[6] || ''), + modifier = (parts[3] || parts[5] || 1) - 1; + + // Parse the key modifier + key.ctrl = !!(modifier & 4); + key.meta = !!(modifier & 10); + key.shift = !!(modifier & 1); + key.code = code; + + // Parse the key itself + switch (code) { + /* xterm/gnome ESC O letter */ + case 'OP': key.name = 'f1'; break; + case 'OQ': key.name = 'f2'; break; + case 'OR': key.name = 'f3'; break; + case 'OS': key.name = 'f4'; break; + + /* xterm/rxvt ESC [ number ~ */ + case '[11~': key.name = 'f1'; break; + case '[12~': key.name = 'f2'; break; + case '[13~': key.name = 'f3'; break; + case '[14~': key.name = 'f4'; break; + + /* from Cygwin and used in libuv */ + case '[[A': key.name = 'f1'; break; + case '[[B': key.name = 'f2'; break; + case '[[C': key.name = 'f3'; break; + case '[[D': key.name = 'f4'; break; + case '[[E': key.name = 'f5'; break; + + /* common */ + case '[15~': key.name = 'f5'; break; + case '[17~': key.name = 'f6'; break; + case '[18~': key.name = 'f7'; break; + case '[19~': key.name = 'f8'; break; + case '[20~': key.name = 'f9'; break; + case '[21~': key.name = 'f10'; break; + case '[23~': key.name = 'f11'; break; + case '[24~': key.name = 'f12'; break; + + /* xterm ESC [ letter */ + case '[A': key.name = 'up'; break; + case '[B': key.name = 'down'; break; + case '[C': key.name = 'right'; break; + case '[D': key.name = 'left'; break; + case '[E': key.name = 'clear'; break; + case '[F': key.name = 'end'; break; + case '[H': key.name = 'home'; break; + + /* xterm/gnome ESC O letter */ + case 'OA': key.name = 'up'; break; + case 'OB': key.name = 'down'; break; + case 'OC': key.name = 'right'; break; + case 'OD': key.name = 'left'; break; + case 'OE': key.name = 'clear'; break; + case 'OF': key.name = 'end'; break; + case 'OH': key.name = 'home'; break; + + /* xterm/rxvt ESC [ number ~ */ + case '[1~': key.name = 'home'; break; + case '[2~': key.name = 'insert'; break; + case '[3~': key.name = 'delete'; break; + case '[4~': key.name = 'end'; break; + case '[5~': key.name = 'pageup'; break; + case '[6~': key.name = 'pagedown'; break; + + /* putty */ + case '[[5~': key.name = 'pageup'; break; + case '[[6~': key.name = 'pagedown'; break; + + /* rxvt */ + case '[7~': key.name = 'home'; break; + case '[8~': key.name = 'end'; break; + + /* rxvt keys with modifiers */ + case '[a': key.name = 'up'; key.shift = true; break; + case '[b': key.name = 'down'; key.shift = true; break; + case '[c': key.name = 'right'; key.shift = true; break; + case '[d': key.name = 'left'; key.shift = true; break; + case '[e': key.name = 'clear'; key.shift = true; break; + + case '[2$': key.name = 'insert'; key.shift = true; break; + case '[3$': key.name = 'delete'; key.shift = true; break; + case '[5$': key.name = 'pageup'; key.shift = true; break; + case '[6$': key.name = 'pagedown'; key.shift = true; break; + case '[7$': key.name = 'home'; key.shift = true; break; + case '[8$': key.name = 'end'; key.shift = true; break; + + case 'Oa': key.name = 'up'; key.ctrl = true; break; + case 'Ob': key.name = 'down'; key.ctrl = true; break; + case 'Oc': key.name = 'right'; key.ctrl = true; break; + case 'Od': key.name = 'left'; key.ctrl = true; break; + case 'Oe': key.name = 'clear'; key.ctrl = true; break; + + case '[2^': key.name = 'insert'; key.ctrl = true; break; + case '[3^': key.name = 'delete'; key.ctrl = true; break; + case '[5^': key.name = 'pageup'; key.ctrl = true; break; + case '[6^': key.name = 'pagedown'; key.ctrl = true; break; + case '[7^': key.name = 'home'; key.ctrl = true; break; + case '[8^': key.name = 'end'; key.ctrl = true; break; + + /* misc. */ + case '[Z': key.name = 'tab'; key.shift = true; break; + default: key.name = 'undefined'; break; + + } + } else if (s.length > 1 && s[0] !== '\x1b') { + // Got a longer-than-one string of characters. + // Probably a paste, since it wasn't a control sequence. + Array.prototype.forEach.call(s, function(c) { + emitKey(stream, c); + }); + return; + } + + // XXX: this "mouse" parsing code is NOT part of the node-core standard + // `readline.js` module, and is a `keypress` module non-standard extension. + if (key.code == '[M') { + key.name = 'mouse'; + var s = key.sequence; + var b = s.charCodeAt(3); + key.x = s.charCodeAt(4) - 040; + key.y = s.charCodeAt(5) - 040; + + key.scroll = 0; + + key.ctrl = !!(1<<4 & b); + key.meta = !!(1<<3 & b); + key.shift = !!(1<<2 & b); + + key.release = (3 & b) === 3; + + if (1<<6 & b) { //scroll + key.scroll = 1 & b ? 1 : -1; + } + + if (!key.release && !key.scroll) { + key.button = b & 3; + } + } + + // Don't emit a key if no name was found + if (key.name === undefined) { + key = undefined; + } + + if (s.length === 1) { + ch = s; + } + + if (key && key.name == 'mouse') { + stream.emit('mousepress', key); + } else if (key || ch) { + stream.emit('keypress', ch, key); + } +} diff --git a/deps/console-menu/node_modules/keypress/package.json b/deps/console-menu/node_modules/keypress/package.json new file mode 100644 index 0000000..9f02d4e --- /dev/null +++ b/deps/console-menu/node_modules/keypress/package.json @@ -0,0 +1,50 @@ +{ + "name": "keypress", + "version": "0.2.1", + "description": "Make any Node ReadableStream emit \"keypress\" events", + "author": { + "name": "Nathan Rajlich", + "email": "nathan@tootallnate.net", + "url": "http://tootallnate.net" + }, + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "git://github.com/TooTallNate/keypress.git" + }, + "keywords": [ + "keypress", + "readline", + "core" + ], + "license": "MIT", + "readme": "keypress\n========\n### Make any Node ReadableStream emit \"keypress\" events\n\n\nPrevious to Node `v0.8.x`, there was an undocumented `\"keypress\"` event that\n`process.stdin` would emit when it was a TTY. Some people discovered this hidden\ngem, and started using it in their own code.\n\nNow in Node `v0.8.x`, this `\"keypress\"` event does not get emitted by default,\nbut rather only when it is being used in conjuction with the `readline` (or by\nextension, the `repl`) module.\n\nThis module is the exact logic from the node `v0.8.x` releases ripped out into its\nown module.\n\n__Bonus:__ Now with mouse support!\n\nInstallation\n------------\n\nInstall with `npm`:\n\n``` bash\n$ npm install keypress\n```\n\nOr add it to the `\"dependencies\"` section of your _package.json_ file.\n\n\nExample\n-------\n\n#### Listening for \"keypress\" events\n\n``` js\nvar keypress = require('keypress');\n\n// make `process.stdin` begin emitting \"keypress\" events\nkeypress(process.stdin);\n\n// listen for the \"keypress\" event\nprocess.stdin.on('keypress', function (ch, key) {\n console.log('got \"keypress\"', key);\n if (key && key.ctrl && key.name == 'c') {\n process.stdin.pause();\n }\n});\n\nprocess.stdin.setRawMode(true);\nprocess.stdin.resume();\n```\n\n#### Listening for \"mousepress\" events\n\n``` js\nvar keypress = require('keypress');\n\n// make `process.stdin` begin emitting \"mousepress\" (and \"keypress\") events\nkeypress(process.stdin);\n\n// you must enable the mouse events before they will begin firing\nkeypress.enableMouse(process.stdout);\n\nprocess.stdin.on('mousepress', function (info) {\n console.log('got \"mousepress\" event at %d x %d', info.x, info.y);\n});\n\nprocess.on('exit', function () {\n // disable mouse on exit, so that the state\n // is back to normal for the terminal\n keypress.disableMouse(process.stdout);\n});\n```\n\n\nLicense\n-------\n\n(The MIT License)\n\nCopyright (c) 2012 Nathan Rajlich <nathan@tootallnate.net>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/TooTallNate/keypress/issues" + }, + "_id": "keypress@0.2.1", + "dist": { + "shasum": "1e80454250018dbad4c3fe94497d6e67b6269c77", + "tarball": "https://registry.npmjs.org/keypress/-/keypress-0.2.1.tgz" + }, + "_from": "keypress@>=0.2.1 <0.3.0", + "_npmVersion": "1.2.32", + "_npmUser": { + "name": "tootallnate", + "email": "nathan@tootallnate.net" + }, + "maintainers": [ + { + "name": "tootallnate", + "email": "nathan@tootallnate.net" + } + ], + "directories": {}, + "_shasum": "1e80454250018dbad4c3fe94497d6e67b6269c77", + "_resolved": "https://registry.npmjs.org/keypress/-/keypress-0.2.1.tgz", + "homepage": "https://github.com/TooTallNate/keypress#readme" +} diff --git a/deps/console-menu/node_modules/keypress/test.js b/deps/console-menu/node_modules/keypress/test.js new file mode 100644 index 0000000..c3f61d7 --- /dev/null +++ b/deps/console-menu/node_modules/keypress/test.js @@ -0,0 +1,28 @@ + +var keypress = require('./') +keypress(process.stdin) + +if (process.stdin.setRawMode) + process.stdin.setRawMode(true) +else + require('tty').setRawMode(true) + +process.stdin.on('keypress', function (c, key) { + console.log(0, c, key) + if (key && key.ctrl && key.name == 'c') { + process.stdin.pause() + } +}) +process.stdin.on('mousepress', function (mouse) { + console.log(mouse) +}) + +keypress.enableMouse(process.stdout) +process.on('exit', function () { + //disable mouse on exit, so that the state is back to normal + //for the terminal. + keypress.disableMouse(process.stdout) +}) + +process.stdin.resume() + diff --git a/deps/console-menu/package.json b/deps/console-menu/package.json new file mode 100644 index 0000000..d8b70a9 --- /dev/null +++ b/deps/console-menu/package.json @@ -0,0 +1,31 @@ +{ + "name": "console-menu", + "version": "0.1.0", + "description": "A scrollable menu for the Node.js console", + "main": "console-menu.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/jasongin/console-menu.git" + }, + "keywords": [ + "menu" + ], + "author": "", + "license": "MIT", + "bugs": { + "url": "https://github.com/jasongin/console-menu/issues" + }, + "homepage": "https://github.com/jasongin/console-menu#readme", + "dependencies": { + "keypress": "^0.2.1" + }, + "readme": "# console-menu\r\nDisplays a menu of items in the console and asynchronously waits for the user to select an item. Each item title is prefixed by a hotkey. An item may be selected by typing a hotkey or by using Down/Up arrows followed by Enter.\r\n```\r\n.--------------.\r\n| Example menu |\r\n+--------------+\r\n| [a] Item A |\r\n| b) Item B |\r\n| c) Item C |\r\n| d) Item D |\r\n| e) Item E |\r\n'--\\/----------'\r\n```\r\nThe menu may be scrollable (hinted by `/\\` and `\\/` indicators). PageUp, PageDown, Home, and End keys are also supported.\r\n\r\n## Usage\r\nThe `menu` function takes two parameters: an `items` array and an `options` object.\r\n\r\nEach item must be an object with the following properties:\r\n * `separator` (boolean): If true, this is a separator item that inserts a blank line into the menu. (All other properties are ignored on separator items.)\r\n * `title` (string): Item title text.\r\n * `hotkey` (character): Unique item hotkey; must be a single letter, number, or other character. If omitted, the item is only selectable via arrow keys + Enter.\r\n * `selected` (boolean) True if this item should initially selected. If unspecified then the first item is initially selected.\r\n\r\nItems may have additional user-defined properties, which will be included in the returned result.\r\n\r\nThe following options are supported:\r\n * `header` (string): Optional header text for the menu.\r\n * `border` (boolean): True to draw a border around the menu. False for a simpler-looking menu.\r\n * `pageSize` (integer): Max number of items to show at a time; additional items cause the menu to be scrollable. Omitting this value (or specifying 0) disables scrolling.\r\n * `helpMessage` (string): Message text to show under the menu.\r\n\r\nThe return value is a `Promise` that resolves to the chosen item object, or to `null` if the menu was cancelled by pressing Esc or Ctrl-C.\r\n\r\n## Example\r\n```JavaScript\r\nvar menu = require('console-menu');\r\nmenu([\r\n { hotkey: '1', title: 'One' },\r\n { hotkey: '2', title: 'Two', selected: true },\r\n { hotkey: '3', title: 'Three' },\r\n { separator: true },\r\n { hotkey: '?', title: 'Help' },\r\n], {\r\n header: 'Example menu',\r\n border: true,\r\n}).then(item => {\r\n if (item) {\r\n console.log('You chose: ' + JSON.stringify(item));\r\n } else {\r\n console.log('You cancelled the menu.');\r\n }\r\n});\r\n```\r\n", + "readmeFilename": "README.md", + "gitHead": "48bf4a044ea4221045ecfdfbd07108d5a309df06", + "_id": "console-menu@0.1.0", + "_shasum": "65baa6dbf3aea0c15d99ddf302e40bbc3d5df33e", + "_from": "console-menu@latest" +} diff --git a/deps/console-menu/test.js b/deps/console-menu/test.js new file mode 100644 index 0000000..3eef8b4 --- /dev/null +++ b/deps/console-menu/test.js @@ -0,0 +1,38 @@ +// A simple interactive test for the console-menu module. + +const menu = require('./console-menu'); + +menu([ + { hotkey: '1', title: 'One' }, + { hotkey: '2', title: 'Two', selected: true }, + { hotkey: '3', title: 'Three' }, + { hotkey: '4', title: 'Four' }, + { separator: true }, + { hotkey: '0', title: 'Do something else...', cascade: true }, + { separator: true }, + { hotkey: '?', title: 'Help' }, +], { + header: 'Test menu', + border: true, +}).then(item => { + if(item && item.cascade) { + return menu(['a','b','c','d','e','f','g','h','i','j'].map(hotkey => { + return { + hotkey, + title: 'Item ' + hotkey.toUpperCase(), + }; + }), { + header: 'Another menu', + border: true, + pageSize: 5, + }); + } else { + return item; + } +}).then(item => { + if (item) { + console.log('You chose: ' + JSON.stringify(item)); + } else { + console.log('You cancelled the menu.'); + } +}); diff --git a/lib/addRemove.js b/lib/addRemove.js index fb3165f..c2759fe 100644 --- a/lib/addRemove.js +++ b/lib/addRemove.js @@ -13,8 +13,11 @@ let nvsExtract = null; // Delay-load /** * Downloads and extracts a version of node. + * + * @param {NodeVersion} version The version to add. + * @param {boolean} useNow True to use the added version now. */ -function addAsync(version) { +function addAsync(version, useNow) { return nvsList.getRemoteVersionsAsync(version.remoteName).then(versions => { let resolvedVersion = nvsList.find(version, versions); if (!resolvedVersion) { @@ -26,8 +29,12 @@ function addAsync(version) { version = resolvedVersion; let binPath = nvsUse.getVersionBinary(version); if (binPath) { - return ['Already added at: ' + nvsUse.homePath(binPath), - 'To use this version now: nvs use ' + version]; + if (useNow) { + return nvsUse.use(version); + } else { + return ['Already added at: ' + nvsUse.homePath(binPath), + 'To use this version now: nvs use ' + version]; + } } else { // Clean up the directory first, in case there is a failed partial extraction. let versionDir = nvsUse.getVersionDir(version); @@ -42,8 +49,12 @@ function addAsync(version) { binPath = nvsUse.getVersionBinary(version); if (binPath) { - return ['Added at: ' + nvsUse.homePath(binPath), - 'To use this version now: nvs use ' + version]; + if (useNow) { + return nvsUse.use(version); + } else { + return ['Added at: ' + nvsUse.homePath(binPath), + 'To use this version now: nvs use ' + version]; + } } else { throw new Error('Add failed - executable file not found.'); } diff --git a/lib/main.js b/lib/main.js index fd95a7a..6ba75c2 100644 --- a/lib/main.js +++ b/lib/main.js @@ -42,7 +42,6 @@ function doCommand(args) { } switch (args[0]) { - case undefined: case '-h': case '/h': case '-?': @@ -62,6 +61,9 @@ function doCommand(args) { let version = null; switch (args[0]) { + case undefined: + return require('./mainMenu').showMainMenuAsync(); + case 'install': if (args[1]) return help('install'); return require('./install').install(); diff --git a/lib/mainMenu.js b/lib/mainMenu.js new file mode 100644 index 0000000..3e10cd0 --- /dev/null +++ b/lib/mainMenu.js @@ -0,0 +1,118 @@ +const menu = require('../deps/console-menu'); +const nvsAddRemove = require('./addRemove'); +const nvsUse = require('./use'); +const nvsList = require('./list'); +const NodeVersion = require('./version'); + +function showMainMenuAsync() { + // TODO: Group by remotes and major versions when there are many items? + let i = 0; + let menuItems = nvsList.getVersions().map(v => { + let title = v.toString({ label: true }); + if (v.current) { + title += ' [current]'; + } + if (v.default) { + title += ' [default]'; + } + return { + hotkey: (i < 26 ? String.fromCharCode('a'.charCodeAt(0) + i++) : null), + title: title, + selected: v.current, + version: v, + }; + }); + + if (menuItems.length === 0) { + return showRemotesMenuAsync(() => undefined); + } + + menuItems = menuItems.concat([ + { separator: true }, + { hotkey: ',', title: 'Download another version' }, + { hotkey: '.', title: 'Don\'t use any version' }, + ]); + + return menu(menuItems, { + border: true, + header: 'Select a version', + pageSize: 15, + }).then(item => { + if (item && item.hotkey === ',') { + return showRemotesMenuAsync(showMainMenuAsync); + } else if (item && item.hotkey === '.') { + return nvsUse.use(null); + } else if (item && item.version) { + return nvsUse.use(item.version); + } + }); +} + +function showRemotesMenuAsync(cancel) { + let remoteNames = Object.keys(settings.remotes) + .filter(r => r !== 'default' && settings.remotes[r]); + if (remoteNames.length === 1) { + return showRemoteVersionsMenuAsync(remoteNames[0], cancel); + } else if (remoteNames.length === 0) { + throw new Error('No remote download souces are configured.'); + } + + let columnWidth = remoteNames + .map(item => item.length) + .reduce((a, b) => a > b ? a : b, 0) + 2; + + let i = 0; + let menuItems = remoteNames.map(remoteName => { + return { + hotkey: (i < 26 ? String.fromCharCode('a'.charCodeAt(0) + i++) : null), + title: remoteName + ' '.repeat(columnWidth - remoteName.length) + + settings.remotes[remoteName], + selected: remoteName === settings.remotes['default'], + remoteName: remoteName, + }; + }); + + return menu(menuItems, { + border: true, + header: 'Select a remote', + pageSize: 15, + }).then(item => { + if (!item) { + return cancel(); + } else if (item.remoteName) { + return showRemoteVersionsMenuAsync(item.remoteName, + showRemotesMenuAsync.bind(this, cancel)); + } + }); +} + +function showRemoteVersionsMenuAsync(remoteName, cancel) { + // TODO: Group by major versions when there are many items? + return nvsList.getRemoteVersionsAsync(remoteName).then(result => { + let i = 0; + let menuItems = result.map(v => { + return { + hotkey: (i < 26 ? String.fromCharCode('a'.charCodeAt(0) + i++) : null), + title: v.toString({ label: true }), + version: v, + }; + }); + + let header = 'Select a ' + remoteName + ' version'; + return menu(menuItems, { + border: true, + header: header, + pageSize: 15, + }).then(item => { + if (item && item.version) { + return nvsAddRemove.addAsync(item.version, true); + } else { + return cancel(); + } + }); + }); +} + +module.exports = { + showMainMenuAsync, +}; \ No newline at end of file diff --git a/package.json b/package.json index 1d59dea..d73a142 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "nvs", - "version": "0.7.2", + "version": "0.8.0", "description": "Node Version Switcher", "main": "lib/main.js", "scripts": { @@ -61,6 +61,5 @@ } }, "dependencies": { - "progress": "^1.1.8" } }