Ranked searcher
The default search keeps the order of data. With many similar titles, the best match can end up far down the list. This searcher sorts instead: titles that start with the search first, then titles with a word that starts with it, then titles that merely contain it, then keyword matches.
- Paste and Paste and match style first; Copy as path after
- Reopen first, then Open recent (a word starts with it)
- Compare with clipboard last, found by its keyword
- nothing matches: the notice says what Enter will do
// A searcher of your own: rank titles that start with the search above
// those with a word that does, above those that only contain it, and
// keywords last. When nothing matches, a notice says what Enter will do,
// and the `selected` event (which fires with no action) does it.
import '@appulsauce/ninja-keys';
import {const defaultSearcher: SearcherThe search ninja-keys has always done: the text as a case-insensitive
regular expression over title and keywords, across every level at the
root and within the open submenu otherwise.
defaultSearcher} from '@appulsauce/ninja-keys';
import type {INinjaAction, class NinjaKeysA keyboard command palette: a modal list of actions, opened with a hotkey,
searched as you type, with nested menus and per-action hotkeys.
NinjaKeys, type Searcher = (search: string, actions: readonly INinjaAction[], context: SearchContext) => SearchResultDecides which actions a search shows. ninja-keys calls it on every render
with the flattened action list, so it should be cheap; cache anything
derived from actions by the array's identity, which only changes when
data is set.
Searcher} from '@appulsauce/ninja-keys';
/** Lower is better; undefined is no match. */
function function rank(action: INinjaAction, search: string): number | undefinedLower is better; undefined is no match.
rank(action: INinjaActionaction: INinjaAction, search: stringsearch: string): number | undefined {
const const title: stringtitle = action: INinjaActionaction.INinjaAction.title: stringThe text shown in the list, and searched.
title.String.toLowerCase(): stringConverts all the alphabetic characters in a string to lowercase.
toLowerCase();
if (const title: stringtitle.String.startsWith(searchString: string, position?: number): booleanReturns true if the sequence of elements of searchString converted to a String is the
same as the corresponding elements of this object (converted to a String) starting at
position. Otherwise returns false.
startsWith(search: stringsearch)) return 0;
if (const title: stringtitle.String.split(splitter: {
[Symbol.split](string: string, limit?: number): string[];
}, limit?: number): string[] (+1 overload)
Split a string into substrings using the specified separator and return them as an array.
split(/\s+/).Array<string>.some(predicate: (value: string, index: number, array: string[]) => unknown, thisArg?: any): booleanDetermines whether the specified callback function returns true for any element of an array.
some((word: stringword) => word: stringword.String.startsWith(searchString: string, position?: number): booleanReturns true if the sequence of elements of searchString converted to a String is the
same as the corresponding elements of this object (converted to a String) starting at
position. Otherwise returns false.
startsWith(search: stringsearch))) return 1;
if (const title: stringtitle.String.includes(searchString: string, position?: number): booleanReturns true if searchString appears as a substring of the result of converting this
object to a String, at one or more positions that are
greater than or equal to position; otherwise, returns false.
includes(search: stringsearch)) return 2;
if (action: INinjaActionaction.INinjaAction.keywords?: string | undefinedMore words to match, separated by spaces; not shown.
keywords?.String.toLowerCase(): stringConverts all the alphabetic characters in a string to lowercase.
toLowerCase().String.includes(searchString: string, position?: number): booleanReturns true if searchString appears as a substring of the result of converting this
object to a String, at one or more positions that are
greater than or equal to position; otherwise, returns false.
includes(search: stringsearch)) return 3;
return var undefinedundefined;
}
export const const rankedSearcher: SearcherrankedSearcher: type Searcher = (search: string, actions: readonly INinjaAction[], context: SearchContext) => SearchResultDecides which actions a search shows. ninja-keys calls it on every render
with the flattened action list, so it should be cheap; cache anything
derived from actions by the array's identity, which only changes when
data is set.
Searcher = (search: stringsearch, actions: readonly INinjaAction[]actions, context: SearchContextcontext) => {
const const query: stringquery = search: stringsearch.String.trim(): stringRemoves the leading and trailing white space and line terminator characters from a string.
trim().String.toLowerCase(): stringConverts all the alphabetic characters in a string to lowercase.
toLowerCase();
// An empty box lists the open menu, exactly as the default does.
if (!const query: stringquery) return function defaultSearcher(search: string, actions: readonly INinjaAction[], context: SearchContext): SearchResultThe search ninja-keys has always done: the text as a case-insensitive
regular expression over title and keywords, across every level at the
root and within the open submenu otherwise.
defaultSearcher(search: stringsearch, actions: readonly INinjaAction[]actions, context: SearchContextcontext);
const const ranked: {
action: INinjaAction;
score: number;
}[]
ranked = actions: readonly INinjaAction[]actions
.ReadonlyArray<INinjaAction>.map<{
action: INinjaAction;
score: number | undefined;
}>(callbackfn: (value: INinjaAction, index: number, array: readonly INinjaAction[]) => {
action: INinjaAction;
score: number | undefined;
}, thisArg?: any): {
action: INinjaAction;
score: number | undefined;
}[]
Calls a defined callback function on each element of an array, and returns an array that contains the results.
map((action: INinjaActionaction) => ({action: INinjaActionaction, score: number | undefinedscore: function rank(action: INinjaAction, search: string): number | undefinedLower is better; undefined is no match.
rank(action: INinjaActionaction, const query: stringquery)}))
.Array<{ action: INinjaAction; score: number | undefined; }>.filter<{
action: INinjaAction;
score: number;
}>(predicate: (value: {
action: INinjaAction;
score: number | undefined;
}, index: number, array: {
action: INinjaAction;
score: number | undefined;
}[]) => value is {
action: INinjaAction;
score: number;
}, thisArg?: any): {
action: INinjaAction;
score: number;
}[] (+1 overload)
Returns the elements of an array that meet the condition specified in a callback function.
filter(
(entry: {
action: INinjaAction;
score: number | undefined;
}
entry): entry: {
action: INinjaAction;
score: number | undefined;
}
entry is {action: INinjaActionaction: INinjaAction; score: numberscore: number} =>
entry: {
action: INinjaAction;
score: number | undefined;
}
entry.score: number | undefinedscore !== var undefinedundefined
)
.Array<{ action: INinjaAction; score: number; }>.toSorted(compareFn?: ((a: {
action: INinjaAction;
score: number;
}, b: {
action: INinjaAction;
score: number;
}) => number) | undefined): {
action: INinjaAction;
score: number;
}[]
Returns a copy of an array with its elements sorted.
toSorted((a: {
action: INinjaAction;
score: number;
}
a, b: {
action: INinjaAction;
score: number;
}
b) => a: {
action: INinjaAction;
score: number;
}
a.score: numberscore - b: {
action: INinjaAction;
score: number;
}
b.score: numberscore);
return {
SearchResult.actions: readonly INinjaAction[]The actions to show, in the order to show them.
actions: const ranked: {
action: INinjaAction;
score: number;
}[]
ranked.Array<{ action: INinjaAction; score: number; }>.map<INinjaAction>(callbackfn: (value: {
action: INinjaAction;
score: number;
}, index: number, array: {
action: INinjaAction;
score: number;
}[]) => INinjaAction, thisArg?: any): INinjaAction[]
Calls a defined callback function on each element of an array, and returns an array that contains the results.
map((entry: {
action: INinjaAction;
score: number;
}
entry) => entry: {
action: INinjaAction;
score: number;
}
entry.action: INinjaActionaction),
SearchResult.notice?: stringOne line about the query (a half-typed filter, an unknown field).
notice:
const ranked: {
action: INinjaAction;
score: number;
}[]
ranked.Array<{ action: INinjaAction; score: number; }>.length: numberGets or sets the length of the array. This is a number one higher than the highest index in the array.
length === 0
? `Nothing here. Enter searches the web for “${search: stringsearch}”.`
: '',
};
};
export default function function setup(ninja: NinjaKeys, report: (message: string) => void): voidsetup(
ninja: NinjaKeysninja: class NinjaKeysA keyboard command palette: a modal list of actions, opened with a hotkey,
searched as you type, with nested menus and per-action hotkeys.
NinjaKeys,
report: (message: string) => voidreport: (message: stringmessage: string) => void
): void {
const const titles: string[]titles = [
'Paste',
'Paste and match style',
'Copy as path',
'Compare with clipboard',
'Open recent',
'Reopen closed tab',
'Split editor',
];
ninja: NinjaKeysninja.NinjaKeys.data: INinjaAction[]The actions, as a flat list (children name their menu in parent) or
a tree (menus hold their children in children). Assign a new array to
change it; the hotkeys are rebound each time.
data = const titles: string[]titles.Array<string>.map<{
id: string;
title: string;
keywords: string;
handler: () => void;
}>(callbackfn: (value: string, index: number, array: string[]) => {
id: string;
title: string;
keywords: string;
handler: () => void;
}, thisArg?: any): {
id: string;
title: string;
keywords: string;
handler: () => void;
}[]
Calls a defined callback function on each element of an array, and returns an array that contains the results.
map((title: stringtitle) => ({
id: stringid: title: stringtitle,
title: stringtitle,
keywords: stringkeywords: title: stringtitle.String.includes(searchString: string, position?: number): booleanReturns true if searchString appears as a substring of the result of converting this
object to a String, at one or more positions that are
greater than or equal to position; otherwise, returns false.
includes('clipboard') ? 'pasteboard' : '',
handler: () => voidhandler: () => report: (message: string) => voidreport(`Ran "${title: stringtitle}"`),
}));
ninja: NinjaKeysninja.NinjaKeys.searcher: SearcherDecides which actions a search shows, and may add a notice and
completions under the search box. The default is the regular-expression
match over title and keywords; @appulsauce/ninja-keys/catsearch provides a
field query language (section:guides under.title:rendering).
searcher = const rankedSearcher: SearcherrankedSearcher;
ninja: NinjaKeysninja.NinjaKeys.addEventListener<"selected">(type: "selected", listener: (this: NinjaKeys, event: CustomEvent<NinjaSelectedDetail>) => unknown, options?: boolean | AddEventListenerOptions): void (+2 overloads)addEventListener('selected', ({detail: NinjaSelectedDetailThe read-only detail property of the CustomEvent interface returns any data passed when initializing the event.
detail}) => {
if (!detail: NinjaSelectedDetailThe read-only detail property of the CustomEvent interface returns any data passed when initializing the event.
detail.NinjaSelectedDetail.action: INinjaAction | undefinedThe chosen action, or undefined when Enter was pressed on no match.
action) report: (message: string) => voidreport(`Web search for "${detail: NinjaSelectedDetailThe read-only detail property of the CustomEvent interface returns any data passed when initializing the event.
detail.NinjaSelectedDetail.search: stringThe search text when the choice was made.
search}"`);
});
}How it fits the contract
- The searcher returns
{actions, notice}: the contract needs nothing more. The palette still groups the result by section, so ranking is within each section. - On an empty search it hands over to
defaultSearcher, so menus and the top level list exactly as before. - The notice line under the input says what Enter will do when nothing matches, and the
selectedlistener does it:selectedfires with no action in that case.
Unlike the default, this one searches every level even inside a menu; filter by context.root (the open menu’s id) to change that.