Opening and events

The palette can be driven from the page as well as from the keyboard: four methods open, close and run it, and four events say what happened. The page-driven example uses all of them.

Methods

const 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
(); // at the top level
const 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
({parent?: stringparent: 'Theme'}); // inside the Theme menu
const 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: 'exp'}); // with "exp" already typed
await const 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
(); // run the selected action, as Enter does
const ninja: NinjaKeysninja.NinjaKeys.setParent(parent?: string): void

Navigate to group of actions

@paramparent id of parent group/action
setParent
('Theme'); // move to a menu while open
const ninja: NinjaKeysninja.NinjaKeys.close(): void

Close modal

close
();

open({search}) starts the search box with that text and searches it, as if it had been typed (without a change event: nothing was typed). It is for a page that opens the palette on a key press: pass on what the user typed while it was opening, instead of dropping it or letting it land in the page.

// Any printable key on the page opens the palette with that key typed.
var document: Document

window.document returns a reference to the document contained in the window.

MDN Reference

document
.Document.addEventListener<"keydown">(type: "keydown", listener: (this: Document, ev: KeyboardEvent) => 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.

MDN Reference

addEventListener
('keydown', (event: KeyboardEventevent) => {
const const typing: booleantyping = event: KeyboardEventevent.Event.target: EventTarget | null

The read-only target property of the Event interface is a reference to the object onto which the event was dispatched. It is different from Event.currentTarget when the event handler is called during the bubbling or capturing phase of the event.

MDN Reference

target
instanceof
var HTMLInputElement: {
    new (): HTMLInputElement;
    prototype: HTMLInputElement;
}

The HTMLInputElement interface provides special properties and methods for manipulating the options, layout, and presentation of elements.

MDN Reference

HTMLInputElement
;
if (const typing: booleantyping || event: KeyboardEventevent.KeyboardEvent.key: string

The KeyboardEvent interface's key read-only property returns the value of the key pressed by the user, taking into consideration the state of modifier keys such as Shift as well as the keyboard locale and layout.

MDN Reference

key
.String.length: number

Returns the length of a String object.

length
!== 1 || event: KeyboardEventevent.KeyboardEvent.ctrlKey: boolean

The KeyboardEvent.ctrlKey read-only property returns a boolean value that indicates if the control key was pressed (true) or not (false) when the event occurred.

MDN Reference

ctrlKey
|| event: KeyboardEventevent.KeyboardEvent.metaKey: boolean

The KeyboardEvent.metaKey read-only property returning a boolean value that indicates if the Meta key was pressed (true) or not (false) when the event occurred. Some operating systems may intercept the key so it is never detected.

MDN Reference

metaKey
)
return; event: KeyboardEventevent.Event.preventDefault(): void

The preventDefault() method of the Event interface tells the user agent that the event is being explicitly handled, so its default action, such as page scrolling, link navigation, or pasting text, should not be taken.

MDN Reference

preventDefault
();
const 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: event: KeyboardEventevent.KeyboardEvent.key: string

The KeyboardEvent interface's key read-only property returns the value of the key pressed by the user, taking into consideration the state of modifier keys such as Shift as well as the keyboard locale and layout.

MDN Reference

key
});
});

Running an action from code

submit() does what Enter does: runs the selected action, or opens its menu. After open({search}) the selected action is the first match, so the two together run “the best match for this text”, like a browser’s I’m-feeling-lucky. With the palette closed, or nothing matching, submit() does nothing. It waits for the element to apply a search set just before it, and its promise resolves once the action has run.

const const params: URLSearchParamsparams = new var URLSearchParams: new (init?: string[][] | Record<string, string> | string | URLSearchParams) => URLSearchParams

The URLSearchParams interface defines utility methods to work with the query string of a URL.

MDN Reference

