2022-01-21 08:28:41 +00:00
|
|
|
'use strict';
|
|
|
|
|
2022-05-29 09:24:36 +00:00
|
|
|
var _ = require('lodash');
|
|
|
|
var chalk = require('chalk');
|
2022-01-21 08:28:41 +00:00
|
|
|
|
|
|
|
/**
|
2022-05-29 09:24:36 +00:00
|
|
|
* The paginator keeps track of a pointer index in a list and returns
|
|
|
|
* a subset of the choices if the list is too long.
|
2022-01-21 08:28:41 +00:00
|
|
|
*/
|
|
|
|
|
|
|
|
class Paginator {
|
2022-05-29 09:24:36 +00:00
|
|
|
constructor(screen) {
|
|
|
|
this.pointer = 0;
|
2022-01-21 08:28:41 +00:00
|
|
|
this.lastIndex = 0;
|
|
|
|
this.screen = screen;
|
|
|
|
}
|
|
|
|
|
|
|
|
paginate(output, active, pageSize) {
|
|
|
|
pageSize = pageSize || 7;
|
2022-05-29 09:24:36 +00:00
|
|
|
var middleOfList = Math.floor(pageSize / 2);
|
|
|
|
var lines = output.split('\n');
|
2022-01-21 08:28:41 +00:00
|
|
|
|
|
|
|
if (this.screen) {
|
|
|
|
lines = this.screen.breakLines(lines);
|
2022-05-29 09:24:36 +00:00
|
|
|
active = _.sum(lines.map(lineParts => lineParts.length).splice(0, active));
|
|
|
|
lines = _.flatten(lines);
|
2022-01-21 08:28:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Make sure there's enough lines to paginate
|
|
|
|
if (lines.length <= pageSize) {
|
|
|
|
return output;
|
|
|
|
}
|
|
|
|
|
|
|
|
// 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
|
|
|
this.lastIndex = active;
|
2022-04-07 07:06:43 +00:00
|
|
|
|
2022-05-29 09:24:36 +00:00
|
|
|
// Duplicate the lines so it give an infinite list look
|
|
|
|
var infinite = _.flatten([lines, lines, lines]);
|
|
|
|
var topIndex = Math.max(0, active + lines.length - this.pointer);
|
2022-01-21 08:28:41 +00:00
|
|
|
|
2022-05-29 09:24:36 +00:00
|
|
|
var section = infinite.splice(topIndex, pageSize).join('\n');
|
|
|
|
return section + '\n' + chalk.dim('(Move up and down to reveal more choices)');
|
2022-01-21 08:28:41 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = Paginator;
|