robin-rpr / inquirer-search-list

Inquirer.js Prompt to Fuzzy-Search a list of selectables 🔍
https://npmjs.com/package/inquirer-search-list
Other
30 stars 12 forks source link

DRAFT Add further customization #2

Closed echo-bravo-yahoo closed 3 years ago

echo-bravo-yahoo commented 3 years ago

This change allows customizing the way matching and rendering is done. I'd be happy to clean it up and change the API surface to make this mergeable, but I added this to make a use case of mine possible. Here's what my consumer does using these new features:

const renderRow = (item, isSelected) => {
  const post = item.value;
  if (isSelected) {
    return `${chalk.cyan(figures.pointer)}${chalk.cyan(post.description)} (${chalk.white(url.parse(post.href).hostname)}) [${post.tags.split(' ').join(', ')}]`
  } else {
    return ` ${post.description} (${chalk.dim(url.parse(post.href).hostname)})`
  }
}

const filterSet = (list, query) => {
  list = list.filter((item) => filterOutUntagged(item, query))
  let fuse = new Fuse(list, { keys: ['name'] })
  return fuse.search(query).map((i) => i.item)
}

const filterOutUntagged = ({ value: post }, query) => {
  const desiredTags = query.split(' ').filter((subQuery) => subQuery[0] === '+')
  const queryMinusTags = query.split(' ').filter((subQuery) => subQuery[0] !== '+').join('')
  const actualTags = post.tags.split(' ')
  const validTags =
    desiredTags.every((desiredTag) => actualTags.some((actualTag) => fuzzy.test(desiredTag.slice(1), actualTag)))
  if (validTags) {
    return true
    // fuzzy.test(queryMinusTags, `${post.description} ${url.parse(post.href).hostname}`)
  } else {
    return false
  }
}

const promptUser = async (db) => {
  return inquirer
    .prompt([{
      type: 'search-list',
      message: 'Select a link',
      name: 'link',
      // we just overwrite name anyway in renderRow, not sure why it exists...
      choices: db.map((post) => { return { name: post.description, value: post } }),
      renderRow,
      filterSet
    }])
    .then((answers) => {
      open(answers.link.href)
    })
    .catch((error) => console.log(error))
}
echo-bravo-yahoo commented 3 years ago

Hey! I'm doing a quick run-through the PRs I have open, and just wanted to ask if this is likely to be reviewed for merge or not. :)

echo-bravo-yahoo commented 3 years ago

Hurray! Glad to see this merged & to hear you have plans to tidy things up :)