index.js 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. import { createPrompt, useState, useKeypress, usePrefix, usePagination, useRef, useMemo, useEffect, isBackspaceKey, isEnterKey, isUpKey, isDownKey, isNumberKey, Separator, ValidationError, makeTheme, } from '@inquirer/core';
  2. import colors from 'yoctocolors-cjs';
  3. import figures from '@inquirer/figures';
  4. import ansiEscapes from 'ansi-escapes';
  5. const selectTheme = {
  6. icon: { cursor: figures.pointer },
  7. style: {
  8. disabled: (text) => colors.dim(`- ${text}`),
  9. description: (text) => colors.cyan(text),
  10. },
  11. helpMode: 'auto',
  12. indexMode: 'hidden',
  13. };
  14. function isSelectable(item) {
  15. return !Separator.isSeparator(item) && !item.disabled;
  16. }
  17. function normalizeChoices(choices) {
  18. return choices.map((choice) => {
  19. if (Separator.isSeparator(choice))
  20. return choice;
  21. if (typeof choice === 'string') {
  22. return {
  23. value: choice,
  24. name: choice,
  25. short: choice,
  26. disabled: false,
  27. };
  28. }
  29. const name = choice.name ?? String(choice.value);
  30. const normalizedChoice = {
  31. value: choice.value,
  32. name,
  33. short: choice.short ?? name,
  34. disabled: choice.disabled ?? false,
  35. };
  36. if (choice.description) {
  37. normalizedChoice.description = choice.description;
  38. }
  39. return normalizedChoice;
  40. });
  41. }
  42. export default createPrompt((config, done) => {
  43. const { loop = true, pageSize = 7 } = config;
  44. const firstRender = useRef(true);
  45. const theme = makeTheme(selectTheme, config.theme);
  46. const [status, setStatus] = useState('idle');
  47. const prefix = usePrefix({ status, theme });
  48. const searchTimeoutRef = useRef();
  49. const items = useMemo(() => normalizeChoices(config.choices), [config.choices]);
  50. const bounds = useMemo(() => {
  51. const first = items.findIndex(isSelectable);
  52. const last = items.findLastIndex(isSelectable);
  53. if (first === -1) {
  54. throw new ValidationError('[select prompt] No selectable choices. All choices are disabled.');
  55. }
  56. return { first, last };
  57. }, [items]);
  58. const defaultItemIndex = useMemo(() => {
  59. if (!('default' in config))
  60. return -1;
  61. return items.findIndex((item) => isSelectable(item) && item.value === config.default);
  62. }, [config.default, items]);
  63. const [active, setActive] = useState(defaultItemIndex === -1 ? bounds.first : defaultItemIndex);
  64. // Safe to assume the cursor position always point to a Choice.
  65. const selectedChoice = items[active];
  66. useKeypress((key, rl) => {
  67. clearTimeout(searchTimeoutRef.current);
  68. if (isEnterKey(key)) {
  69. setStatus('done');
  70. done(selectedChoice.value);
  71. }
  72. else if (isUpKey(key) || isDownKey(key)) {
  73. rl.clearLine(0);
  74. if (loop ||
  75. (isUpKey(key) && active !== bounds.first) ||
  76. (isDownKey(key) && active !== bounds.last)) {
  77. const offset = isUpKey(key) ? -1 : 1;
  78. let next = active;
  79. do {
  80. next = (next + offset + items.length) % items.length;
  81. } while (!isSelectable(items[next]));
  82. setActive(next);
  83. }
  84. }
  85. else if (isNumberKey(key) && !Number.isNaN(Number(rl.line))) {
  86. const position = Number(rl.line) - 1;
  87. const item = items[position];
  88. if (item != null && isSelectable(item)) {
  89. setActive(position);
  90. }
  91. searchTimeoutRef.current = setTimeout(() => {
  92. rl.clearLine(0);
  93. }, 700);
  94. }
  95. else if (isBackspaceKey(key)) {
  96. rl.clearLine(0);
  97. }
  98. else {
  99. // Default to search
  100. const searchTerm = rl.line.toLowerCase();
  101. const matchIndex = items.findIndex((item) => {
  102. if (Separator.isSeparator(item) || !isSelectable(item))
  103. return false;
  104. return item.name.toLowerCase().startsWith(searchTerm);
  105. });
  106. if (matchIndex !== -1) {
  107. setActive(matchIndex);
  108. }
  109. searchTimeoutRef.current = setTimeout(() => {
  110. rl.clearLine(0);
  111. }, 700);
  112. }
  113. });
  114. useEffect(() => () => {
  115. clearTimeout(searchTimeoutRef.current);
  116. }, []);
  117. const message = theme.style.message(config.message, status);
  118. let helpTipTop = '';
  119. let helpTipBottom = '';
  120. if (theme.helpMode === 'always' ||
  121. (theme.helpMode === 'auto' && firstRender.current)) {
  122. firstRender.current = false;
  123. if (items.length > pageSize) {
  124. helpTipBottom = `\n${theme.style.help('(Use arrow keys to reveal more choices)')}`;
  125. }
  126. else {
  127. helpTipTop = theme.style.help('(Use arrow keys)');
  128. }
  129. }
  130. const page = usePagination({
  131. items,
  132. active,
  133. renderItem({ item, isActive, index }) {
  134. if (Separator.isSeparator(item)) {
  135. return ` ${item.separator}`;
  136. }
  137. const indexLabel = theme.indexMode === 'number' ? `${index + 1}. ` : '';
  138. if (item.disabled) {
  139. const disabledLabel = typeof item.disabled === 'string' ? item.disabled : '(disabled)';
  140. return theme.style.disabled(`${indexLabel}${item.name} ${disabledLabel}`);
  141. }
  142. const color = isActive ? theme.style.highlight : (x) => x;
  143. const cursor = isActive ? theme.icon.cursor : ` `;
  144. return color(`${cursor} ${indexLabel}${item.name}`);
  145. },
  146. pageSize,
  147. loop,
  148. });
  149. if (status === 'done') {
  150. return `${prefix} ${message} ${theme.style.answer(selectedChoice.short)}`;
  151. }
  152. const choiceDescription = selectedChoice.description
  153. ? `\n${theme.style.description(selectedChoice.description)}`
  154. : ``;
  155. return `${[prefix, message, helpTipTop].filter(Boolean).join(' ')}\n${page}${helpTipBottom}${choiceDescription}${ansiEscapes.cursorHide}`;
  156. });
  157. export { Separator } from '@inquirer/core';