// What a click on something that opens opens, and how it is drawn: a link // to its address (`href`) where the app gives one, so a page drawn on a // server opens it before the code arrives and a person can open it in a // new tab; else a button. Either way an ordinary click opens it through // the app. /** What a click opens (`run`), what to call it for a screen reader, and its address, where the app gives one. */ export type Opener = { run: () => void; label: string; href?: string }; /** A link's click: `run`, in place of following it, unless the browser is * to follow it itself (one handled already, with another button, or with a * key held: a new tab, a new window, a download); `stop` keeps it from what * holds the link either way. */ export function clickOpen(run: () => void, stop = false): (event: MouseEvent) => void { return (event) => { if (stop) event.stopPropagation(); if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return; event.preventDefault(); run(); }; } /** The element that draws `open`: a link where it has an address, else a button. */ export const tagOf = (open: Opener): 'a' | 'button' => (open.href === undefined ? 'button' : 'a'); /** The attributes of the element `tagOf` names for `open`: its address and a link's click, or a button's type and click; `stop` keeps the click from what holds it. */ export function opens(open: Opener, stop = false): { href?: string; type?: 'button'; onclick: (event: MouseEvent) => void } { if (open.href !== undefined) return { href: open.href, onclick: clickOpen(open.run, stop) }; const run = open.run; return { type: 'button', onclick: stop ? (event) => { event.stopPropagation(); run(); } : run }; }