nepsilon / search-query-parser

A simple parser for advanced search query syntax
https://www.npmjs.org/package/search-query-parser
MIT License
251 stars 40 forks source link

Return the character offsets of parsed search parts. The use case is … #14

Closed bradvogel closed 7 years ago

bradvogel commented 7 years ago

…that browser code using the library might want to track the cursor position (eg in an HTML element) to understand which part of the search query the user is editing. It could then show an editor specific to that keyboard, such as a calendar picker, and then splice in the edited value back into the search string.

wearhere commented 7 years ago

Neat!

nepsilon commented 7 years ago

Thanks @bradvogel.

But given the use case you describe, how is that better than just using this:

var el = document.querySelector("input[type='search']");
el.addEventListener('keypress', function (ev) {
    var cursor_pos = this.selectionStart;
    // Use the cursor position to show the autocomplete/calendar/etc at the right offset
    console.log(cursor_pos);
});

This is IE9+ compliant.

bradvogel commented 7 years ago

Yes, but this would allow the us to understand which part of the query the user is editing. Here's an example of how this PR could be used using your snippet: https://gist.github.com/bradvogel/ece08f779de0d435a3637dd08b76003a

So as the user is typing, OR when they click directly in to the search box on a search token, we'll know what part of the query they're trying to edit. So in the example if you click to put the cursor into to:brad@gmail.com in the search bar, I could have UI show an autocomplete menu of email addresses. Furthermore, because we know the offsets, I could even modify the search query by splicing in the updated value when you select a new email. Eg using code like this:

        var start = query.slice(0, parsed.offsetStart + parsed.keyword.length + 1 /* Colon */);
        var after = query.slice(parsed.offsetEnd);
        var newQuery = start + newValue + after;
        this.$('input[type="search"]').val(newQuery);
bradvogel commented 7 years ago

ping @nepsilon . Would love to get this merged :)

nepsilon commented 7 years ago

Hi @bradvogel, thanks for the gist and explanation. Even though we are adding 300 new lines in the lib, I think it would take just as many to fully implement the same use-case outside of lib. So let's save people that hassle.

Plus, we're not breaking previous behavior and we have testing for this. So let's merge this baby 👍. Releasing a new version too.