npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

x-autosuggest

v1.5.0

Published

Autosuggest results based on input.

Downloads

3,509

Readme

x-autosuggest

Build Status BrowserStack Status

Autosuggest results based on input.

Features:

  • Best accessibility practices baked in
  • Flexible styling

Try it now!

Install

npm install x-autosuggest --save

Usage

Following example will decorate existing input element with autosuggest functionality.

When user inputs query, autosuggest first checks if query has less than 2 characters. If it does, no results are returned, otherwise it fetches list of countries and maps names to content (which is country name wrapped in b HTML tag) and value which will be used for input element value.

When user chooses option, closest form element submit event will be triggered.

import autosuggest from 'x-autosuggest';

const element = document.querySelector('input[type="text"]');

const instance = autosuggest(element, {
	onOptionSelect() {
		element.closest('form').submit();
	},
	async onQueryInput(query) {
		if (query.trim().length < 2) {
			return [];
		}
		const response = await fetch(
			`https://restcountries.eu/rest/v2/name/${query}`
		);
		const countries = await response.json();
		return countries.map(({ name }) => {
			return {
				content: `<b>${name}</b>`,
				value: name
			};
		});
	}
});

API

autosuggest(element, options)

Returns: Object

Decorates element with autosuggest functionality.

element

Type: HTMLInputElement

Input element to decorate.

options

Type: Object

onQueryInput

Type: Function
Default: async (query) => []

Callback to run when query changes. You can perform actions such as testing query, fetching data and mapping results to valid format here.

Return value should either be empty array (when you don’t want to display results or don’t have results to display) or array of objects, where each object contains following properties:

content

Type: string

Content for option. Can be regular string or HTML string as markup.

value

Type: *

Value used for input element value.

If it’s null option element will be considered as placeholder element and won’t be used as option. Useful if you want to have dividers between your options, or if you need to group option elements with headings.

meta

Type: *

Additional (meta) information for option. Useful if you need to provide additional complex information for option, e.g. input element value is defined with value option, but if you need to update additional element (e.g. hidden input) with ID of option, you can use meta information for that.

decorateOption

Type: Function
Default: (node) => {}

Decorate autosuggest option. Callback receives one argument which is option Element node. Useful if you want to add additional functionality to option such as attach event listeners or add HTML classes.

If return value is function, it will be used as cleanup callback for when autosuggest instance is removed or option is rerendered. You can perform actions such as custom event handlers removal for option inside this callback.

onFocus

Type: Function
Default: async (currentResults) => []

Callback to run when input element is focused. You can perform actions such as creating initial placeholders.

It receives one argument, which is list of current results.

Return value should be the same as for onQueryInput hook.

decorateInputEvent

Type: Function
Default: (listener) => {}

Decorate input event of input element. Callback receives one argument which is default listener for input event. useful if you want to add additional functionality such as debounce or throttle of events.

onOptionSelect

Type: Function
Default: (event, value, meta) => {}

Callback to run when option is selected. It receives following arguments:

  • Event object of triggered event
  • Value of triggered option
  • Additional (meta) information of triggered option

This callback is useful for performing actions such as triggering form submit.

htmlClassNamespace

Type: string
Default: ``

HTML class namespace in addition to default one (x-Autosuggest).

Useful if you want to create additional styling/functionality selector hook.

instance.destroy()

Destroy instance.

FAQ

How do I cache results?

By default, results are not cached, but it can be achieved with techniques such as memoization.

import autosuggest from 'x-autosuggest';
import memoize from '@f/memoize';

// We cache fetch results based on URL
const cachedFetch = memoize(async (url) => {
	const response = await fetch(url);
	const json = await response.json();
	return {
		ok: response.ok,
		json: async () => json
	};
});

// And then in autosuggest instance options…
const options = {
	onQueryInput(query) {
		return cachedFetch(`https://restcountries.eu/rest/v2/name/${query}`);
		// …
	}
};

How to display current results on input focus?

You can use onFocus hook and return current results.

// In autosuggest instance options…
const options = {
	async onFocus(results) {
		return results;
	}
};

Browser support

Tested in IE11+ and all modern browsers, assuming Promise is available.

Test

For automated tests, run npm run test:automated (append :watch for watcher support).

License

MIT © Ivan Nikolić