URLSearchParams
(var location: Location

The read-only location property of the Window interface returns a Location object with information about the current location of the document.

MDN Reference

location
.Location.search: string

The search property of the Location interface is a search string, also called a query string, that is a string containing a "?" followed by the parameters of the location's URL. If the URL does not have a search query, this property contains an empty string, "".

MDN Reference

search
);
const const command: string | nullcommand = const params: URLSearchParamsparams.URLSearchParams.get(name: string): string | null

The get() method of the URLSearchParams interface returns the first value associated to the given search parameter.

MDN Reference

get
('run');
if (const command: string | nullcommand) { const 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 command: stringcommand});
await const 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
();
}

Events

EventWhendetail
changethe search text changesNinjaChangeDetail: search, and the actions now shown
selectedan action is chosen, or Enter is pressed with nothing to chooseNinjaSelectedDetail: search, and the action or undefined
openthe palette becomes visible, however it was openednull
closethe palette is hidden, however it was closednull

All four bubble and cross the shadow boundary (composed), so a listener on a parent element or the document hears them too.

The events are typed. addEventListener on a NinjaKeys knows each event’s detail, so listeners need no cast:

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

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

action
, const search: string

The search text when the choice was made.

search
} = event: CustomEvent<NinjaSelectedDetail>event.CustomEvent<NinjaSelectedDetail>.detail: NinjaSelectedDetail

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

MDN Reference

detail
;
if (!const action: INinjaAction | undefined

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

action
) {
// Enter on no match: hand the text to a server search. void function fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>fetch(`/api/search?q=${function encodeURIComponent(uriComponent: string | number | boolean): string

Encodes a text string as a valid component of a Uniform Resource Identifier (URI).

@paramuriComponent A value representing an unencoded URI component.
encodeURIComponent
(const search: string

The search text when the choice was made.

search
)}`);
} });

selected or handler?

Both run when an action is chosen. Put an action’s own behaviour in its handler; that keeps it next to the action and runs from its hotkey too (selected does not fire for a hotkey). Use selected for what is common to every choice, such as analytics, and for the case handler cannot see: Enter with no match.

open and close

They fire once per change of visibility, whatever caused it: a method call, the open key, Escape, a click on the overlay, or an action that closed it. Use them to restore focus to where it was, pause something behind the palette, or track usage:

let let returnTo: Element | nullreturnTo: Element | null = null;
const ninja: NinjaKeysninja.NinjaKeys.addEventListener<"open">(type: "open", listener: (this: NinjaKeys, event: CustomEvent<null>) => unknown, options?: boolean | AddEventListenerOptions): void (+2 overloads)addEventListener('open', () => {
  let returnTo: Element | nullreturnTo = var document: Document

window.document returns a reference to the document contained in the window.

MDN Reference

document
.DocumentOrShadowRoot.activeElement: Element | null

Returns the deepest element in the document through which or to which key events are being routed. This is, roughly speaking, the focused element in the document.

For the purposes of this API, when a child browsing context is focused, its container is focused in the parent browsing context. For example, if the user moves the focus to a text control in an iframe, the iframe is the element returned by the activeElement API in the iframe's node document.

Similarly, when the focused element is in a different node tree than documentOrShadowRoot, the element returned will be the host that's located in the same node tree as documentOrShadowRoot if documentOrShadowRoot is a shadow-including inclusive ancestor of the focused element, and null if not.

MDN Reference

activeElement
;
}); const ninja: NinjaKeysninja.NinjaKeys.addEventListener<"close">(type: "close", listener: (this: NinjaKeys, event: CustomEvent<null>) => unknown, options?: boolean | AddEventListenerOptions): void (+2 overloads)addEventListener('close', () => { if (let returnTo: Element | nullreturnTo instanceof
var HTMLElement: {
    new (): HTMLElement;
    prototype: HTMLElement;
}

The HTMLElement interface represents any HTML element. Some elements directly implement this interface, while others implement it via an interface that inherits it.

MDN Reference

HTMLElement
) let returnTo: HTMLElementreturnTo.HTMLOrSVGElement.focus(options?: FocusOptions): voidfocus();
});

visible tells whether the palette is open right now.