source: trip-planner-front/node_modules/inquirer/lib/utils/paginator.js@ bdd6491

Last change on this file since bdd6491 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 2.1 KB
Line 
1'use strict';
2
3const _ = {
4 sum: require('lodash/sum'),
5 flatten: require('lodash/flatten'),
6};
7const chalk = require('chalk');
8
9/**
10 * The paginator returns a subset of the choices if the list is too long.
11 */
12
13class Paginator {
14 constructor(screen, options = {}) {
15 const { isInfinite = true } = options;
16 this.lastIndex = 0;
17 this.screen = screen;
18 this.isInfinite = isInfinite;
19 }
20
21 paginate(output, active, pageSize) {
22 pageSize = pageSize || 7;
23 let lines = output.split('\n');
24
25 if (this.screen) {
26 lines = this.screen.breakLines(lines);
27 active = _.sum(lines.map((lineParts) => lineParts.length).splice(0, active));
28 lines = _.flatten(lines);
29 }
30
31 // Make sure there's enough lines to paginate
32 if (lines.length <= pageSize) {
33 return output;
34 }
35 const visibleLines = this.isInfinite
36 ? this.getInfiniteLines(lines, active, pageSize)
37 : this.getFiniteLines(lines, active, pageSize);
38 this.lastIndex = active;
39 return (
40 visibleLines.join('\n') +
41 '\n' +
42 chalk.dim('(Move up and down to reveal more choices)')
43 );
44 }
45
46 getInfiniteLines(lines, active, pageSize) {
47 if (this.pointer === undefined) {
48 this.pointer = 0;
49 }
50 const middleOfList = Math.floor(pageSize / 2);
51 // Move the pointer only when the user go down and limit it to the middle of the list
52 if (
53 this.pointer < middleOfList &&
54 this.lastIndex < active &&
55 active - this.lastIndex < pageSize
56 ) {
57 this.pointer = Math.min(middleOfList, this.pointer + active - this.lastIndex);
58 }
59
60 // Duplicate the lines so it give an infinite list look
61 const infinite = _.flatten([lines, lines, lines]);
62 const topIndex = Math.max(0, active + lines.length - this.pointer);
63
64 return infinite.splice(topIndex, pageSize);
65 }
66
67 getFiniteLines(lines, active, pageSize) {
68 let topIndex = active - pageSize / 2;
69 if (topIndex < 0) {
70 topIndex = 0;
71 } else if (topIndex + pageSize > lines.length) {
72 topIndex = lines.length - pageSize;
73 }
74 return lines.splice(topIndex, pageSize);
75 }
76}
77
78module.exports = Paginator;
Note: See TracBrowser for help on using the repository browser.