@inquirer/core 5.0.1 → 5.1.0

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.
package/README.md CHANGED
@@ -104,6 +104,7 @@ Those hooks are matching the React hooks API:
104
104
  - `useState`
105
105
  - `useRef`
106
106
  - `useEffect`
107
+ - `useMemo`
107
108
 
108
109
  And those are custom utilities from Inquirer:
109
110
 
@@ -124,20 +125,25 @@ Listening for keypress events inside an inquirer prompt is a very common pattern
124
125
 
125
126
  ### `usePagination`
126
127
 
127
- When looping through a long list of options (like in the `select` prompt), paginating the results appearing on the screen at once can be necessary. The `usePagination` hook is the utility used within the `select` and `checkbox` prompt to cycle through the list of options.
128
+ When looping through a long list of options (like in the `select` prompt), paginating the results appearing on the screen at once can be necessary. The `usePagination` hook is the utility used within the `select` and `checkbox` prompts to cycle through the list of options.
129
+
130
+ Pagination works by taking in the list of options and returning a subset of the rendered items that fit within the page. The hook takes in a few options. It needs a list of options (`items`), and a `pageSize` which is the number of lines to be rendered. The `active` index is the index of the currently selected/selectable item. The `loop` option is a boolean that indicates if the list should loop around when reaching the end: this is the default behavior. The pagination hook renders items only as necessary, so it takes a function that can render an item at an index, including an `active` state, called `renderItem`.
128
131
 
129
132
  ```js
130
133
  export default createPrompt((config, done) => {
131
- const [cursorPosition, setCursorPosition] = useState(0);
134
+ const [active, setActive] = useState(0);
132
135
 
133
136
  const allChoices = config.choices.map((choice) => choice.name);
134
137
 
135
- const windowedChoices = usePagination(allChoices, {
136
- active: cursorPosition,
138
+ const page = usePagination({
139
+ items: allChoices,
140
+ active: active,
141
+ renderItem: ({ item, index, isActive }) => `${isActive ? ">" : " "}${index}. ${item.toString()}`
137
142
  pageSize: config.pageSize,
143
+ loop: config.loop,
138
144
  });
139
145
 
140
- return `... ${windowedChoices}`;
146
+ return `... ${page}`;
141
147
  });
142
148
  ```
143
149
 
package/dist/cjs/index.js CHANGED
@@ -14,7 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.Separator = exports.createPrompt = exports.usePagination = exports.useKeypress = exports.useRef = exports.useEffect = exports.useState = exports.usePrefix = void 0;
17
+ exports.Separator = exports.createPrompt = exports.usePagination = exports.useKeypress = exports.useRef = exports.useMemo = exports.useEffect = exports.useState = exports.usePrefix = void 0;
18
18
  __exportStar(require('./lib/key.js'), exports);
19
19
  var use_prefix_mjs_1 = require('./lib/use-prefix.js');
20
20
  Object.defineProperty(exports, "usePrefix", { enumerable: true, get: function () { return use_prefix_mjs_1.usePrefix; } });
@@ -22,11 +22,13 @@ var use_state_mjs_1 = require('./lib/use-state.js');
22
22
  Object.defineProperty(exports, "useState", { enumerable: true, get: function () { return use_state_mjs_1.useState; } });
23
23
  var use_effect_mjs_1 = require('./lib/use-effect.js');
24
24
  Object.defineProperty(exports, "useEffect", { enumerable: true, get: function () { return use_effect_mjs_1.useEffect; } });
25
+ var use_memo_mjs_1 = require('./lib/use-memo.js');
26
+ Object.defineProperty(exports, "useMemo", { enumerable: true, get: function () { return use_memo_mjs_1.useMemo; } });
25
27
  var use_ref_mjs_1 = require('./lib/use-ref.js');
26
28
  Object.defineProperty(exports, "useRef", { enumerable: true, get: function () { return use_ref_mjs_1.useRef; } });
27
29
  var use_keypress_mjs_1 = require('./lib/use-keypress.js');
28
30
  Object.defineProperty(exports, "useKeypress", { enumerable: true, get: function () { return use_keypress_mjs_1.useKeypress; } });
