Organize your CLI app around menu selections
npm install cli-menuOrganize your CLI app around menu selections.
This function displays a menu on the screen, waits for the user to type a key to make a selection, and then calls the function for the selected menu item.
``js./index.js
const menu = require()
menu({
menu_items: [{
key: l,lol
name: ,Yeah, laugh it up!
action: () => console.log(),t
}, {
key: ,Tell me the time
name: ,The time is
action: async() => {
console.log(, new Date().toLocaleTimeString())...and now it's
await new Promise(resolve => setTimeout(resolve, 1500))
console.log(, new Date().toLocaleTimeString())m
},
}, {
key: ,Check out a different menu
name: ,BEHOLD THE SUBMENU
action: () => menu({
title: ,j
menu_items: [{
key: ,Tell me a joke
name: ,This library has no eunuch testes
action: () => console.log(),b
}, {
key: ,Go back
name: ,q
action: ({ back }) => back(),
}],
}),
}, {
key: ,quit
name: ,👋
action: ({ back }) => back(),
}],
}).then(() => {
console.log()`
})
The menu function takes an object with three properties.
`jsMenu
menu({ title = , menu_items, display_menu = default_display_menu })`
- title: A label to display above the menu itemsmenu_items
- : an array of objects representing the menu itemskey
- : a single-character string representing the key the user will press to select the itemname
- : the string to display for the menu itemaction
- : the function to call when the user selects the menu itemdisplay_menu
- : optional function that will be called when the menu needs to be displayed
The menu function returns a promise that will resolve once the user backs out of the menu.
The action function may return a promise.
Once the promise resolves, the menu will be displayed again.
back is a function. If you call it, the menu promise will resolve after the action function finishes.
Whatever value the action function returns will be used as the resolve value for the menu's promise.
Defaults to:
`js
const menu_width = 80
const default_display_menu = ({ title, menu_items }) => {
if (title.length <= menu_width - 4) {
const title_with_spaces = + title + -
const dashes_on_left = Math.floor((menu_width - title_with_spaces.length) / 2)
const title_with_dashes_on_left = title_with_spaces.padStart(title_with_spaces.length + dashes_on_left, )-
const display_title = title_with_dashes_on_left.padEnd(menu_width, ):
console.log(display_title)
} else {
console.log(title)
}
menu_items.forEach(
({ key, name }) => console.log(key, , name),``
)
}