Page-driven palette
The palette as part of a page’s own UI rather than a hidden shortcut. The box below is an ordinary <input> on the page: typing in it opens the palette with what you typed, so no key is lost. The second button runs the best match for rep without showing a choice. Every event the element fires is reported under the buttons.
// The page drives the palette: a search box on the page opens it with
// what was typed, a button runs the first match with submit(), and the
// four events report what happened.
import '@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} from '@appulsauce/ninja-keys';
export default function function setup(ninja: NinjaKeys, report: (message: string) => void, page: HTMLElement): 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,
page: HTMLElementpage: HTMLElement
): void {
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 = ['Invoices', 'Customers', 'Products', 'Reports', 'Settings'].Array<string>.map<INinjaAction>(callbackfn: (value: string, index: number, array: string[]) => INinjaAction, thisArg?: any): INinjaAction[]Calls a defined callback function on each element of an array, and returns an array that contains the results.
map(
(title: stringtitle): INinjaAction => ({
INinjaAction.id: stringUnique across all actions. Child actions name their menu by it in
parent, and the breadcrumbs show it while that menu is open.
id: title: stringtitle,
INinjaAction.title: stringThe text shown in the list, and searched.
title: `Go to ${title: stringtitle}`,
INinjaAction.keywords?: stringMore words to match, separated by spaces; not shown.
keywords: title: stringtitle.String.toLowerCase(): stringConverts all the alphabetic characters in a string to lowercase.
toLowerCase(),
INinjaAction.handler?: (action: INinjaAction) => {
keepOpen?: boolean;
} | void
Runs when the action is chosen, by Enter, a click or its hotkey. The
palette closes afterwards unless it returns {keepOpen: true}.
handler: () => report: (message: string) => voidreport(`Navigated to ${title: stringtitle}`),
})
);
const const input: HTMLInputElement | nullinput = page: HTMLElementpage.ParentNode.querySelector<HTMLInputElement>(selectors: string): HTMLInputElement | null (+4 overloads)Returns the first element that is a descendant of node that matches selectors.
querySelector<HTMLInputElement>('input[name="jump"]');
const const lucky: HTMLButtonElement | nulllucky = page: HTMLElementpage.ParentNode.querySelector<HTMLButtonElement>(selectors: string): HTMLButtonElement | null (+4 overloads)Returns the first element that is a descendant of node that matches selectors.
querySelector<HTMLButtonElement>('button[name="lucky"]');
if (!const input: HTMLInputElement | nullinput || !const lucky: HTMLButtonElement | nulllucky) return;
// Typing in the page's box hands the text over to the palette, so the
// first key is not lost while the palette opens.
const input: HTMLInputElementinput.HTMLInputElement.addEventListener<"input">(type: "input", listener: (this: HTMLInputElement, ev: InputEvent) => any, options?: boolean | AddEventListenerOptions): void (+1 overload)The addEventListener() method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target.
addEventListener('input', () => {
ninja: NinjaKeysninja.NinjaKeys.open(options?: {
parent?: string;
search?: string;
} | undefined): void
Show a modal.
search starts the search box with that text, as if typed: a host that
opens the palette on a key press can pass on what the user typed while
it was opening, instead of dropping it or letting it reach the page.
open({search?: stringsearch: const input: HTMLInputElementinput.HTMLInputElement.value: stringThe value property of the HTMLInputElement interface represents the current value of the element as a string.
value});
const input: HTMLInputElementinput.HTMLInputElement.value: stringThe value property of the HTMLInputElement interface represents the current value of the element as a string.
value = '';
});
// open({search}) then submit() runs the first match, as Enter would.
const lucky: HTMLButtonElementlucky.HTMLButtonElement.addEventListener<"click">(type: "click", listener: (this: HTMLButtonElement, ev: PointerEvent) => any, options?: boolean | AddEventListenerOptions): void (+1 overload)The addEventListener() method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target.
addEventListener('click', () => {
ninja: NinjaKeysninja.NinjaKeys.open(options?: {
parent?: string;
search?: string;
} | undefined): void
Show a modal.
search starts the search box with that text, as if typed: a host that
opens the palette on a key press can pass on what the user typed while
it was opening, instead of dropping it or letting it reach the page.
open({search?: stringsearch: 'rep'});
void ninja: NinjaKeysninja.NinjaKeys.submit(): Promise<void>Run the selected action, as Enter does: after open({search}), the
first match. Does nothing while closed or when nothing matches.
Resolves once the action has run.
submit();
});
ninja: NinjaKeysninja.NinjaKeys.addEventListener<"open">(type: "open", listener: (this: NinjaKeys, event: CustomEvent<null>) => unknown, options?: boolean | AddEventListenerOptions): void (+2 overloads)addEventListener('open', () => report: (message: string) => voidreport('event: open'));
ninja: NinjaKeysninja.NinjaKeys.addEventListener<"close">(type: "close", listener: (this: NinjaKeys, event: CustomEvent<null>) => unknown, options?: boolean | AddEventListenerOptions): void (+2 overloads)addEventListener('close', () => {
report: (message: string) => voidreport('event: close');
const input: HTMLInputElementinput.HTMLOrSVGElement.focus(options?: FocusOptions): voidfocus();
});
// The events are typed: `event.detail` needs no cast.
ninja: NinjaKeysninja.NinjaKeys.addEventListener<"change">(type: "change", listener: (this: NinjaKeys, event: CustomEvent<NinjaChangeDetail>) => unknown, options?: boolean | AddEventListenerOptions): void (+2 overloads)addEventListener('change', (event: CustomEvent<NinjaChangeDetail>event) => {
const {const search: stringThe search text.
search, const actions: readonly INinjaAction[]The actions now shown, in order.
actions} = event: CustomEvent<NinjaChangeDetail>event.CustomEvent<NinjaChangeDetail>.detail: NinjaChangeDetailThe read-only detail property of the CustomEvent interface returns any data passed when initializing the event.
detail;
report: (message: string) => voidreport(`event: change "${const search: stringThe search text.
search}", ${const actions: readonly INinjaAction[]The actions now shown, in order.
actions.ReadonlyArray<INinjaAction>.length: numberGets the length of the array. This is a number one higher than the highest element defined in an array.
length} shown`);
});
ninja: NinjaKeysninja.NinjaKeys.addEventListener<"selected">(type: "selected", listener: (this: NinjaKeys, event: CustomEvent<NinjaSelectedDetail>) => unknown, options?: boolean | AddEventListenerOptions): void (+2 overloads)addEventListener('selected', (event: CustomEvent<NinjaSelectedDetail>event) => {
const {const action: INinjaAction | undefinedThe chosen action, or undefined when Enter was pressed on no match.
action, const search: stringThe search text when the choice was made.
search} = event: CustomEvent<NinjaSelectedDetail>event.CustomEvent<NinjaSelectedDetail>.detail: NinjaSelectedDetailThe read-only detail property of the CustomEvent interface returns any data passed when initializing the event.
detail;
const const chosen: stringchosen = const action: INinjaAction | undefinedThe chosen action, or undefined when Enter was pressed on no match.
action ? const action: INinjaActionThe chosen action, or undefined when Enter was pressed on no match.
action.INinjaAction.id: stringUnique across all actions. Child actions name their menu by it in
parent, and the breadcrumbs show it while that menu is open.
id : `nothing for "${const search: stringThe search text when the choice was made.
search}"`;
report: (message: string) => voidreport(`event: selected ${const chosen: stringchosen}`);
});
}When this is useful
- A search box in a header that should behave like the palette, without building a second search: hand its text to
open({search}). - Deep links that run a command: read
?run=...from the URL and callopen({search})thensubmit(). - Restoring focus: the
closehandler puts focus back in the page’s box, so the keyboard user lands where they started. - Server search on no match:
selectedfires with no action when Enter is pressed on an empty list, with the search text indetail.
Opening and events covers each method and event.