paginator.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. 'use strict';
  2. var _ = require('lodash');
  3. var chalk = require('chalk');
  4. /**
  5. * The paginator keep trakcs of a pointer index in a list and return
  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) {
  13. var pageSize = 7;
  14. var lines = output.split('\n');
  15. // Make sure there's enough lines to paginate
  16. if (lines.length <= pageSize + 2) {
  17. return output;
  18. }
  19. // Move the pointer only when the user go down and limit it to 3
  20. if (this.pointer < 3 && this.lastIndex < active && active - this.lastIndex < 9) {
  21. this.pointer = Math.min(3, this.pointer + active - this.lastIndex);
  22. }
  23. this.lastIndex = active;
  24. // Duplicate the lines so it give an infinite list look
  25. var infinite = _.flatten([lines, lines, lines]);
  26. var topIndex = Math.max(0, active + lines.length - this.pointer);
  27. var section = infinite.splice(topIndex, pageSize).join('\n');
  28. return section + '\n' + chalk.dim('(Move up and down to reveal more choices)');
  29. };