firest commit

This commit is contained in:
wwweww
2026-02-21 22:48:40 +08:00
commit 55e8053e07
1034 changed files with 99049 additions and 0 deletions
+22
View File
@@ -0,0 +1,22 @@
Copyright (c) 2025 Simon Boudrias
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
+181
View File
@@ -0,0 +1,181 @@
# `@inquirer/select`
Simple interactive command line prompt to display a list of choices (single select.)
![select prompt](https://cdn.rawgit.com/SBoudrias/Inquirer.js/28ae8337ba51d93e359ef4f7ee24e79b69898962/assets/screenshots/list.svg)
# Installation
<table>
<tr>
<th>npm</th>
<th>yarn</th>
</tr>
<tr>
<td>
```sh
npm install @inquirer/prompts
```
</td>
<td>
```sh
yarn add @inquirer/prompts
```
</td>
</tr>
<tr>
<td colSpan="2" align="center">Or</td>
</tr>
<tr>
<td>
```sh
npm install @inquirer/select
```
</td>
<td>
```sh
yarn add @inquirer/select
```
</td>
</tr>
</table>
# Usage
```js
import { select, Separator } from '@inquirer/prompts';
// Or
// import select, { Separator } from '@inquirer/select';
const answer = await select({
message: 'Select a package manager',
choices: [
{
name: 'npm',
value: 'npm',
description: 'npm is the most popular package manager',
},
{
name: 'yarn',
value: 'yarn',
description: 'yarn is an awesome package manager',
},
new Separator(),
{
name: 'jspm',
value: 'jspm',
disabled: true,
},
{
name: 'pnpm',
value: 'pnpm',
disabled: '(pnpm is not available)',
},
],
});
```
## Options
| Property | Type | Required | Description |
| -------- | ----------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| message | `string` | yes | The question to ask |
| choices | `Choice[]` | yes | List of the available choices. |
| default | `string` | no | Defines in front of which item the cursor will initially appear. When omitted, the cursor will appear on the first selectable item. |
| pageSize | `number` | no | By default, lists of choice longer than 7 will be paginated. Use this option to control how many choices will appear on the screen at once. |
| loop | `boolean` | no | Defaults to `true`. When set to `false`, the cursor will be constrained to the top and bottom of the choice list without looping. |
| theme | [See Theming](#Theming) | no | Customize look of the prompt. |
`Separator` objects can be used in the `choices` array to render non-selectable lines in the choice list. By default it'll render a line, but you can provide the text as argument (`new Separator('-- Dependencies --')`). This option is often used to add labels to groups within long list of options.
### `Choice` object
The `Choice` object is typed as
```ts
type Choice<Value> = {
value: Value;
name?: string;
description?: string;
short?: string;
disabled?: boolean | string;
};
```
Here's each property:
- `value`: The value is what will be returned by `await select()`.
- `name`: This is the string displayed in the choice list.
- `description`: Option for a longer description string that'll appear under the list when the cursor highlight a given choice.
- `short`: Once the prompt is done (press enter), we'll use `short` if defined to render next to the question. By default we'll use `name`.
- `disabled`: Disallow the option from being selected. If `disabled` is a string, it'll be used as a help tip explaining why the choice isn't available.
`choices` can also be an array of string, in which case the string will be used both as the `value` and the `name`.
## Theming
You can theme a prompt by passing a `theme` object option. The theme object only need to includes the keys you wish to modify, we'll fallback on the defaults for the rest.
```ts
type Theme = {
prefix: string | { idle: string; done: string };
spinner: {
interval: number;
frames: string[];
};
style: {
answer: (text: string) => string;
message: (text: string, status: 'idle' | 'done' | 'loading') => string;
error: (text: string) => string;
help: (text: string) => string;
highlight: (text: string) => string;
description: (text: string) => string;
disabled: (text: string) => string;
keysHelpTip: (keys: [key: string, action: string][]) => string | undefined;
};
icon: {
cursor: string;
};
indexMode: 'hidden' | 'number';
};
```
### `theme.style.keysHelpTip`
This function allows you to customize the keyboard shortcuts help tip displayed below the prompt. It receives an array of key-action pairs and should return a formatted string. You can also hook here to localize the labels to different languages.
It can also returns `undefined` to hide the help tip entirely.
```js
theme: {
style: {
keysHelpTip: (keys) => {
// Return undefined to hide the help tip completely.
return undefined;
// Or customize the formatting. Or localize the labels.
return keys.map(([key, action]) => `${key}: ${action}`).join(' | ');
};
}
}
```
### `theme.indexMode`
Controls how indices are displayed before each choice:
- `hidden` (default): No indices are shown
- `number`: Display a number before each choice (e.g. "1. Option A")
# License
Copyright (c) 2023 Simon Boudrias (twitter: [@vaxilart](https://twitter.com/Vaxilart))<br/>
Licensed under the MIT license.
+32
View File
@@ -0,0 +1,32 @@
import { Separator, type Theme, type Keybinding } from '@inquirer/core';
import type { PartialDeep } from '@inquirer/type';
type SelectTheme = {
icon: {
cursor: string;
};
style: {
disabled: (text: string) => string;
description: (text: string) => string;
keysHelpTip: (keys: [key: string, action: string][]) => string | undefined;
};
indexMode: 'hidden' | 'number';
keybindings: ReadonlyArray<Keybinding>;
};
type Choice<Value> = {
value: Value;
name?: string;
description?: string;
short?: string;
disabled?: boolean | string;
type?: never;
};
declare const _default: <Value>(config: {
message: string;
choices: readonly (Separator | Value | Choice<Value>)[];
pageSize?: number | undefined;
loop?: boolean | undefined;
default?: NoInfer<Value> | undefined;
theme?: PartialDeep<Theme<SelectTheme>> | undefined;
}, context?: import("@inquirer/type").Context) => Promise<Value>;
export default _default;
export { Separator } from '@inquirer/core';
+176
View File
@@ -0,0 +1,176 @@
import { createPrompt, useState, useKeypress, usePrefix, usePagination, useRef, useMemo, useEffect, isBackspaceKey, isEnterKey, isUpKey, isDownKey, isNumberKey, Separator, ValidationError, makeTheme, } from '@inquirer/core';
import { cursorHide } from '@inquirer/ansi';
import { styleText } from 'node:util';
import figures from '@inquirer/figures';
const selectTheme = {
icon: { cursor: figures.pointer },
style: {
disabled: (text) => styleText('dim', `- ${text}`),
description: (text) => styleText('cyan', text),
keysHelpTip: (keys) => keys
.map(([key, action]) => `${styleText('bold', key)} ${styleText('dim', action)}`)
.join(styleText('dim', ' • ')),
},
indexMode: 'hidden',
keybindings: [],
};
function isSelectable(item) {
return !Separator.isSeparator(item) && !item.disabled;
}
function normalizeChoices(choices) {
return choices.map((choice) => {
if (Separator.isSeparator(choice))
return choice;
if (typeof choice !== 'object' || choice === null || !('value' in choice)) {
// It's a raw value (string, number, etc.)
const name = String(choice);
return {
value: choice,
name,
short: name,
disabled: false,
};
}
const name = choice.name ?? String(choice.value);
const normalizedChoice = {
value: choice.value,
name,
short: choice.short ?? name,
disabled: choice.disabled ?? false,
};
if (choice.description) {
normalizedChoice.description = choice.description;
}
return normalizedChoice;
});
}
export default createPrompt((config, done) => {
const { loop = true, pageSize = 7 } = config;
const theme = makeTheme(selectTheme, config.theme);
const { keybindings } = theme;
const [status, setStatus] = useState('idle');
const prefix = usePrefix({ status, theme });
const searchTimeoutRef = useRef();
// Vim keybindings (j/k) conflict with typing those letters in search,
// so search must be disabled when vim bindings are enabled
const searchEnabled = !keybindings.includes('vim');
const items = useMemo(() => normalizeChoices(config.choices), [config.choices]);
const bounds = useMemo(() => {
const first = items.findIndex(isSelectable);
const last = items.findLastIndex(isSelectable);
if (first === -1) {
throw new ValidationError('[select prompt] No selectable choices. All choices are disabled.');
}
return { first, last };
}, [items]);
const defaultItemIndex = useMemo(() => {
if (!('default' in config))
return -1;
return items.findIndex((item) => isSelectable(item) && item.value === config.default);
}, [config.default, items]);
const [active, setActive] = useState(defaultItemIndex === -1 ? bounds.first : defaultItemIndex);
// Safe to assume the cursor position always point to a Choice.
const selectedChoice = items[active];
useKeypress((key, rl) => {
clearTimeout(searchTimeoutRef.current);
if (isEnterKey(key)) {
setStatus('done');
done(selectedChoice.value);
}
else if (isUpKey(key, keybindings) || isDownKey(key, keybindings)) {
rl.clearLine(0);
if (loop ||
(isUpKey(key, keybindings) && active !== bounds.first) ||
(isDownKey(key, keybindings) && active !== bounds.last)) {
const offset = isUpKey(key, keybindings) ? -1 : 1;
let next = active;
do {
next = (next + offset + items.length) % items.length;
} while (!isSelectable(items[next]));
setActive(next);
}
}
else if (isNumberKey(key) && !Number.isNaN(Number(rl.line))) {
const selectedIndex = Number(rl.line) - 1;
// Find the nth item (ignoring separators)
let selectableIndex = -1;
const position = items.findIndex((item) => {
if (Separator.isSeparator(item))
return false;
selectableIndex++;
return selectableIndex === selectedIndex;
});
const item = items[position];
if (item != null && isSelectable(item)) {
setActive(position);
}
searchTimeoutRef.current = setTimeout(() => {
rl.clearLine(0);
}, 700);
}
else if (isBackspaceKey(key)) {
rl.clearLine(0);
}
else if (searchEnabled) {
const searchTerm = rl.line.toLowerCase();
const matchIndex = items.findIndex((item) => {
if (Separator.isSeparator(item) || !isSelectable(item))
return false;
return item.name.toLowerCase().startsWith(searchTerm);
});
if (matchIndex !== -1) {
setActive(matchIndex);
}
searchTimeoutRef.current = setTimeout(() => {
rl.clearLine(0);
}, 700);
}
});
useEffect(() => () => {
clearTimeout(searchTimeoutRef.current);
}, []);
const message = theme.style.message(config.message, status);
const helpLine = theme.style.keysHelpTip([
['↑↓', 'navigate'],
['⏎', 'select'],
]);
let separatorCount = 0;
const page = usePagination({
items,
active,
renderItem({ item, isActive, index }) {
if (Separator.isSeparator(item)) {
separatorCount++;
return ` ${item.separator}`;
}
const indexLabel = theme.indexMode === 'number' ? `${index + 1 - separatorCount}. ` : '';
if (item.disabled) {
const disabledLabel = typeof item.disabled === 'string' ? item.disabled : '(disabled)';
return theme.style.disabled(`${indexLabel}${item.name} ${disabledLabel}`);
}
const color = isActive ? theme.style.highlight : (x) => x;
const cursor = isActive ? theme.icon.cursor : ` `;
return color(`${cursor} ${indexLabel}${item.name}`);
},
pageSize,
loop,
});
if (status === 'done') {
return [prefix, message, theme.style.answer(selectedChoice.short)]
.filter(Boolean)
.join(' ');
}
const { description } = selectedChoice;
const lines = [
[prefix, message].filter(Boolean).join(' '),
page,
' ',
description ? theme.style.description(description) : '',
helpLine,
]
.filter(Boolean)
.join('\n')
.trimEnd();
return `${lines}${cursorHide}`;
});
export { Separator } from '@inquirer/core';
+93
View File
@@ -0,0 +1,93 @@
{
"name": "@inquirer/select",
"version": "5.0.4",
"description": "Inquirer select/list prompt",
"keywords": [
"answer",
"answers",
"ask",
"base",
"cli",
"command",
"command-line",
"confirm",
"enquirer",
"generate",
"generator",
"hyper",
"input",
"inquire",
"inquirer",
"interface",
"iterm",
"javascript",
"menu",
"node",
"nodejs",
"prompt",
"promptly",
"prompts",
"question",
"readline",
"scaffold",
"scaffolder",
"scaffolding",
"stdin",
"stdout",
"terminal",
"tty",
"ui",
"yeoman",
"yo",
"zsh"
],
"homepage": "https://github.com/SBoudrias/Inquirer.js/blob/main/packages/select/README.md",
"license": "MIT",
"author": "Simon Boudrias <admin@simonboudrias.com>",
"repository": {
"type": "git",
"url": "https://github.com/SBoudrias/Inquirer.js.git"
},
"files": [
"dist"
],
"type": "module",
"sideEffects": false,
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"./package.json": "./package.json"
},
"publishConfig": {
"access": "public"
},
"scripts": {
"tsc": "tsc"
},
"dependencies": {
"@inquirer/ansi": "^2.0.3",
"@inquirer/core": "^11.1.1",
"@inquirer/figures": "^2.0.3",
"@inquirer/type": "^4.0.3"
},
"devDependencies": {
"@inquirer/testing": "^3.0.4",
"typescript": "^5.9.3"
},
"peerDependencies": {
"@types/node": ">=18"
},
"peerDependenciesMeta": {
"@types/node": {
"optional": true
}
},
"engines": {
"node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0"
},
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"gitHead": "99d00a9adc53be8b7edf5926b2ec4ba0b792f68f"
}