@inquirer/core 10.1.11 → 10.1.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -46,6 +46,7 @@ const promise_polyfill_ts_1 = require("./promise-polyfill.js");
46
46
  const hook_engine_ts_1 = require("./hook-engine.js");
47
47
  const errors_ts_1 = require("./errors.js");
48
48
  function getCallSites() {
49
+ // eslint-disable-next-line @typescript-eslint/unbound-method
49
50
  const _prepareStackTrace = Error.prepareStackTrace;
50
51
  let result = [];
51
52
  try {
@@ -1,15 +1,16 @@
1
1
  import type { Prettify } from '@inquirer/type';
2
- import { type Theme } from '../theme.ts';
3
- import { type Layout } from './lines.ts';
4
2
  export declare function usePagination<T>({ items, active, renderItem, pageSize, loop, }: {
5
3
  items: ReadonlyArray<T>;
6
4
  /** The index of the active item. */
7
5
  active: number;
8
6
  /** Renders an item as part of a page. */
9
- renderItem: (layout: Prettify<Layout<T>>) => string;
7
+ renderItem: (layout: Prettify<{
8
+ item: T;
9
+ index: number;
10
+ isActive: boolean;
11
+ }>) => string;
10
12
  /** The size of the page. */
11
13
  pageSize: number;
12
14
  /** Allows creating an infinitely looping list. `true` if unspecified. */
13
15
  loop?: boolean;
14
- theme?: Theme;
15
16
  }): string;
@@ -3,31 +3,122 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.usePagination = usePagination;
4
4
  const use_ref_ts_1 = require("../use-ref.js");
5
5
  const utils_ts_1 = require("../utils.js");
6
- const lines_ts_1 = require("./lines.js");
7
- const position_ts_1 = require("./position.js");
8
- function usePagination({ items, active, renderItem, pageSize, loop = true, }) {
9
- const state = (0, use_ref_ts_1.useRef)({ position: 0, lastActive: 0 });
10
- const position = loop
11
- ? (0, position_ts_1.infinite)({
12
- active,
13
- lastActive: state.current.lastActive,
14
- total: items.length,
15
- pageSize,
16
- pointer: state.current.position,
17
- })
18
- : (0, position_ts_1.finite)({
19
- active,
20
- total: items.length,
21
- pageSize,
22
- });
23
- state.current.position = position;
6
+ function usePointerPosition({ active, renderedItems, pageSize, loop, }) {
7
+ const state = (0, use_ref_ts_1.useRef)({
8
+ lastPointer: active,
9
+ lastActive: undefined,
10
+ });
11
+ const { lastPointer, lastActive } = state.current;
12
+ const middle = Math.floor(pageSize / 2);
13
+ const renderedLength = renderedItems.reduce((acc, item) => acc + item.length, 0);
14
+ const defaultPointerPosition = renderedItems
15
+ .slice(0, active)
16
+ .reduce((acc, item) => acc + item.length, 0);
17
+ let pointer = defaultPointerPosition;
18
+ if (renderedLength > pageSize) {
19
+ if (loop) {
20
+ /**
21
+ * Creates the next position for the pointer considering an infinitely
22
+ * looping list of items to be rendered on the page.
23
+ *
24
+ * The goal is to progressively move the cursor to the middle position as the user move down, and then keep
25
+ * the cursor there. When the user move up, maintain the cursor position.
26
+ */
27
+ // By default, keep the cursor position as-is.
28
+ pointer = lastPointer;
29
+ if (
30
+ // First render, skip this logic.
31
+ lastActive != null &&
32
+ // Only move the pointer down when the user moves down.
33
+ lastActive < active &&
34
+ // Check user didn't move up across page boundary.
35
+ active - lastActive < pageSize) {
36
+ pointer = Math.min(
37
+ // Furthest allowed position for the pointer is the middle of the list
38
+ middle, Math.abs(active - lastActive) === 1
39
+ ? Math.min(
40
+ // Move the pointer at most the height of the last active item.
41
+ lastPointer + (renderedItems[lastActive]?.length ?? 0),
42
+ // If the user moved by one item, move the pointer to the natural position of the active item as
43
+ // long as it doesn't move the cursor up.
44
+ Math.max(defaultPointerPosition, lastPointer))
45
+ : // Otherwise, move the pointer down by the difference between the active and last active item.
46
+ lastPointer + active - lastActive);
47
+ }
48
+ }
49
+ else {
50
+ /**
51
+ * Creates the next position for the pointer considering a finite list of
52
+ * items to be rendered on a page.
53
+ *
54
+ * The goal is to keep the pointer in the middle of the page whenever possible, until
55
+ * we reach the bounds of the list (top or bottom). In which case, the cursor moves progressively
56
+ * to the bottom or top of the list.
57
+ */
58
+ const spaceUnderActive = renderedItems
59
+ .slice(active)
60
+ .reduce((acc, item) => acc + item.length, 0);
61
+ pointer =
62
+ spaceUnderActive < pageSize - middle
63
+ ? // If the active item is near the end of the list, progressively move the cursor towards the end.
64
+ pageSize - spaceUnderActive
65
+ : // Otherwise, progressively move the pointer to the middle of the list.
66
+ Math.min(defaultPointerPosition, middle);
67
+ }
68
+ }
69
+ // Save state for the next render
70
+ state.current.lastPointer = pointer;
24
71
  state.current.lastActive = active;
25
- return (0, lines_ts_1.lines)({
26
- items,
27
- width: (0, utils_ts_1.readlineWidth)(),
28
- renderItem,
29
- active,
30
- position,
31
- pageSize,
32
- }).join('\n');
72
+ return pointer;
73
+ }
74
+ function usePagination({ items, active, renderItem, pageSize, loop = true, }) {
75
+ const width = (0, utils_ts_1.readlineWidth)();
76
+ const bound = (num) => ((num % items.length) + items.length) % items.length;
77
+ const renderedItems = items.map((item, index) => {
78
+ if (item == null)
79
+ return [];
80
+ return (0, utils_ts_1.breakLines)(renderItem({ item, index, isActive: index === active }), width).split('\n');
81
+ });
82
+ const renderedLength = renderedItems.reduce((acc, item) => acc + item.length, 0);
83
+ const renderItemAtIndex = (index) => renderedItems[index] ?? [];
84
+ const pointer = usePointerPosition({ active, renderedItems, pageSize, loop });
85
+ // Render the active item to decide the position.
86
+ // If the active item fits under the pointer, we render it there.
87
+ // Otherwise, we need to render it to fit at the bottom of the page; moving the pointer up.
88
+ const activeItem = renderItemAtIndex(active).slice(0, pageSize);
89
+ const activeItemPosition = pointer + activeItem.length <= pageSize ? pointer : pageSize - activeItem.length;
90
+ // Create an array of lines for the page, and add the lines of the active item into the page
91
+ const pageBuffer = Array.from({ length: pageSize });
92
+ pageBuffer.splice(activeItemPosition, activeItem.length, ...activeItem);
93
+ // Store to prevent rendering the same item twice
94
+ const itemVisited = new Set([active]);
95
+ // Fill the page under the active item
96
+ let bufferPointer = activeItemPosition + activeItem.length;
97
+ let itemPointer = bound(active + 1);
98
+ while (bufferPointer < pageSize &&
99
+ !itemVisited.has(itemPointer) &&
100
+ (loop && renderedLength > pageSize ? itemPointer !== active : itemPointer > active)) {
101
+ const lines = renderItemAtIndex(itemPointer);
102
+ const linesToAdd = lines.slice(0, pageSize - bufferPointer);
103
+ pageBuffer.splice(bufferPointer, linesToAdd.length, ...linesToAdd);
104
+ // Move pointers for next iteration
105
+ itemVisited.add(itemPointer);
106
+ bufferPointer += linesToAdd.length;
107
+ itemPointer = bound(itemPointer + 1);
108
+ }
109
+ // Fill the page over the active item
110
+ bufferPointer = activeItemPosition - 1;
111
+ itemPointer = bound(active - 1);
112
+ while (bufferPointer >= 0 &&
113
+ !itemVisited.has(itemPointer) &&
114
+ (loop && renderedLength > pageSize ? itemPointer !== active : itemPointer < active)) {
115
+ const lines = renderItemAtIndex(itemPointer);
116
+ const linesToAdd = lines.slice(Math.max(0, lines.length - bufferPointer - 1));
117
+ pageBuffer.splice(bufferPointer - linesToAdd.length + 1, linesToAdd.length, ...linesToAdd);
118
+ // Move pointers for next iteration
119
+ itemVisited.add(itemPointer);
120
+ bufferPointer -= linesToAdd.length;
121
+ itemPointer = bound(itemPointer - 1);
122
+ }
123
+ return pageBuffer.filter((line) => typeof line === 'string').join('\n');
33
124
  }
@@ -1,7 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.usePrefix = usePrefix;
4
- const node_async_hooks_1 = require("node:async_hooks");
5
4
  const use_state_ts_1 = require("./use-state.js");
6
5
  const use_effect_ts_1 = require("./use-effect.js");
7
6
  const make_theme_ts_1 = require("./make-theme.js");
@@ -14,13 +13,13 @@ function usePrefix({ status = 'idle', theme, }) {
14
13
  let tickInterval;
15
14
  let inc = -1;
16
15
  // Delay displaying spinner by 300ms, to avoid flickering
17
- const delayTimeout = setTimeout(node_async_hooks_1.AsyncResource.bind(() => {
16
+ const delayTimeout = setTimeout(() => {
18
17
  setShowLoader(true);
19
- tickInterval = setInterval(node_async_hooks_1.AsyncResource.bind(() => {
18
+ tickInterval = setInterval(() => {
20
19
  inc = inc + 1;
21
20
  setTick(inc % spinner.frames.length);
22
- }), spinner.interval);
23
- }), 300);
21
+ }, spinner.interval);
22
+ }, 300);
24
23
  return () => {
25
24
  clearTimeout(delayTimeout);
26
25
  clearInterval(tickInterval);
@@ -1,22 +1,23 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.useState = useState;
4
+ const node_async_hooks_1 = require("node:async_hooks");
4
5
  const hook_engine_ts_1 = require("./hook-engine.js");
5
6
  function useState(defaultValue) {
6
7
  return (0, hook_engine_ts_1.withPointer)((pointer) => {
7
- const setFn = (newValue) => {
8
+ const setState = node_async_hooks_1.AsyncResource.bind(function setState(newValue) {
8
9
  // Noop if the value is still the same.
9
10
  if (pointer.get() !== newValue) {
10
11
  pointer.set(newValue);
11
12
  // Trigger re-render
12
13
  (0, hook_engine_ts_1.handleChange)();
13
14
  }
14
- };
15
+ });
15
16
  if (pointer.initialized) {
16
- return [pointer.get(), setFn];
17
+ return [pointer.get(), setState];
17
18
  }
18
19
  const value = typeof defaultValue === 'function' ? defaultValue() : defaultValue;
19
20
  pointer.set(value);
20
- return [value, setFn];
21
+ return [value, setState];
21
22
  });
22
23
  }
@@ -7,6 +7,7 @@ import { PromisePolyfill } from "./promise-polyfill.js";
7
7
  import { withHooks, effectScheduler } from "./hook-engine.js";
8
8
  import { AbortPromptError, CancelPromptError, ExitPromptError } from "./errors.js";
9
9
  function getCallSites() {
10
+ // eslint-disable-next-line @typescript-eslint/unbound-method
10
11
  const _prepareStackTrace = Error.prepareStackTrace;
11
12
  let result = [];
12
13
  try {
@@ -1,15 +1,16 @@
1
1
  import type { Prettify } from '@inquirer/type';
2
- import { type Theme } from '../theme.ts';
3
- import { type Layout } from './lines.ts';
4
2
  export declare function usePagination<T>({ items, active, renderItem, pageSize, loop, }: {
5
3
  items: ReadonlyArray<T>;
6
4
  /** The index of the active item. */
7
5
  active: number;
8
6
  /** Renders an item as part of a page. */
9
- renderItem: (layout: Prettify<Layout<T>>) => string;
7
+ renderItem: (layout: Prettify<{
8
+ item: T;
9
+ index: number;
10
+ isActive: boolean;
11
+ }>) => string;
10
12
  /** The size of the page. */
11
13
  pageSize: number;
12
14
  /** Allows creating an infinitely looping list. `true` if unspecified. */
13
15
  loop?: boolean;
14
- theme?: Theme;
15
16
  }): string;
@@ -1,30 +1,121 @@
1
1
  import { useRef } from "../use-ref.js";
2
- import { readlineWidth } from "../utils.js";
3
- import { lines } from "./lines.js";
4
- import { finite, infinite } from "./position.js";
5
- export function usePagination({ items, active, renderItem, pageSize, loop = true, }) {
6
- const state = useRef({ position: 0, lastActive: 0 });
7
- const position = loop
8
- ? infinite({
9
- active,
10
- lastActive: state.current.lastActive,
11
- total: items.length,
12
- pageSize,
13
- pointer: state.current.position,
14
- })
15
- : finite({
16
- active,
17
- total: items.length,
18
- pageSize,
19
- });
20
- state.current.position = position;
2
+ import { readlineWidth, breakLines } from "../utils.js";
3
+ function usePointerPosition({ active, renderedItems, pageSize, loop, }) {
4
+ const state = useRef({
5
+ lastPointer: active,
6
+ lastActive: undefined,
7
+ });
8
+ const { lastPointer, lastActive } = state.current;
9
+ const middle = Math.floor(pageSize / 2);
10
+ const renderedLength = renderedItems.reduce((acc, item) => acc + item.length, 0);
11
+ const defaultPointerPosition = renderedItems
12
+ .slice(0, active)
13
+ .reduce((acc, item) => acc + item.length, 0);
14
+ let pointer = defaultPointerPosition;
15
+ if (renderedLength > pageSize) {
16
+ if (loop) {
17
+ /**
18
+ * Creates the next position for the pointer considering an infinitely
19
+ * looping list of items to be rendered on the page.
20
+ *
21
+ * The goal is to progressively move the cursor to the middle position as the user move down, and then keep
22
+ * the cursor there. When the user move up, maintain the cursor position.
23
+ */
24
+ // By default, keep the cursor position as-is.
25
+ pointer = lastPointer;
26
+ if (
27
+ // First render, skip this logic.
28
+ lastActive != null &&
29
+ // Only move the pointer down when the user moves down.
30
+ lastActive < active &&
31
+ // Check user didn't move up across page boundary.
32
+ active - lastActive < pageSize) {
33
+ pointer = Math.min(
34
+ // Furthest allowed position for the pointer is the middle of the list
35
+ middle, Math.abs(active - lastActive) === 1
36
+ ? Math.min(
37
+ // Move the pointer at most the height of the last active item.
38
+ lastPointer + (renderedItems[lastActive]?.length ?? 0),
39
+ // If the user moved by one item, move the pointer to the natural position of the active item as
40
+ // long as it doesn't move the cursor up.
41
+ Math.max(defaultPointerPosition, lastPointer))
42
+ : // Otherwise, move the pointer down by the difference between the active and last active item.
43
+ lastPointer + active - lastActive);
44
+ }
45
+ }
46
+ else {
47
+ /**
48
+ * Creates the next position for the pointer considering a finite list of
49
+ * items to be rendered on a page.
50
+ *
51
+ * The goal is to keep the pointer in the middle of the page whenever possible, until
52
+ * we reach the bounds of the list (top or bottom). In which case, the cursor moves progressively
53
+ * to the bottom or top of the list.
54
+ */
55
+ const spaceUnderActive = renderedItems
56
+ .slice(active)
57
+ .reduce((acc, item) => acc + item.length, 0);
58
+ pointer =
59
+ spaceUnderActive < pageSize - middle
60
+ ? // If the active item is near the end of the list, progressively move the cursor towards the end.
61
+ pageSize - spaceUnderActive
62
+ : // Otherwise, progressively move the pointer to the middle of the list.
63
+ Math.min(defaultPointerPosition, middle);
64
+ }
65
+ }
66
+ // Save state for the next render
67
+ state.current.lastPointer = pointer;
21
68
  state.current.lastActive = active;
22
- return lines({
23
- items,
24
- width: readlineWidth(),
25
- renderItem,
26
- active,
27
- position,
28
- pageSize,
29
- }).join('\n');
69
+ return pointer;
70
+ }
71
+ export function usePagination({ items, active, renderItem, pageSize, loop = true, }) {
72
+ const width = readlineWidth();
73
+ const bound = (num) => ((num % items.length) + items.length) % items.length;
74
+ const renderedItems = items.map((item, index) => {
75
+ if (item == null)
76
+ return [];
77
+ return breakLines(renderItem({ item, index, isActive: index === active }), width).split('\n');
78
+ });
79
+ const renderedLength = renderedItems.reduce((acc, item) => acc + item.length, 0);
80
+ const renderItemAtIndex = (index) => renderedItems[index] ?? [];
81
+ const pointer = usePointerPosition({ active, renderedItems, pageSize, loop });
82
+ // Render the active item to decide the position.
83
+ // If the active item fits under the pointer, we render it there.
84
+ // Otherwise, we need to render it to fit at the bottom of the page; moving the pointer up.
85
+ const activeItem = renderItemAtIndex(active).slice(0, pageSize);
86
+ const activeItemPosition = pointer + activeItem.length <= pageSize ? pointer : pageSize - activeItem.length;
87
+ // Create an array of lines for the page, and add the lines of the active item into the page
88
+ const pageBuffer = Array.from({ length: pageSize });
89
+ pageBuffer.splice(activeItemPosition, activeItem.length, ...activeItem);
90
+ // Store to prevent rendering the same item twice
91
+ const itemVisited = new Set([active]);
92
+ // Fill the page under the active item
93
+ let bufferPointer = activeItemPosition + activeItem.length;
94
+ let itemPointer = bound(active + 1);
95
+ while (bufferPointer < pageSize &&
96
+ !itemVisited.has(itemPointer) &&
97
+ (loop && renderedLength > pageSize ? itemPointer !== active : itemPointer > active)) {
98
+ const lines = renderItemAtIndex(itemPointer);
99
+ const linesToAdd = lines.slice(0, pageSize - bufferPointer);
100
+ pageBuffer.splice(bufferPointer, linesToAdd.length, ...linesToAdd);
101
+ // Move pointers for next iteration
102
+ itemVisited.add(itemPointer);
103
+ bufferPointer += linesToAdd.length;
104
+ itemPointer = bound(itemPointer + 1);
105
+ }
106
+ // Fill the page over the active item
107
+ bufferPointer = activeItemPosition - 1;
108
+ itemPointer = bound(active - 1);
109
+ while (bufferPointer >= 0 &&
110
+ !itemVisited.has(itemPointer) &&
111
+ (loop && renderedLength > pageSize ? itemPointer !== active : itemPointer < active)) {
112
+ const lines = renderItemAtIndex(itemPointer);
113
+ const linesToAdd = lines.slice(Math.max(0, lines.length - bufferPointer - 1));
114
+ pageBuffer.splice(bufferPointer - linesToAdd.length + 1, linesToAdd.length, ...linesToAdd);
115
+ // Move pointers for next iteration
116
+ itemVisited.add(itemPointer);
117
+ bufferPointer -= linesToAdd.length;
118
+ itemPointer = bound(itemPointer - 1);
119
+ }
120
+ return pageBuffer.filter((line) => typeof line === 'string').join('\n');
30
121
  }
@@ -1,4 +1,3 @@
1
- import { AsyncResource } from 'node:async_hooks';
2
1
  import { useState } from "./use-state.js";
3
2
  import { useEffect } from "./use-effect.js";
4
3
  import { makeTheme } from "./make-theme.js";
@@ -11,13 +10,13 @@ export function usePrefix({ status = 'idle', theme, }) {
11
10
  let tickInterval;
12
11
  let inc = -1;
13
12
  // Delay displaying spinner by 300ms, to avoid flickering
14
- const delayTimeout = setTimeout(AsyncResource.bind(() => {
13
+ const delayTimeout = setTimeout(() => {
15
14
  setShowLoader(true);
16
- tickInterval = setInterval(AsyncResource.bind(() => {
15
+ tickInterval = setInterval(() => {
17
16
  inc = inc + 1;
18
17
  setTick(inc % spinner.frames.length);
19
- }), spinner.interval);
20
- }), 300);
18
+ }, spinner.interval);
19
+ }, 300);
21
20
  return () => {
22
21
  clearTimeout(delayTimeout);
23
22
  clearInterval(tickInterval);
@@ -1,19 +1,20 @@
1
+ import { AsyncResource } from 'node:async_hooks';
1
2
  import { withPointer, handleChange } from "./hook-engine.js";
2
3
  export function useState(defaultValue) {
3
4
  return withPointer((pointer) => {
4
- const setFn = (newValue) => {
5
+ const setState = AsyncResource.bind(function setState(newValue) {
5
6
  // Noop if the value is still the same.
6
7
  if (pointer.get() !== newValue) {
7
8
  pointer.set(newValue);
8
9
  // Trigger re-render
9
10
  handleChange();
10
11
  }
11
- };
12
+ });
12
13
  if (pointer.initialized) {
13
- return [pointer.get(), setFn];
14
+ return [pointer.get(), setState];
14
15
  }
15
16
  const value = typeof defaultValue === 'function' ? defaultValue() : defaultValue;
16
17
  pointer.set(value);
17
- return [value, setFn];
18
+ return [value, setState];
18
19
  });
19
20
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inquirer/core",
3
- "version": "10.1.11",
3
+ "version": "10.1.13",
4
4
  "description": "Core Inquirer prompt API",
5
5
  "keywords": [
6
6
  "answer",
@@ -74,8 +74,8 @@
74
74
  "tsc": "tshy"
75
75
  },
76
76
  "dependencies": {
77
- "@inquirer/figures": "^1.0.11",
78
- "@inquirer/type": "^3.0.6",
77
+ "@inquirer/figures": "^1.0.12",
78
+ "@inquirer/type": "^3.0.7",
79
79
  "ansi-escapes": "^4.3.2",
80
80
  "cli-width": "^4.1.0",
81
81
  "mute-stream": "^2.0.0",
@@ -84,8 +84,8 @@
84
84
  "yoctocolors-cjs": "^2.1.2"
85
85
  },
86
86
  "devDependencies": {
87
- "@arethetypeswrong/cli": "^0.17.4",
88
- "@inquirer/testing": "^2.1.46",
87
+ "@arethetypeswrong/cli": "^0.18.1",
88
+ "@inquirer/testing": "^2.1.47",
89
89
  "@types/mute-stream": "^0.0.4",
90
90
  "@types/node": "^22.14.0",
91
91
  "@types/wrap-ansi": "^3.0.0",
@@ -114,5 +114,5 @@
114
114
  ".": "./src/index.ts"
115
115
  }
116
116
  },
117
- "gitHead": "50bac82683b9a8d8e06ec87972894d56b2883bcd"
117
+ "gitHead": "dc0770cf6344140b19b2e6b82330fc51084653d1"
118
118
  }
@@ -1,26 +0,0 @@
1
- import { type Prettify } from '@inquirer/type';
2
- /** Represents an item that's part of a layout, about to be rendered */
3
- export type Layout<T> = {
4
- item: T;
5
- index: number;
6
- isActive: boolean;
7
- };
8
- /**
9
- * Renders a page of items as lines that fit within the given width ensuring
10
- * that the number of lines is not greater than the page size, and the active
11
- * item renders at the provided position, while prioritizing that as many lines
12
- * of the active item get rendered as possible.
13
- */
14
- export declare function lines<T>({ items, width, renderItem, active, position: requested, pageSize, }: {
15
- items: ReadonlyArray<T>;
16
- /** The width of a rendered line in characters. */
17
- width: number;
18
- /** Renders an item as part of a page. */
19
- renderItem: (layout: Prettify<Layout<T>>) => string;
20
- /** The index of the active item in the list of items. */
21
- active: number;
22
- /** The position on the page at which to render the active item. */
23
- position: number;
24
- /** The number of lines to render per page. */
25
- pageSize: number;
26
- }): string[];
@@ -1,62 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.lines = lines;
4
- const utils_ts_1 = require("../utils.js");
5
- function split(content, width) {
6
- return (0, utils_ts_1.breakLines)(content, width).split('\n');
7
- }
8
- /**
9
- * Rotates an array of items by an integer number of positions.
10
- * @param {number} count The number of positions to rotate by
11
- * @param {T[]} items The items to rotate
12
- */
13
- function rotate(count, items) {
14
- const max = items.length;
15
- const offset = ((count % max) + max) % max;
16
- return [...items.slice(offset), ...items.slice(0, offset)];
17
- }
18
- /**
19
- * Renders a page of items as lines that fit within the given width ensuring
20
- * that the number of lines is not greater than the page size, and the active
21
- * item renders at the provided position, while prioritizing that as many lines
22
- * of the active item get rendered as possible.
23
- */
24
- function lines({ items, width, renderItem, active, position: requested, pageSize, }) {
25
- const layouts = items.map((item, index) => ({
26
- item,
27
- index,
28
- isActive: index === active,
29
- }));
30
- const layoutsInPage = rotate(active - requested, layouts).slice(0, pageSize);
31
- const renderItemAt = (index) => layoutsInPage[index] == null ? [] : split(renderItem(layoutsInPage[index]), width);
32
- // Create a blank array of lines for the page
33
- const pageBuffer = Array.from({ length: pageSize });
34
- // Render the active item to decide the position
35
- const activeItem = renderItemAt(requested).slice(0, pageSize);
36
- const position = requested + activeItem.length <= pageSize ? requested : pageSize - activeItem.length;
37
- // Add the lines of the active item into the page
38
- pageBuffer.splice(position, activeItem.length, ...activeItem);
39
- // Fill the page under the active item
40
- let bufferPointer = position + activeItem.length;
41
- let layoutPointer = requested + 1;
42
- while (bufferPointer < pageSize && layoutPointer < layoutsInPage.length) {
43
- for (const line of renderItemAt(layoutPointer)) {
44
- pageBuffer[bufferPointer++] = line;
45
- if (bufferPointer >= pageSize)
46
- break;
47
- }
48
- layoutPointer++;
49
- }
50
- // Fill the page over the active item
51
- bufferPointer = position - 1;
52
- layoutPointer = requested - 1;
53
- while (bufferPointer >= 0 && layoutPointer >= 0) {
54
- for (const line of renderItemAt(layoutPointer).reverse()) {
55
- pageBuffer[bufferPointer--] = line;
56
- if (bufferPointer < 0)
57
- break;
58
- }
59
- layoutPointer--;
60
- }
61
- return pageBuffer.filter((line) => typeof line === 'string');
62
- }
@@ -1,20 +0,0 @@
1
- /**
2
- * Creates the next position for the active item considering a finite list of
3
- * items to be rendered on a page.
4
- */
5
- export declare function finite({ active, pageSize, total, }: {
6
- active: number;
7
- pageSize: number;
8
- total: number;
9
- }): number;
10
- /**
11
- * Creates the next position for the active item considering an infinitely
12
- * looping list of items to be rendered on the page.
13
- */
14
- export declare function infinite({ active, lastActive, total, pageSize, pointer, }: {
15
- active: number;
16
- lastActive: number;
17
- total: number;
18
- pageSize: number;
19
- pointer: number;
20
- }): number;
@@ -1,31 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.finite = finite;
4
- exports.infinite = infinite;
5
- /**
6
- * Creates the next position for the active item considering a finite list of
7
- * items to be rendered on a page.
8
- */
9
- function finite({ active, pageSize, total, }) {
10
- const middle = Math.floor(pageSize / 2);
11
- if (total <= pageSize || active < middle)
12
- return active;
13
- if (active >= total - middle)
14
- return active + pageSize - total;
15
- return middle;
16
- }
17
- /**
18
- * Creates the next position for the active item considering an infinitely
19
- * looping list of items to be rendered on the page.
20
- */
21
- function infinite({ active, lastActive, total, pageSize, pointer, }) {
22
- if (total <= pageSize)
23
- return active;
24
- // Move the position only when the user moves down, and when the
25
- // navigation fits within a single page
26
- if (lastActive < active && active - lastActive < pageSize) {
27
- // Limit it to the middle of the list
28
- return Math.min(Math.floor(pageSize / 2), pointer + active - lastActive);
29
- }
30
- return pointer;
31
- }
@@ -1,26 +0,0 @@
1
- import { type Prettify } from '@inquirer/type';
2
- /** Represents an item that's part of a layout, about to be rendered */
3
- export type Layout<T> = {
4
- item: T;
5
- index: number;
6
- isActive: boolean;
7
- };
8
- /**
9
- * Renders a page of items as lines that fit within the given width ensuring
10
- * that the number of lines is not greater than the page size, and the active
11
- * item renders at the provided position, while prioritizing that as many lines
12
- * of the active item get rendered as possible.
13
- */
14
- export declare function lines<T>({ items, width, renderItem, active, position: requested, pageSize, }: {
15
- items: ReadonlyArray<T>;
16
- /** The width of a rendered line in characters. */
17
- width: number;
18
- /** Renders an item as part of a page. */
19
- renderItem: (layout: Prettify<Layout<T>>) => string;
20
- /** The index of the active item in the list of items. */
21
- active: number;
22
- /** The position on the page at which to render the active item. */
23
- position: number;
24
- /** The number of lines to render per page. */
25
- pageSize: number;
26
- }): string[];
@@ -1,59 +0,0 @@
1
- import { breakLines } from "../utils.js";
2
- function split(content, width) {
3
- return breakLines(content, width).split('\n');
4
- }
5
- /**
6
- * Rotates an array of items by an integer number of positions.
7
- * @param {number} count The number of positions to rotate by
8
- * @param {T[]} items The items to rotate
9
- */
10
- function rotate(count, items) {
11
- const max = items.length;
12
- const offset = ((count % max) + max) % max;
13
- return [...items.slice(offset), ...items.slice(0, offset)];
14
- }
15
- /**
16
- * Renders a page of items as lines that fit within the given width ensuring
17
- * that the number of lines is not greater than the page size, and the active
18
- * item renders at the provided position, while prioritizing that as many lines
19
- * of the active item get rendered as possible.
20
- */
21
- export function lines({ items, width, renderItem, active, position: requested, pageSize, }) {
22
- const layouts = items.map((item, index) => ({
23
- item,
24
- index,
25
- isActive: index === active,
26
- }));
27
- const layoutsInPage = rotate(active - requested, layouts).slice(0, pageSize);
28
- const renderItemAt = (index) => layoutsInPage[index] == null ? [] : split(renderItem(layoutsInPage[index]), width);
29
- // Create a blank array of lines for the page
30
- const pageBuffer = Array.from({ length: pageSize });
31
- // Render the active item to decide the position
32
- const activeItem = renderItemAt(requested).slice(0, pageSize);
33
- const position = requested + activeItem.length <= pageSize ? requested : pageSize - activeItem.length;
34
- // Add the lines of the active item into the page
35
- pageBuffer.splice(position, activeItem.length, ...activeItem);
36
- // Fill the page under the active item
37
- let bufferPointer = position + activeItem.length;
38
- let layoutPointer = requested + 1;
39
- while (bufferPointer < pageSize && layoutPointer < layoutsInPage.length) {
40
- for (const line of renderItemAt(layoutPointer)) {
41
- pageBuffer[bufferPointer++] = line;
42
- if (bufferPointer >= pageSize)
43
- break;
44
- }
45
- layoutPointer++;
46
- }
47
- // Fill the page over the active item
48
- bufferPointer = position - 1;
49
- layoutPointer = requested - 1;
50
- while (bufferPointer >= 0 && layoutPointer >= 0) {
51
- for (const line of renderItemAt(layoutPointer).reverse()) {
52
- pageBuffer[bufferPointer--] = line;
53
- if (bufferPointer < 0)
54
- break;
55
- }
56
- layoutPointer--;
57
- }
58
- return pageBuffer.filter((line) => typeof line === 'string');
59
- }
@@ -1,20 +0,0 @@
1
- /**
2
- * Creates the next position for the active item considering a finite list of
3
- * items to be rendered on a page.
4
- */
5
- export declare function finite({ active, pageSize, total, }: {
6
- active: number;
7
- pageSize: number;
8
- total: number;
9
- }): number;
10
- /**
11
- * Creates the next position for the active item considering an infinitely
12
- * looping list of items to be rendered on the page.
13
- */
14
- export declare function infinite({ active, lastActive, total, pageSize, pointer, }: {
15
- active: number;
16
- lastActive: number;
17
- total: number;
18
- pageSize: number;
19
- pointer: number;
20
- }): number;
@@ -1,27 +0,0 @@
1
- /**
2
- * Creates the next position for the active item considering a finite list of
3
- * items to be rendered on a page.
4
- */
5
- export function finite({ active, pageSize, total, }) {
6
- const middle = Math.floor(pageSize / 2);
7
- if (total <= pageSize || active < middle)
8
- return active;
9
- if (active >= total - middle)
10
- return active + pageSize - total;
11
- return middle;
12
- }
13
- /**
14
- * Creates the next position for the active item considering an infinitely
15
- * looping list of items to be rendered on the page.
16
- */
17
- export function infinite({ active, lastActive, total, pageSize, pointer, }) {
18
- if (total <= pageSize)
19
- return active;
20
- // Move the position only when the user moves down, and when the
21
- // navigation fits within a single page
22
- if (lastActive < active && active - lastActive < pageSize) {
23
- // Limit it to the middle of the list
24
- return Math.min(Math.floor(pageSize / 2), pointer + active - lastActive);
25
- }
26
- return pointer;
27
- }