29
- var use_pagination_mjs_1 = require('./lib/use-pagination.js');
31
+ var use_pagination_mjs_1 = require('./lib/pagination/use-pagination.js');
30
32
  Object.defineProperty(exports, "usePagination", { enumerable: true, get: function () { return use_pagination_mjs_1.usePagination; } });
31
33
  var create_prompt_mjs_1 = require('./lib/create-prompt.js');
32
34
  Object.defineProperty(exports, "createPrompt", { enumerable: true, get: function () { return create_prompt_mjs_1.createPrompt; } });
@@ -0,0 +1,63 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.lines = void 0;
4
+ const utils_mjs_1 = require('../utils.js');
5
+ function split(content, width) {
6
+ return (0, utils_mjs_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).concat(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) => split(renderItem(layoutsInPage[index]), width);
32
+ // Create a blank array of lines for the page
33
+ const pageBuffer = new Array(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
+ }
63
+ exports.lines = lines;
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.infinite = exports.finite = void 0;
4
+ /**
5
+ * Creates the next position for the active item considering a finite list of
6
+ * items to be rendered on a page.
7
+ */
8
+ function finite({ active, pageSize, total, }) {
9
+ const middle = Math.floor(pageSize / 2);
10
+ if (total <= pageSize || active < middle)
11
+ return active;
12
+ if (active >= total - middle)
13
+ return active + pageSize - total;
14
+ return middle;
15
+ }
16
+ exports.finite = finite;
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
+ }
32
+ exports.infinite = infinite;
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.usePagination = void 0;
7
+ const chalk_1 = __importDefault(require("chalk"));
8
+ const use_ref_mjs_1 = require('../use-ref.js');
9
+ const utils_mjs_1 = require('../utils.js');
10
+ const lines_mjs_1 = require('./lines.js');
11
+ const position_mjs_1 = require('./position.js');
12
+ function usePagination({ items, active, renderItem, pageSize = 7, loop = true, }) {
13
+ const state = (0, use_ref_mjs_1.useRef)({ position: 0, lastActive: 0 });
14
+ const position = loop
15
+ ? (0, position_mjs_1.infinite)({
16
+ active,
17
+ lastActive: state.current.lastActive,
18
+ total: items.length,
19
+ pageSize,
20
+ pointer: state.current.position,
21
+ })
22
+ : (0, position_mjs_1.finite)({
23
+ active,
24
+ total: items.length,
25
+ pageSize,
26
+ });
27
+ state.current.position = position;
28
+ state.current.lastActive = active;
29
+ const visibleLines = (0, lines_mjs_1.lines)({
30
+ items,
31
+ width: (0, utils_mjs_1.readlineWidth)(),
32
+ renderItem,
33
+ active,
34
+ position,
35
+ pageSize,
36
+ }).join('\n');
37
+ if (items.length > pageSize) {
38
+ return `${visibleLines}\n${chalk_1.default.dim('(Use arrow keys to reveal more choices)')}`;
39
+ }
40
+ return visibleLines;
41
+ }
42
+ exports.usePagination = usePagination;
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.useMemo = void 0;
4
+ const hook_engine_mjs_1 = require('./hook-engine.js');
5
+ function useMemo(fn, dependencies) {
6
+ return (0, hook_engine_mjs_1.withPointer)((pointer) => {
7
+ const prev = pointer.get();
8
+ if (!prev ||
9
+ prev.dependencies.length !== dependencies.length ||
10
+ prev.dependencies.some((dep, i) => dep !== dependencies[i])) {
11
+ const value = fn();
12
+ pointer.set({ value, dependencies });
13
+ return value;
14
+ }
15
+ return prev.value;
16
+ });
17
+ }
18
+ exports.useMemo = useMemo;
@@ -4,25 +4,20 @@ exports.useState = void 0;
4
4
  const hook_engine_mjs_1 = require('./hook-engine.js');
