ssleptsov / ninja-keys

Keyboard shortcuts interface for your website. Working with static HTML, Vanilla JS, Vue, React, Svelte.
https://ninja-keys-demo.vercel.app/
MIT License
1.62k stars 60 forks source link

Can we implement a search using async data from a server? #36

Open fayazara opened 1 year ago

fayazara commented 1 year ago

We're planning on making the ninja-keys as the primary search window for our tool. It works well for items which are defined already, but is there a way to make api requests and get data and show them in Ninja keys command palette?

CC: @ssleptsov

eelcoj commented 1 year ago

@fayazara Maybe a bit late, but this exactly what I've done for my product. Needs a bit of work, but not too complicated.

search

Anything below "Content Types" is static. Then below that you have all the search results.

elalemanyo commented 1 year ago

@eelcoj how did you do it? did you use ninja-keys?

eelcoj commented 1 year ago

@elalemanyo Yes, all it really does is fire a request to backend's search. The json response is then changed to match the data structure ninja keys need.

elalemanyo commented 1 year ago

@eelcoj can you show me how you are doing it? if it is possible. Thanks

eelcoj commented 1 year ago

@elalemanyo Would only be useful if you use the same framework, right? In essence listen for the change event on the input field, when certain character threshold is met (eg. min. 3 characters), send async post request to get the search results, than merge this result into the data structure needed for ninja-keys.

dandv commented 1 year ago

is there a way to make api requests and get data and show them in Ninja keys command palette?

Yes, but it's not exactly designed for that. There are better tools for the job.

Here's how you'd do it with NinjaKeys:

ninja.addEventListener('change', (event) => {
  debouncedSearch(event.detail.search);  // define your debounced search function
})

One problem with this is that Ninja filters the data array for titles that match the search queries. For keyword searches this is fine, but if you run a semantic search and your result doesn't echo the query (e.g. search for "excursion" and find "trip") then Ninja won't show the result!

One library that displays exactly a search modal is search-modal. Needs some love but does the job more cleanly. You just need to supply the search URL.

olivercoad commented 5 months ago

One problem with this is that Ninja filters the data array

Could you get around that by adding the search query as keyword in data array for all search results so that it always matches?