基于Node.js和Chalk,可以编写一个CLI表格,并使用箭头键在表格中进行导航。以下是实现示例代码:
const chalk = require('chalk');
const readline = require('readline');
class CLI_Table {
constructor(header, rows) {
this._header = header;
this._rows = rows;
this._selectedRowIndex = 0;
this._isHeaderSelected = true;
this.render();
this.handleKeyPress();
}
render() {
const rowLength = this._rows.length + 1;
readline.cursorTo(process.stdout, 0, 0);
readline.clearScreenDown(process.stdout);
for (let i = 0; i < rowLength; i++) {
let row;
if (i === 0) {
row = this._header.join(' | ');
} else {
row = this._rows[i - 1].join(' | ');
}
if (this._isHeaderSelected && i === 0) {
console.log(chalk.bgWhite.black(row));
} else if (i === this._selectedRowIndex) {
console.log(chalk.inverse(row));
} else {
console.log(row);
}
}
}
handleKeyPress() {
readline.emitKeypressEvents(process.stdin);
process.stdin.setRawMode(true);
process.stdin.on('keypress', (key) => {
if (key === '\u0003') {
process.exit();
}
if (key === '\r') {
this.onSelected();
}
if (key === '\u001B\u005B\u0041') {
if (this._isHeaderSelected) {
this._isHeaderSelected = false;
this._selectedRowIndex = this._rows.length - 1;
} else if (this._selectedRowIndex === 1) {
this._isHeaderSelected = true;
this._selectedRowIndex = 0;
} else {
this._selectedRowIndex--;
}
this.render();
}
if (key === '\u001B\u005B\u0043') {
if (this._isHeaderSelected)