wishthis/node_modules/inquirer/lib/utils/paginator.js

82 lines
2.2 KiB
JavaScript
Raw Normal View History

2022-01-21 08:28:41 +00:00
'use strict';
2022-06-08 10:36:39 +00:00
const chalk = require('chalk');
2022-01-21 08:28:41 +00:00
/**
2022-06-08 10:36:39 +00:00
* The paginator returns a subset of the choices if the list is too long.
2022-01-21 08:28:41 +00:00
*/
class Paginator {
2022-06-08 10:36:39 +00:00
/**
* @param {import("./screen-manager")} [screen]
* @param {{isInfinite?: boolean}} [options]
*/
constructor(screen, options = {}) {
const { isInfinite = true } = options;
2022-01-21 08:28:41 +00:00
this.lastIndex = 0;
this.screen = screen;
2022-06-08 10:36:39 +00:00
this.isInfinite = isInfinite;
2022-01-21 08:28:41 +00:00
}
paginate(output, active, pageSize) {
pageSize = pageSize || 7;
2022-06-08 10:36:39 +00:00
let lines = output.split('\n');
2022-01-21 08:28:41 +00:00
if (this.screen) {
lines = this.screen.breakLines(lines);
2022-06-08 10:36:39 +00:00
active = lines
.map((lineParts) => lineParts.length)
.splice(0, active)
.reduce((a, b) => a + b, 0);
lines = lines.flat();
2022-01-21 08:28:41 +00:00
}
// Make sure there's enough lines to paginate
if (lines.length <= pageSize) {
return output;
}
2022-06-08 10:36:39 +00:00
const visibleLines = this.isInfinite
? this.getInfiniteLines(lines, active, pageSize)
: this.getFiniteLines(lines, active, pageSize);
this.lastIndex = active;
return (
visibleLines.join('\n') +
'\n' +
chalk.dim('(Move up and down to reveal more choices)')
);
}
2022-01-21 08:28:41 +00:00
2022-06-08 10:36:39 +00:00
getInfiniteLines(lines, active, pageSize) {
if (this.pointer === undefined) {
this.pointer = 0;
}
const middleOfList = Math.floor(pageSize / 2);
2022-01-21 08:28:41 +00:00
// Move the pointer only when the user go down and limit it to the middle of the list
if (
this.pointer < middleOfList &&
this.lastIndex < active &&
active - this.lastIndex < pageSize
) {
this.pointer = Math.min(middleOfList, this.pointer + active - this.lastIndex);
}
2022-05-29 09:24:36 +00:00
// Duplicate the lines so it give an infinite list look
2022-06-08 10:36:39 +00:00
const infinite = [lines, lines, lines].flat();
const topIndex = Math.max(0, active + lines.length - this.pointer);
return infinite.splice(topIndex, pageSize);
}
2022-01-21 08:28:41 +00:00
2022-06-08 10:36:39 +00:00
getFiniteLines(lines, active, pageSize) {
let topIndex = active - pageSize / 2;
if (topIndex < 0) {
topIndex = 0;
} else if (topIndex + pageSize > lines.length) {
topIndex = lines.length - pageSize;
}
return lines.splice(topIndex, pageSize);
2022-01-21 08:28:41 +00:00
}
}
module.exports = Paginator;