heapwolf / prompt-sync

a synchronous prompt for node.js
MIT License
211 stars 42 forks source link

Fix for handling multiple tab autocomplete attempts #62

Open Vpet95 opened 1 year ago

Vpet95 commented 1 year ago

What is this attempting to fix?

Prior to this PR, a user's input was taken into account only for the first autocompletion pass through; after which prompt-sync would fall back to cycling through the entire possible data set provided by the user, regardless of whether the initial search string yielded multiple possible autocomplete results.

Additionally, any subsequent autocomplete attempts would yield results from anywhere within the new result list, not the start.

How does this fix the problem?

This PR splits the responsibilities of the autocomplete search string and the main output string between two variables. autoCompleteSearchTerm allows users to cycle through the results of the current search, while str allows current selection and terminal output to stay up-to-date as it did before.

Hitting any other key after the tab would clear the current search state.

Testing / Example Case

Simple demo program to demonstrate the fix:

const fullList = [
  "Apple",
  "Broil",
  "Cup",
  "Baseball",
  "Danger",
  "Cast",
  "Dork",
  "Create",
  "Ardvark",
  "Balloon",
  "Avocado",
  "Dog",
  "Aromatic",
  "Destiny",
  "Apperant"
];

const complete = (choices) => (str) =>
  choices.filter(
    (choice) => choice.toLowerCase().indexOf(str.toLowerCase()) === 0
  );

const prompt = require(".")({
  autocomplete: complete(fullList),
});

const resp = prompt("Enter a string then press TAB: ");

console.log(`You entered: ${resp}`);

In either version, running the program and entering "a", followed by TAB would yield the string: "Apple".

Prior to the fix, subsequent TAB inputs would yield the following results:

"Broil"
"Cup"
"Baseball"
"Danger"
etc...

After the fix, subsequent tab inputs yield all a-strings:

"Apperant"
"Apple"
"Ardvark"
"Aromatic"
"Avocado"

Demo

Before

Kapture 2022-08-15 at 21 56 09

After

Kapture 2022-08-15 at 21 57 51