index.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  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.Separator = void 0;
  7. const core_1 = require("@inquirer/core");
  8. const yoctocolors_cjs_1 = __importDefault(require("yoctocolors-cjs"));
  9. const figures_1 = __importDefault(require("@inquirer/figures"));
  10. const searchTheme = {
  11. icon: { cursor: figures_1.default.pointer },
  12. style: {
  13. disabled: (text) => yoctocolors_cjs_1.default.dim(`- ${text}`),
  14. searchTerm: (text) => yoctocolors_cjs_1.default.cyan(text),
  15. description: (text) => yoctocolors_cjs_1.default.cyan(text),
  16. },
  17. helpMode: 'auto',
  18. };
  19. function isSelectable(item) {
  20. return !core_1.Separator.isSeparator(item) && !item.disabled;
  21. }
  22. function normalizeChoices(choices) {
  23. return choices.map((choice) => {
  24. if (core_1.Separator.isSeparator(choice))
  25. return choice;
  26. if (typeof choice === 'string') {
  27. return {
  28. value: choice,
  29. name: choice,
  30. short: choice,
  31. disabled: false,
  32. };
  33. }
  34. const name = choice.name ?? String(choice.value);
  35. const normalizedChoice = {
  36. value: choice.value,
  37. name,
  38. short: choice.short ?? name,
  39. disabled: choice.disabled ?? false,
  40. };
  41. if (choice.description) {
  42. normalizedChoice.description = choice.description;
  43. }
  44. return normalizedChoice;
  45. });
  46. }
  47. exports.default = (0, core_1.createPrompt)((config, done) => {
  48. const { pageSize = 7, validate = () => true } = config;
  49. const theme = (0, core_1.makeTheme)(searchTheme, config.theme);
  50. const firstRender = (0, core_1.useRef)(true);
  51. const [status, setStatus] = (0, core_1.useState)('loading');
  52. const [searchTerm, setSearchTerm] = (0, core_1.useState)('');
  53. const [searchResults, setSearchResults] = (0, core_1.useState)([]);
  54. const [searchError, setSearchError] = (0, core_1.useState)();
  55. const prefix = (0, core_1.usePrefix)({ status, theme });
  56. const bounds = (0, core_1.useMemo)(() => {
  57. const first = searchResults.findIndex(isSelectable);
  58. const last = searchResults.findLastIndex(isSelectable);
  59. return { first, last };
  60. }, [searchResults]);
  61. const [active = bounds.first, setActive] = (0, core_1.useState)();
  62. (0, core_1.useEffect)(() => {
  63. const controller = new AbortController();
  64. setStatus('loading');
  65. setSearchError(undefined);
  66. const fetchResults = async () => {
  67. try {
  68. const results = await config.source(searchTerm || undefined, {
  69. signal: controller.signal,
  70. });
  71. if (!controller.signal.aborted) {
  72. // Reset the pointer
  73. setActive(undefined);
  74. setSearchError(undefined);
  75. setSearchResults(normalizeChoices(results));
  76. setStatus('idle');
  77. }
  78. }
  79. catch (error) {
  80. if (!controller.signal.aborted && error instanceof Error) {
  81. setSearchError(error.message);
  82. }
  83. }
  84. };
  85. void fetchResults();
  86. return () => {
  87. controller.abort();
  88. };
  89. }, [searchTerm]);
  90. // Safe to assume the cursor position never points to a Separator.
  91. const selectedChoice = searchResults[active];
  92. (0, core_1.useKeypress)(async (key, rl) => {
  93. if ((0, core_1.isEnterKey)(key)) {
  94. if (selectedChoice) {
  95. setStatus('loading');
  96. const isValid = await validate(selectedChoice.value);
  97. setStatus('idle');
  98. if (isValid === true) {
  99. setStatus('done');
  100. done(selectedChoice.value);
  101. }
  102. else if (selectedChoice.name === searchTerm) {
  103. setSearchError(isValid || 'You must provide a valid value');
  104. }
  105. else {
  106. // Reset line with new search term
  107. rl.write(selectedChoice.name);
  108. setSearchTerm(selectedChoice.name);
  109. }
  110. }
  111. else {
  112. // Reset the readline line value to the previous value. On line event, the value
  113. // get cleared, forcing the user to re-enter the value instead of fixing it.
  114. rl.write(searchTerm);
  115. }
  116. }
  117. else if (key.name === 'tab' && selectedChoice) {
  118. rl.clearLine(0); // Remove the tab character.
  119. rl.write(selectedChoice.name);
  120. setSearchTerm(selectedChoice.name);
  121. }
  122. else if (status !== 'loading' && (key.name === 'up' || key.name === 'down')) {
  123. rl.clearLine(0);
  124. if ((key.name === 'up' && active !== bounds.first) ||
  125. (key.name === 'down' && active !== bounds.last)) {
  126. const offset = key.name === 'up' ? -1 : 1;
  127. let next = active;
  128. do {
  129. next = (next + offset + searchResults.length) % searchResults.length;
  130. } while (!isSelectable(searchResults[next]));
  131. setActive(next);
  132. }
  133. }
  134. else {
  135. setSearchTerm(rl.line);
  136. }
  137. });
  138. const message = theme.style.message(config.message, status);
  139. if (active > 0) {
  140. firstRender.current = false;
  141. }
  142. let helpTip = '';
  143. if (searchResults.length > 1 &&
  144. (theme.helpMode === 'always' || (theme.helpMode === 'auto' && firstRender.current))) {
  145. helpTip =
  146. searchResults.length > pageSize
  147. ? `\n${theme.style.help('(Use arrow keys to reveal more choices)')}`
  148. : `\n${theme.style.help('(Use arrow keys)')}`;
  149. }
  150. // TODO: What to do if no results are found? Should we display a message?
  151. const page = (0, core_1.usePagination)({
  152. items: searchResults,
  153. active,
  154. renderItem({ item, isActive }) {
  155. if (core_1.Separator.isSeparator(item)) {
  156. return ` ${item.separator}`;
  157. }
  158. if (item.disabled) {
  159. const disabledLabel = typeof item.disabled === 'string' ? item.disabled : '(disabled)';
  160. return theme.style.disabled(`${item.name} ${disabledLabel}`);
  161. }
  162. const color = isActive ? theme.style.highlight : (x) => x;
  163. const cursor = isActive ? theme.icon.cursor : ` `;
  164. return color(`${cursor} ${item.name}`);
  165. },
  166. pageSize,
  167. loop: false,
  168. });
  169. let error;
  170. if (searchError) {
  171. error = theme.style.error(searchError);
  172. }
  173. else if (searchResults.length === 0 && searchTerm !== '' && status === 'idle') {
  174. error = theme.style.error('No results found');
  175. }
  176. let searchStr;
  177. if (status === 'done' && selectedChoice) {
  178. const answer = selectedChoice.short;
  179. return `${prefix} ${message} ${theme.style.answer(answer)}`;
  180. }
  181. else {
  182. searchStr = theme.style.searchTerm(searchTerm);
  183. }
  184. const choiceDescription = selectedChoice?.description
  185. ? `\n${theme.style.description(selectedChoice.description)}`
  186. : ``;
  187. return [
  188. [prefix, message, searchStr].filter(Boolean).join(' '),
  189. `${error ?? page}${helpTip}${choiceDescription}`,
  190. ];
  191. });
  192. var core_2 = require("@inquirer/core");
  193. Object.defineProperty(exports, "Separator", { enumerable: true, get: function () { return core_2.Separator; } });