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
Handlers and events report here.
ranked-searcher.ts
// 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: Searcher

The 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 NinjaKeys

A keyboard command palette: a modal list of actions, opened with a hotkey, searched as you type, with nested menus and per-action hotkeys.

@fireschange - On every change of the search text. detail is {search: string, actions: INinjaAction[]}, the actions now shown.@firesselected - When an action is chosen, or Enter is pressed with nothing to choose. detail is {search: string, action?: INinjaAction}.@firesopen - When the palette becomes visible, however it was opened.@firesclose - When the palette is hidden, however it was closed: a method, a hotkey, Escape, a click on the overlay, or an action.@slotfooter - Replaces the key-hint footer; an empty element hides it.@csspartactions-list - The scrolling list that holds every action.@csspartninja-action - One action row.@csspartninja-selected - The selected action row.@csspartninja-icon - An action's Material icon.@csspartninja-input - The search input.@csspartninja-input-wrapper - The element around the search input.@csspartninja-search-hint - The line under the input holding a searcher's completions and notice.@csspartninja-suggestion - One completion chip.@csspartninja-notice - A searcher's notice.@cssprop[--ninja-width=640px] - Width of the palette.@cssprop[--ninja-top=20%] - Distance from the top of the viewport.@cssprop[--ninja-font-size=16px] - Base size every other size scales from.@cssprop[--ninja-font-family=inherit] - Font of the palette.@cssprop[--ninja-code-font-family=ui-monospace, monospace] - Font of completion chips.@cssprop[--ninja-z-index=1] - Stacking order of the overlay.@cssprop[--ninja-backdrop-filter=none] - Filter behind the overlay, such as blur(4px).@cssprop[--ninja-overflow-background=rgba(255, 255, 255, 0.5)] - The overlay over the page.@cssprop[--ninja-modal-background=#fff] - Background of the palette.@cssprop[--ninja-modal-shadow=rgb(0 0 0 / 50%) 0px 16px 70px] - Shadow of the palette.@cssprop[--ninja-text-color=rgb(60, 65, 73)] - Text.@cssprop[--ninja-accent-color=rgb(110, 94, 210)] - Caret, selection bar and focused chips.@cssprop[--ninja-secondary-text-color=rgb(107, 111, 118)] - Hints, keys and breadcrumbs.@cssprop[--ninja-secondary-background-color=rgb(239, 241, 244)] - Key badges, breadcrumbs and chips.@cssprop[--ninja-selected-background=rgb(248, 249, 251)] - The selected row.@cssprop[--ninja-selected-text-color=inherit] - Text of the selected row.@cssprop[--ninja-placeholder-color=#8e8e8e] - Placeholder of the input.@cssprop[--ninja-group-text-color=rgb(144, 149, 157)] - Section headers.@cssprop[--ninja-icon-color=var(--ninja-secondary-text-color)] - Icons.@cssprop[--ninja-icon-size=1.2em] - Icons.@cssprop[--ninja-key-border-radius=0.25em] - Key badges, breadcrumbs and chips.@cssprop[--ninja-separate-border=1px solid var(--ninja-secondary-background-color)] - Lines between the input, the list and the footer.@cssprop[--ninja-actions-height=300px] - Maximum height of the list.@cssprop[--ninja-footer-background=rgba(242, 242, 242, 0.4)] - The footer.
NinjaKeys
, type Searcher = (search: string, actions: readonly INinjaAction[], context: SearchContext) => SearchResult

Decides 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 | undefined

Lower is better; undefined is no match.

rank
(action: INinjaActionaction: INinjaAction, search: stringsearch: string): number | undefined {
const const title: stringtitle = action: INinjaActionaction.INinjaAction.title: string

The text shown in the list, and searched.

title
.String.toLowerCase(): string

Converts all the alphabetic characters in a string to lowercase.

toLowerCase
();
if (const title: stringtitle.String.startsWith(searchString: string, position?: number): boolean

Returns 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.

@paramsplitter An object that can split a string.@paramlimit A value used to limit the number of elements returned in the array.
split
(/\s+/).Array<string>.some(predicate: (value: string, index: number, array: string[]) => unknown, thisArg?: any): boolean

Determines whether the specified callback function returns true for any element of an array.

@parampredicate A function that accepts up to three arguments. The some method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value true, or until the end of the array.@paramthisArg An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
some
((word: stringword) => word: stringword.String.startsWith(searchString: string, position?: number): boolean

Returns 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): boolean

Returns 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.

@paramsearchString search string@paramposition If position is undefined, 0 is assumed, so as to search all of the String.
includes
(search: stringsearch)) return 2;
if (action: INinjaActionaction.INinjaAction.keywords?: string | undefined

More words to match, separated by spaces; not shown.

keywords
?.String.toLowerCase(): string

Converts all the alphabetic characters in a string to lowercase.

toLowerCase
().String.includes(searchString: string, position?: number): boolean

Returns 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.

@paramsearchString search string@paramposition If position is undefined, 0 is assumed, so as to search all of the String.
includes
(search: stringsearch)) return 3;
return var undefinedundefined; } export const const rankedSearcher: SearcherrankedSearcher: type Searcher = (search: string, actions: readonly INinjaAction[], context: SearchContext) => SearchResult

Decides 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(): string

Removes the leading and trailing white space and line terminator characters from a string.

trim
().String.toLowerCase(): string

Converts 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): SearchResult

The 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.

@paramcallbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.@paramthisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
map
((action: INinjaActionaction) => ({action: INinjaActionaction, score: number | undefinedscore: function rank(action: INinjaAction, search: string): number | undefined

Lower 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.

@parampredicate A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.@paramthisArg An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
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.

@paramcompareFn Function used to determine the order of the elements. It is expected to return a negative value if the first argument is less than the second argument, zero if they're equal, and a positive value otherwise. If omitted, the elements are sorted in ascending, UTF-16 code unit order. ts [11, 2, 22, 1].toSorted((a, b) => a - b) // [1, 2, 11, 22]
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.

@paramcallbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.@paramthisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
map
((
entry: {
    action: INinjaAction;
    score: number;
}
entry
) =>
entry: {
    action: INinjaAction;
    score: number;
}
entry
.action: INinjaActionaction),
SearchResult.notice?: string

One 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: number

Gets 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 NinjaKeys

A keyboard command palette: a modal list of actions, opened with a hotkey, searched as you type, with nested menus and per-action hotkeys.

@fireschange - On every change of the search text. detail is {search: string, actions: INinjaAction[]}, the actions now shown.@firesselected - When an action is chosen, or Enter is pressed with nothing to choose. detail is {search: string, action?: INinjaAction}.@firesopen - When the palette becomes visible, however it was opened.@firesclose - When the palette is hidden, however it was closed: a method, a hotkey, Escape, a click on the overlay, or an action.@slotfooter - Replaces the key-hint footer; an empty element hides it.@csspartactions-list - The scrolling list that holds every action.@csspartninja-action - One action row.@csspartninja-selected - The selected action row.@csspartninja-icon - An action's Material icon.@csspartninja-input - The search input.@csspartninja-input-wrapper - The element around the search input.@csspartninja-search-hint - The line under the input holding a searcher's completions and notice.@csspartninja-suggestion - One completion chip.@csspartninja-notice - A searcher's notice.@cssprop[--ninja-width=640px] - Width of the palette.@cssprop[--ninja-top=20%] - Distance from the top of the viewport.@cssprop[--ninja-font-size=16px] - Base size every other size scales from.@cssprop[--ninja-font-family=inherit] - Font of the palette.@cssprop[--ninja-code-font-family=ui-monospace, monospace] - Font of completion chips.@cssprop[--ninja-z-index=1] - Stacking order of the overlay.@cssprop[--ninja-backdrop-filter=none] - Filter behind the overlay, such as blur(4px).@cssprop[--ninja-overflow-background=rgba(255, 255, 255, 0.5)] - The overlay over the page.@cssprop[--ninja-modal-background=#fff] - Background of the palette.@cssprop[--ninja-modal-shadow=rgb(0 0 0 / 50%) 0px 16px 70px] - Shadow of the palette.@cssprop[--ninja-text-color=rgb(60, 65, 73)] - Text.@cssprop[--ninja-accent-color=rgb(110, 94, 210)] - Caret, selection bar and focused chips.@cssprop[--ninja-secondary-text-color=rgb(107, 111, 118)] - Hints, keys and breadcrumbs.@cssprop[--ninja-secondary-background-color=rgb(239, 241, 244)] - Key badges, breadcrumbs and chips.@cssprop[--ninja-selected-background=rgb(248, 249, 251)] - The selected row.@cssprop[--ninja-selected-text-color=inherit] - Text of the selected row.@cssprop[--ninja-placeholder-color=#8e8e8e] - Placeholder of the input.@cssprop[--ninja-group-text-color=rgb(144, 149, 157)] - Section headers.@cssprop[--ninja-icon-color=var(--ninja-secondary-text-color)] - Icons.@cssprop[--ninja-icon-size=1.2em] - Icons.@cssprop[--ninja-key-border-radius=0.25em] - Key badges, breadcrumbs and chips.@cssprop[--ninja-separate-border=1px solid var(--ninja-secondary-background-color)] - Lines between the input, the list and the footer.@cssprop[--ninja-actions-height=300px] - Maximum height of the list.@cssprop[--ninja-footer-background=rgba(242, 242, 242, 0.4)] - The footer.
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.

@paramcallbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.@paramthisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
map
((title: stringtitle) => ({
id: stringid: title: stringtitle, title: stringtitle, keywords: stringkeywords: title: stringtitle.String.includes(searchString: string, position?: number): boolean

Returns 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.

@paramsearchString search string@paramposition If position is undefined, 0 is assumed, so as to search all of the String.
includes
('clipboard') ? 'pasteboard' : '',
handler: () => voidhandler: () => report: (message: string) => voidreport(`Ran "${title: stringtitle}"`), })); ninja: NinjaKeysninja.NinjaKeys.searcher: Searcher

Decides 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: NinjaSelectedDetail

The read-only detail property of the CustomEvent interface returns any data passed when initializing the event.

MDN Reference

detail
}) => {
if (!detail: NinjaSelectedDetail

The read-only detail property of the CustomEvent interface returns any data passed when initializing the event.

MDN Reference

detail
.NinjaSelectedDetail.action: INinjaAction | undefined

The chosen action, or undefined when Enter was pressed on no match.

action
) report: (message: string) => voidreport(`Web search for "${detail: NinjaSelectedDetail

The read-only detail property of the CustomEvent interface returns any data passed when initializing the event.

MDN Reference

detail
.NinjaSelectedDetail.search: string

The 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 selected listener does it: selected fires 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.