4 sum: require('lodash/sum'),
5 flatten: require('lodash/flatten'),
7 var chalk = require('chalk');
10 * The paginator keeps track of a pointer index in a list and returns
11 * a subset of the choices if the list is too long.
21 paginate(output, active, pageSize) {
22 pageSize = pageSize || 7;
23 var middleOfList = Math.floor(pageSize / 2);
24 var lines = output.split('\n');
27 lines = this.screen.breakLines(lines);
28 active = _.sum(lines.map((lineParts) => lineParts.length).splice(0, active));
29 lines = _.flatten(lines);
32 // Make sure there's enough lines to paginate
33 if (lines.length <= pageSize) {
37 // Move the pointer only when the user go down and limit it to the middle of the list
39 this.pointer < middleOfList &&
40 this.lastIndex < active &&
41 active - this.lastIndex < pageSize
43 this.pointer = Math.min(middleOfList, this.pointer + active - this.lastIndex);
46 this.lastIndex = active;
48 // Duplicate the lines so it give an infinite list look
49 var infinite = _.flatten([lines, lines, lines]);
50 var topIndex = Math.max(0, active + lines.length - this.pointer);
52 var section = infinite.splice(topIndex, pageSize).join('\n');
53 return section + '\n' + chalk.dim('(Move up and down to reveal more choices)');
57 module.exports = Paginator;