paginator.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. 'use strict';
  2. var _ = require('lodash');
  3. var chalk = require('chalk');
  4. /**
  5. * The paginator keeps track of a pointer index in a list and returns
  6. * a subset of the choices if the list is too long.
  7. */
  8. var Paginator = module.exports = function () {
  9. this.pointer = 0;
  10. this.lastIndex = 0;
  11. };
  12. Paginator.prototype.paginate = function (output, active, pageSize) {
  13. pageSize = pageSize || 7;
  14. var middleOfList = Math.floor(pageSize / 2);
  15. var lines = output.split('\n');
  16. // Make sure there's enough lines to paginate
  17. if (lines.length <= pageSize) {
  18. return output;
  19. }
  20. // Move the pointer only when the user go down and limit it to the middle of the list
  21. if (this.pointer < middleOfList && this.lastIndex < active && active - this.lastIndex < pageSize) {
  22. this.pointer = Math.min(middleOfList, this.pointer + active - this.lastIndex);
  23. }
  24. this.lastIndex = active;
  25. // Duplicate the lines so it give an infinite list look
  26. var infinite = _.flatten([lines, lines, lines]);
  27. var topIndex = Math.max(0, active + lines.length - this.pointer);
  28. var section = infinite.splice(topIndex, pageSize).join('\n');
  29. return section + '\n' + chalk.dim('(Move up and down to reveal more choices)');
  30. };