Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

paginator.js 1.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. class Paginator {
  9. constructor(screen) {
  10. this.pointer = 0;
  11. this.lastIndex = 0;
  12. this.screen = screen;
  13. }
  14. paginate(output, active, pageSize) {
  15. pageSize = pageSize || 7;
  16. var middleOfList = Math.floor(pageSize / 2);
  17. var lines = output.split('\n');
  18. if (this.screen) {
  19. lines = this.screen.breakLines(lines);
  20. active = _.sum(lines.map(lineParts => lineParts.length).splice(0, active));
  21. lines = _.flatten(lines);
  22. }
  23. // Make sure there's enough lines to paginate
  24. if (lines.length <= pageSize) {
  25. return output;
  26. }
  27. // Move the pointer only when the user go down and limit it to the middle of the list
  28. if (
  29. this.pointer < middleOfList &&
  30. this.lastIndex < active &&
  31. active - this.lastIndex < pageSize
  32. ) {
  33. this.pointer = Math.min(middleOfList, this.pointer + active - this.lastIndex);
  34. }
  35. this.lastIndex = active;
  36. // Duplicate the lines so it give an infinite list look
  37. var infinite = _.flatten([lines, lines, lines]);
  38. var topIndex = Math.max(0, active + lines.length - this.pointer);
  39. var section = infinite.splice(topIndex, pageSize).join('\n');
  40. return section + '\n' + chalk.dim('(Move up and down to reveal more choices)');
  41. }
  42. }
  43. module.exports = Paginator;