-
Notifications
You must be signed in to change notification settings - Fork 211
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Show interactive menus when no command specified
- Loading branch information
Showing
13 changed files
with
1,060 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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.'); | ||
} | ||
}); | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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; |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Oops, something went wrong.