5
5
  function useState(defaultValue) {
6
6
  return (0, hook_engine_mjs_1.withPointer)((pointer) => {
7
- if (!pointer.initialized) {
8
- if (typeof defaultValue === 'function') {
9
- pointer.set(defaultValue());
10
- }
11
- else {
12
- pointer.set(defaultValue);
7
+ const setFn = (newValue) => {
8
+ // Noop if the value is still the same.
9
+ if (pointer.get() !== newValue) {
10
+ pointer.set(newValue);
11
+ // Trigger re-render
12
+ (0, hook_engine_mjs_1.handleChange)();
13
13
  }
14
+ };
15
+ if (pointer.initialized) {
16
+ return [pointer.get(), setFn];
14
17
  }
15
- return [
16
- pointer.get(),
17
- (newValue) => {
18
- // Noop if the value is still the same.
19
- if (pointer.get() !== newValue) {
20
- pointer.set(newValue);
21
- // Trigger re-render
22
- (0, hook_engine_mjs_1.handleChange)();
23
- }
24
- },
25
- ];
18
+ const value = typeof defaultValue === 'function' ? defaultValue() : defaultValue;
19
+ pointer.set(value);
20
+ return [value, setFn];
26
21
  });
27
22
  }
28
23
  exports.useState = useState;
@@ -2,9 +2,10 @@ export * from './lib/key.js';
2
2
  export { usePrefix } from './lib/use-prefix.js';
3
3
  export { useState } from './lib/use-state.js';
4
4
  export { useEffect } from './lib/use-effect.js';
5
+ export { useMemo } from './lib/use-memo.js';
5
6
  export { useRef } from './lib/use-ref.js';
6
7
  export { useKeypress } from './lib/use-keypress.js';
7
- export { usePagination } from './lib/use-pagination.js';
8
+ export { usePagination } from './lib/pagination/use-pagination.js';
8
9
  export { createPrompt, type PromptConfig, type AsyncPromptConfig, } from './lib/create-prompt.js';
9
10
  export { Separator } from './lib/Separator.js';
10
11
  export { type InquirerReadline } from './lib/read-line.type.js';
@@ -7,15 +7,21 @@ type HookStore = {
7
7
  index: number;
8
8
  handleChange: () => void;
9
9
  };
10
- type Pointer = {
11
- get(): any;
12
- set(value: any): void;
13
- initialized: boolean;
14
- };
15
10
  export declare function withHooks(rl: InquirerReadline, cb: (store: HookStore) => void): void;
16
11
  export declare function readline(): InquirerReadline;
17
12
  export declare function withUpdates<T extends (...args: any) => any>(fn: T): (...args: Parameters<T>) => ReturnType<T>;
18
- export declare function withPointer<Value>(cb: (pointer: Pointer) => Value): Value;
13
+ type SetPointer<Value> = {
14
+ get(): Value;
15
+ set(value: Value): void;
16
+ initialized: true;
17
+ };
18
+ type UnsetPointer<Value> = {
19
+ get(): void;
20
+ set(value: Value): void;
21
+ initialized: false;
22
+ };
23
+ type Pointer<Value> = SetPointer<Value> | UnsetPointer<Value>;
24
+ export declare function withPointer<Value, ReturnValue>(cb: (pointer: Pointer<Value>) => ReturnValue): ReturnValue;
19
25
  export declare function handleChange(): void;
20
26
  export declare const effectScheduler: {
21
27
  queue(cb: (readline: InquirerReadline) => void): void;
@@ -0,0 +1,26 @@
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: readonly 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[];
@@ -0,0 +1,20 @@
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;
@@ -0,0 +1,13 @@
1
+ import { type Prettify } from '@inquirer/type';
2
+ import { type Layout } from './lines.js';
3
+ export declare function usePagination<T>({ items, active, renderItem, pageSize, loop, }: {
4
+ items: readonly T[];
5
+ /** The index of the active item. */
6
+ active: number;
7
+ /** Renders an item as part of a page. */
8
+ renderItem: (layout: Prettify<Layout<T>>) => string;
9
+ /** The size of the page. `7` if unspecified. */
10
+ pageSize?: number;
11
+ /** Allows creating an infinitely looping list. `true` if unspecified. */
12
+ loop?: boolean;
13
+ }): string;
@@ -0,0 +1 @@
1
+ export declare function useMemo<Value>(fn: () => Value, dependencies: unknown[]): Value;
@@ -2,8 +2,9 @@ export * from './lib/key.mjs';
2
2
  export { usePrefix } from './lib/use-prefix.mjs';
3
3
  export { useState } from './lib/use-state.mjs';
4
4
  export { useEffect } from './lib/use-effect.mjs';
5
+ export { useMemo } from './lib/use-memo.mjs';
5
6
  export { useRef } from './lib/use-ref.mjs';
6
7
  export { useKeypress } from './lib/use-keypress.mjs';
7
- export { usePagination } from './lib/use-pagination.mjs';
8
+ export { usePagination } from './lib/pagination/use-pagination.mjs';
8
9
  export { createPrompt, } from './lib/create-prompt.mjs';
9
10
  export { Separator } from './lib/Separator.mjs';
@@ -0,0 +1,59 @@
1
+ import { breakLines } from '../utils.mjs';
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).concat(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) => split(renderItem(layoutsInPage[index]), width);
29
+ // Create a blank array of lines for the page
30
+ const pageBuffer = new Array(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
+ }
@@ -0,0 +1,27 @@
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
+ }
@@ -0,0 +1,35 @@
1
+ import chalk from 'chalk';
2
+ import { useRef } from '../use-ref.mjs';
3
+ import { readlineWidth } from '../utils.mjs';
4
+ import { lines } from './lines.mjs';
5
+ import { finite, infinite } from './position.mjs';
6
+ export function usePagination({ items, active, renderItem, pageSize = 7, loop = true, }) {
7
+ const state = useRef({ position: 0, lastActive: 0 });
8
+ const position = loop
9
+ ? infinite({
10
+ active,
11
+ lastActive: state.current.lastActive,
12
+ total: items.length,
13
+ pageSize,
14
+ pointer: state.current.position,
15
+ })
16
+ : finite({
17
+ active,
18
+ total: items.length,
19
+ pageSize,
20
+ });
21
+ state.current.position = position;
22
+ state.current.lastActive = active;
23
+ const visibleLines = lines({
24
+ items,
25
+ width: readlineWidth(),
26
+ renderItem,
27
+ active,
28
+ position,
29
+ pageSize,
30
+ }).join('\n');
31
+ if (items.length > pageSize) {
32
+ return `${visibleLines}\n${chalk.dim('(Use arrow keys to reveal more choices)')}`;
33
+ }
34
+ return visibleLines;
35
+ }
@@ -0,0 +1,14 @@
1
+ import { withPointer } from './hook-engine.mjs';
2
+ export function useMemo(fn, dependencies) {
3
+ return withPointer((pointer) => {
4
+ const prev = pointer.get();
5
+ if (!prev ||
6
+ prev.dependencies.length !== dependencies.length ||
7
+ prev.dependencies.some((dep, i) => dep !== dependencies[i])) {
8
+ const value = fn();
9
+ pointer.set({ value, dependencies });
10
+ return value;
11
+ }
12
+ return prev.value;
13
+ });
14
+ }
@@ -1,24 +1,19 @@
1
1
  import { withPointer, handleChange } from './hook-engine.mjs';
2
2
  export function useState(defaultValue) {
3
3
  return withPointer((pointer) => {
4
- if (!pointer.initialized) {
5
- if (typeof defaultValue === 'function') {
6
- pointer.set(defaultValue());
7
- }
8
- else {
9
- pointer.set(defaultValue);
4
+ const setFn = (newValue) => {
5
+ // Noop if the value is still the same.
6
+ if (pointer.get() !== newValue) {
7
+ pointer.set(newValue);
8
+ // Trigger re-render
9
+ handleChange();
10
10
  }
11
+ };
12
+ if (pointer.initialized) {
13
+ return [pointer.get(), setFn];
11
14
  }
12
- return [
13
- pointer.get(),
14
- (newValue) => {
15
- // Noop if the value is still the same.
16
- if (pointer.get() !== newValue) {
17
- pointer.set(newValue);
18
- // Trigger re-render
19
- handleChange();
20
- }
21
- },
22
- ];
15
+ const value = typeof defaultValue === 'function' ? defaultValue() : defaultValue;
16
+ pointer.set(value);
17
+ return [value, setFn];
23
18
  });
24
19
  }
@@ -2,9 +2,10 @@ export * from './lib/key.mjs';
2
2
  export { usePrefix } from './lib/use-prefix.mjs';
3
3
  export { useState } from './lib/use-state.mjs';
4
4
  export { useEffect } from './lib/use-effect.mjs';
5
+ export { useMemo } from './lib/use-memo.mjs';
5
6
  export { useRef } from './lib/use-ref.mjs';
6
7
  export { useKeypress } from './lib/use-keypress.mjs';
7
- export { usePagination } from './lib/use-pagination.mjs';
8
+ export { usePagination } from './lib/pagination/use-pagination.mjs';
8
9
  export { createPrompt, type PromptConfig, type AsyncPromptConfig, } from './lib/create-prompt.mjs';
9
10
  export { Separator } from './lib/Separator.mjs';
10
11
  export { type InquirerReadline } from './lib/read-line.type.mjs';
@@ -7,15 +7,21 @@ type HookStore = {
7
7
  index: number;
8
8
  handleChange: () => void;
9
9
  };
10
- type Pointer = {
11
- get(): any;
12
- set(value: any): void;
13
- initialized: boolean;
14
- };
15
10
  export declare function withHooks(rl: InquirerReadline, cb: (store: HookStore) => void): void;
16
11
  export declare function readline(): InquirerReadline;
17
12
  export declare function withUpdates<T extends (...args: any) => any>(fn: T): (...args: Parameters<T>) => ReturnType<T>;
18
- export declare function withPointer<Value>(cb: (pointer: Pointer) => Value): Value;
13
+ type SetPointer<Value> = {
14
+ get(): Value;
15
+ set(value: Value): void;
16
+ initialized: true;
17
+ };
18
+ type UnsetPointer<Value> = {
19
+ get(): void;
20
+ set(value: Value): void;
21
+ initialized: false;
22
+ };
23
+ type Pointer<Value> = SetPointer<Value> | UnsetPointer<Value>;
24
+ export declare function withPointer<Value, ReturnValue>(cb: (pointer: Pointer<Value>) => ReturnValue): ReturnValue;
19
25
  export declare function handleChange(): void;
20
26
  export declare const effectScheduler: {
21
27
  queue(cb: (readline: InquirerReadline) => void): void;
@@ -0,0 +1,26 @@
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: readonly 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[];
@@ -0,0 +1,20 @@
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;
@@ -0,0 +1,13 @@
1
+ import { type Prettify } from '@inquirer/type';
2
+ import { type Layout } from './lines.mjs';
3
+ export declare function usePagination<T>({ items, active, renderItem, pageSize, loop, }: {
4
+ items: readonly T[];
5
+ /** The index of the active item. */
6
+ active: number;
7
+ /** Renders an item as part of a page. */
8
+ renderItem: (layout: Prettify<Layout<T>>) => string;
9
+ /** The size of the page. `7` if unspecified. */
10
+ pageSize?: number;
11
+ /** Allows creating an infinitely looping list. `true` if unspecified. */
12
+ loop?: boolean;
13
+ }): string;
@@ -0,0 +1 @@
1
+ export declare function useMemo<Value>(fn: () => Value, dependencies: unknown[]): Value;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inquirer/core",
3
- "version": "5.0.1",
3
+ "version": "5.1.0",
4
4
  "engines": {
5
5
  "node": ">=14.18.0"
6
6
  },
@@ -58,8 +58,8 @@
58
58
  "homepage": "https://github.com/SBoudrias/Inquirer.js/blob/master/packages/core/README.md",
59
59
  "dependencies": {
60
60
  "@inquirer/type": "^1.1.5",
61
- "@types/mute-stream": "^0.0.1",
62
- "@types/node": "^20.6.5",
61
+ "@types/mute-stream": "^0.0.2",
62
+ "@types/node": "^20.8.2",
63
63
  "@types/wrap-ansi": "^3.0.0",
64
64
  "ansi-escapes": "^4.3.2",
65
65
  "chalk": "^4.1.2",
@@ -73,7 +73,7 @@
73
73
  "wrap-ansi": "^6.2.0"
74
74
  },
75
75
  "devDependencies": {
76
- "@inquirer/testing": "^2.1.7"
76
+ "@inquirer/testing": "^2.1.8"
77
77
  },
78
78
  "scripts": {
79
79
  "tsc": "yarn run tsc:esm && yarn run tsc:cjs",
@@ -95,5 +95,5 @@
95
95
  }
96
96
  }
97
97
  },
98
- "gitHead": "85784061d702778bc9dd48ca08f09ee9976b06ee"
98
+ "gitHead": "c88aaca660e58aa0fb079fe656c1004855e029da"
99
99
  }
@@ -1,34 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.usePagination = void 0;
7
- const chalk_1 = __importDefault(require("chalk"));
8
- const utils_mjs_1 = require('./utils.js');
9
- const use_ref_mjs_1 = require('./use-ref.js');
10
- function usePagination(output, { active, pageSize = 7, }) {
11
- const state = (0, use_ref_mjs_1.useRef)({
12
- pointer: 0,
13
- lastIndex: 0,
14
- });
15
- const width = (0, utils_mjs_1.readlineWidth)();
16
- const lines = (0, utils_mjs_1.breakLines)(output, width).split('\n');
17
- // Make sure there's enough lines to paginate
18
- if (lines.length <= pageSize) {
19
- return output;
20
- }
21
- const middleOfList = Math.floor(pageSize / 2);
22
- // Move the pointer only when the user go down and limit it to the middle of the list
23
- const { pointer: prevPointer, lastIndex } = state.current;
24
- if (prevPointer < middleOfList && lastIndex < active && active - lastIndex < pageSize) {
25
- state.current.pointer = Math.min(middleOfList, prevPointer + active - lastIndex);
26
- }
27
- state.current.lastIndex = active;
28
- // Duplicate the lines so it give an infinite list look
29
- const infinite = [lines, lines, lines].flat();
30
- const topIndex = Math.max(0, active + lines.length - state.current.pointer);
31
- const section = infinite.splice(topIndex, pageSize).join('\n');
32
- return section + '\n' + chalk_1.default.dim('(Use arrow keys to reveal more choices)');
33
- }
34
- exports.usePagination = usePagination;
@@ -1,4 +0,0 @@
1
- export declare function usePagination(output: string, { active, pageSize, }: {
2
- active: number;
3
- pageSize?: number;
4
- }): string;
@@ -1,27 +0,0 @@
1
- import chalk from 'chalk';
2
- import { breakLines, readlineWidth } from './utils.mjs';
3
- import { useRef } from './use-ref.mjs';
4
- export function usePagination(output, { active, pageSize = 7, }) {
5
- const state = useRef({
6
- pointer: 0,
7
- lastIndex: 0,
8
- });
9
- const width = readlineWidth();
10
- const lines = breakLines(output, width).split('\n');
11
- // Make sure there's enough lines to paginate
12
- if (lines.length <= pageSize) {
13
- return output;
14
- }
15
- const middleOfList = Math.floor(pageSize / 2);
16
- // Move the pointer only when the user go down and limit it to the middle of the list
17
- const { pointer: prevPointer, lastIndex } = state.current;
18
- if (prevPointer < middleOfList && lastIndex < active && active - lastIndex < pageSize) {
19
- state.current.pointer = Math.min(middleOfList, prevPointer + active - lastIndex);
20
- }
21
- state.current.lastIndex = active;
22
- // Duplicate the lines so it give an infinite list look
23
- const infinite = [lines, lines, lines].flat();
24
- const topIndex = Math.max(0, active + lines.length - state.current.pointer);
25
- const section = infinite.splice(topIndex, pageSize).join('\n');
26
- return section + '\n' + chalk.dim('(Use arrow keys to reveal more choices)');
27
- }
@@ -1,4 +0,0 @@
1
- export declare function usePagination(output: string, { active, pageSize, }: {
2
- active: number;
3
- pageSize?: number;
4
- }): string;