@underpin/ui 0.0.0 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +44 -1
- package/components/autocomplete.d.ts +25 -0
- package/components/autocomplete.js +71 -0
- package/components/autocomplete.js.map +1 -0
- package/components/avatar.d.ts +5 -0
- package/components/avatar.js +26 -0
- package/components/avatar.js.map +1 -0
- package/components/badge.d.ts +36 -0
- package/components/badge.js +140 -0
- package/components/badge.js.map +1 -0
- package/components/bar-list.d.ts +133 -0
- package/components/bar-list.js +204 -0
- package/components/bar-list.js.map +1 -0
- package/components/breakdown-card.d.ts +30 -0
- package/components/breakdown-card.js +43 -0
- package/components/breakdown-card.js.map +1 -0
- package/components/bulk-action-bar.d.ts +21 -0
- package/components/bulk-action-bar.js +38 -0
- package/components/bulk-action-bar.js.map +1 -0
- package/components/button-group.d.ts +21 -0
- package/components/button-group.js +32 -0
- package/components/button-group.js.map +1 -0
- package/components/button.d.ts +39 -0
- package/components/button.js +145 -0
- package/components/button.js.map +1 -0
- package/components/calendar.d.ts +27 -0
- package/components/calendar.js +95 -0
- package/components/calendar.js.map +1 -0
- package/components/callout.d.ts +26 -0
- package/components/callout.js +71 -0
- package/components/callout.js.map +1 -0
- package/components/card.d.ts +55 -0
- package/components/card.js +96 -0
- package/components/card.js.map +1 -0
- package/components/chart.d.ts +32 -0
- package/components/chart.js +43 -0
- package/components/chart.js.map +1 -0
- package/components/checkbox.d.ts +15 -0
- package/components/checkbox.js +42 -0
- package/components/checkbox.js.map +1 -0
- package/components/code-block.d.ts +21 -0
- package/components/code-block.js +35 -0
- package/components/code-block.js.map +1 -0
- package/components/collapse.d.ts +14 -0
- package/components/collapse.js +25 -0
- package/components/collapse.js.map +1 -0
- package/components/combobox.d.ts +71 -0
- package/components/combobox.js +155 -0
- package/components/combobox.js.map +1 -0
- package/components/copy-button.d.ts +29 -0
- package/components/copy-button.js +100 -0
- package/components/copy-button.js.map +1 -0
- package/components/copy-input.d.ts +15 -0
- package/components/copy-input.js +51 -0
- package/components/copy-input.js.map +1 -0
- package/components/data-table.d.ts +120 -0
- package/components/data-table.js +336 -0
- package/components/data-table.js.map +1 -0
- package/components/date-picker-trigger.d.ts +12 -0
- package/components/date-picker-trigger.js +30 -0
- package/components/date-picker-trigger.js.map +1 -0
- package/components/date-picker.d.ts +36 -0
- package/components/date-picker.js +70 -0
- package/components/date-picker.js.map +1 -0
- package/components/detail-row.d.ts +51 -0
- package/components/detail-row.js +77 -0
- package/components/detail-row.js.map +1 -0
- package/components/dialog.d.ts +121 -0
- package/components/dialog.js +327 -0
- package/components/dialog.js.map +1 -0
- package/components/disabled-reason.d.ts +31 -0
- package/components/disabled-reason.js +67 -0
- package/components/disabled-reason.js.map +1 -0
- package/components/empty-state.d.ts +41 -0
- package/components/empty-state.js +84 -0
- package/components/empty-state.js.map +1 -0
- package/components/entity-avatar.d.ts +54 -0
- package/components/entity-avatar.js +68 -0
- package/components/entity-avatar.js.map +1 -0
- package/components/form-section.d.ts +22 -0
- package/components/form-section.js +38 -0
- package/components/form-section.js.map +1 -0
- package/components/form.d.ts +199 -0
- package/components/form.js +456 -0
- package/components/form.js.map +1 -0
- package/components/formatted-number.d.ts +21 -0
- package/components/formatted-number.js +13 -0
- package/components/formatted-number.js.map +1 -0
- package/components/heading.d.ts +23 -0
- package/components/heading.js +44 -0
- package/components/heading.js.map +1 -0
- package/components/icon-swap.d.ts +15 -0
- package/components/icon-swap.js +29 -0
- package/components/icon-swap.js.map +1 -0
- package/components/inline-action.d.ts +21 -0
- package/components/inline-action.js +36 -0
- package/components/inline-action.js.map +1 -0
- package/components/input.d.ts +51 -0
- package/components/input.js +52 -0
- package/components/input.js.map +1 -0
- package/components/kbd.d.ts +17 -0
- package/components/kbd.js +34 -0
- package/components/kbd.js.map +1 -0
- package/components/label.d.ts +10 -0
- package/components/label.js +20 -0
- package/components/label.js.map +1 -0
- package/components/menu.d.ts +77 -0
- package/components/menu.js +189 -0
- package/components/menu.js.map +1 -0
- package/components/nav-button.d.ts +34 -0
- package/components/nav-button.js +71 -0
- package/components/nav-button.js.map +1 -0
- package/components/nav.d.ts +39 -0
- package/components/nav.js +68 -0
- package/components/nav.js.map +1 -0
- package/components/number-input.d.ts +16 -0
- package/components/number-input.js +25 -0
- package/components/number-input.js.map +1 -0
- package/components/page.d.ts +14 -0
- package/components/page.js +23 -0
- package/components/page.js.map +1 -0
- package/components/pagination.d.ts +73 -0
- package/components/pagination.js +212 -0
- package/components/pagination.js.map +1 -0
- package/components/ping.d.ts +38 -0
- package/components/ping.js +50 -0
- package/components/ping.js.map +1 -0
- package/components/popover.d.ts +5 -0
- package/components/popover.js +25 -0
- package/components/popover.js.map +1 -0
- package/components/radio-group.d.ts +35 -0
- package/components/radio-group.js +81 -0
- package/components/radio-group.js.map +1 -0
- package/components/relative-time.d.ts +25 -0
- package/components/relative-time.js +51 -0
- package/components/relative-time.js.map +1 -0
- package/components/saved-mark.d.ts +15 -0
- package/components/saved-mark.js +45 -0
- package/components/saved-mark.js.map +1 -0
- package/components/search-input.d.ts +13 -0
- package/components/search-input.js +44 -0
- package/components/search-input.js.map +1 -0
- package/components/section-header.d.ts +83 -0
- package/components/section-header.js +170 -0
- package/components/section-header.js.map +1 -0
- package/components/segmented-control.d.ts +24 -0
- package/components/segmented-control.js +70 -0
- package/components/segmented-control.js.map +1 -0
- package/components/select.d.ts +28 -0
- package/components/select.js +129 -0
- package/components/select.js.map +1 -0
- package/components/shortcut-keys.d.ts +14 -0
- package/components/shortcut-keys.js +32 -0
- package/components/shortcut-keys.js.map +1 -0
- package/components/shortcuts-dialog.d.ts +10 -0
- package/components/shortcuts-dialog.js +92 -0
- package/components/shortcuts-dialog.js.map +1 -0
- package/components/skeleton.d.ts +8 -0
- package/components/skeleton.js +23 -0
- package/components/skeleton.js.map +1 -0
- package/components/sparkline.d.ts +25 -0
- package/components/sparkline.js +70 -0
- package/components/sparkline.js.map +1 -0
- package/components/stack.d.ts +21 -0
- package/components/stack.js +45 -0
- package/components/stack.js.map +1 -0
- package/components/stat-strip.d.ts +43 -0
- package/components/stat-strip.js +151 -0
- package/components/stat-strip.js.map +1 -0
- package/components/steps.d.ts +19 -0
- package/components/steps.js +25 -0
- package/components/steps.js.map +1 -0
- package/components/switch.d.ts +16 -0
- package/components/switch.js +29 -0
- package/components/switch.js.map +1 -0
- package/components/table-toolbar.d.ts +55 -0
- package/components/table-toolbar.js +119 -0
- package/components/table-toolbar.js.map +1 -0
- package/components/table.d.ts +276 -0
- package/components/table.js +572 -0
- package/components/table.js.map +1 -0
- package/components/tabs.d.ts +36 -0
- package/components/tabs.js +120 -0
- package/components/tabs.js.map +1 -0
- package/components/text-link.d.ts +16 -0
- package/components/text-link.js +32 -0
- package/components/text-link.js.map +1 -0
- package/components/textarea.d.ts +10 -0
- package/components/textarea.js +23 -0
- package/components/textarea.js.map +1 -0
- package/components/theme.d.ts +28 -0
- package/components/theme.js +158 -0
- package/components/theme.js.map +1 -0
- package/components/time-series-chart.d.ts +122 -0
- package/components/time-series-chart.js +722 -0
- package/components/time-series-chart.js.map +1 -0
- package/components/toaster.d.ts +3 -0
- package/components/toaster.js +44 -0
- package/components/toaster.js.map +1 -0
- package/components/tooltip.d.ts +64 -0
- package/components/tooltip.js +126 -0
- package/components/tooltip.js.map +1 -0
- package/components/view-picker.d.ts +20 -0
- package/components/view-picker.js +24 -0
- package/components/view-picker.js.map +1 -0
- package/fonts/inter-OFL.txt +93 -0
- package/fonts/inter-cyrillic-ext.woff2 +0 -0
- package/fonts/inter-cyrillic.woff2 +0 -0
- package/fonts/inter-greek-ext.woff2 +0 -0
- package/fonts/inter-greek.woff2 +0 -0
- package/fonts/inter-latin-ext.woff2 +0 -0
- package/fonts/inter-latin.woff2 +0 -0
- package/fonts/inter-vietnamese.woff2 +0 -0
- package/fonts.css +83 -0
- package/lib/animation.d.ts +14 -0
- package/lib/animation.js +20 -0
- package/lib/animation.js.map +1 -0
- package/lib/aria.d.ts +5 -0
- package/lib/aria.js +12 -0
- package/lib/aria.js.map +1 -0
- package/lib/chart-curve.d.ts +13 -0
- package/lib/chart-curve.js +79 -0
- package/lib/chart-curve.js.map +1 -0
- package/lib/classes.d.ts +134 -0
- package/lib/classes.js +152 -0
- package/lib/classes.js.map +1 -0
- package/lib/color.d.ts +25 -0
- package/lib/color.js +149 -0
- package/lib/color.js.map +1 -0
- package/lib/data-table-state.d.ts +87 -0
- package/lib/data-table-state.js +92 -0
- package/lib/data-table-state.js.map +1 -0
- package/lib/day.d.ts +9 -0
- package/lib/day.js +20 -0
- package/lib/day.js.map +1 -0
- package/lib/design-tokens.d.ts +56 -0
- package/lib/design-tokens.js +196 -0
- package/lib/design-tokens.js.map +1 -0
- package/lib/icon.d.ts +17 -0
- package/lib/icon.js +34 -0
- package/lib/icon.js.map +1 -0
- package/lib/icons.d.ts +29 -0
- package/lib/icons.js +34 -0
- package/lib/icons.js.map +1 -0
- package/lib/interactive.d.ts +21 -0
- package/lib/interactive.js +31 -0
- package/lib/interactive.js.map +1 -0
- package/lib/load-more.d.ts +14 -0
- package/lib/load-more.js +27 -0
- package/lib/load-more.js.map +1 -0
- package/lib/media.d.ts +58 -0
- package/lib/media.js +116 -0
- package/lib/media.js.map +1 -0
- package/lib/segmented.d.ts +57 -0
- package/lib/segmented.js +83 -0
- package/lib/segmented.js.map +1 -0
- package/lib/shortcuts.d.ts +94 -0
- package/lib/shortcuts.js +271 -0
- package/lib/shortcuts.js.map +1 -0
- package/lib/slot.d.ts +9 -0
- package/lib/slot.js +18 -0
- package/lib/slot.js.map +1 -0
- package/lib/time-series.d.ts +100 -0
- package/lib/time-series.js +144 -0
- package/lib/time-series.js.map +1 -0
- package/lib/tone.d.ts +6 -0
- package/lib/tone.js +0 -0
- package/lib/variants.d.ts +12 -0
- package/lib/variants.js +14 -0
- package/lib/variants.js.map +1 -0
- package/package.json +122 -3
- package/styles.css +630 -0
- package/tokens.d.ts +104 -0
- package/tokens.js +108 -0
- package/tokens.js.map +1 -0
- package/publish.log +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"segmented.js","names":[],"sources":["../../src/lib/segmented.ts"],"sourcesContent":["import { type RefObject, useLayoutEffect, useRef } from \"react\"\nimport { interactiveVariants } from \"./interactive\"\nimport { cn, variants, type VariantProps } from \"./variants\"\n\n/** The variant and size a row hands its options, with the defaults filled in. */\nexport interface SegmentedStyle {\n variant: NonNullable<VariantProps<typeof segmentedVariants>[\"variant\"]>\n size: NonNullable<VariantProps<typeof segmentedVariants>[\"size\"]>\n}\n\n/**\n * The row of options with one sliding pill behind the chosen one, shared by `Tabs` and\n * `SegmentedControl`. Each component positions the pill from its own measurements and adds the\n * state classes its primitive emits (`data-active` on a tab, `data-checked` on a radio), so\n * the slots here hold only the shape.\n */\nexport const segmentedVariants = variants({\n slots: {\n root: \"relative inline-flex items-center text-ink-muted\",\n // Positioned from the root's top-left corner rather than centred on it, so a row that\n // wraps onto a second line moves the pill down to the chosen option's line as well as\n // across. 200ms on the `--ease-out-expo` curve: a pill still travelling when the new\n // content lands reads as lag.\n indicator:\n \"absolute top-0 left-0 z-0 rounded-md transition-[translate,width,height] duration-200 ease-out-expo\",\n item: cn(\n interactiveVariants({ interactive: false }),\n \"relative z-10 inline-flex items-center justify-center whitespace-nowrap font-medium\",\n // Hover and press darken the label only. The pill alone marks the chosen option, so a\n // fill under the pointer would read as a second pill beside it while the first one slides.\n \"hover:text-ink active:text-ink\",\n // A finger's 40px target, centred on the option and spilling into the row above and\n // below rather than growing the option: a `min-height` here would stretch the pill, and\n // with it the card header the row sits in. Check it on a real phone: a desktop\n // browser's mobile emulation does not match `pointer: coarse`.\n \"pointer-coarse:before:absolute pointer-coarse:before:inset-x-0 pointer-coarse:before:top-1/2 pointer-coarse:before:h-10 pointer-coarse:before:-translate-y-1/2\",\n ),\n },\n\n variants: {\n variant: {\n // The chosen option is a raised key as tall as the track, which is a well with no edge of\n // its own, so the two read as one control, the way a switch's thumb meets its track. No\n // inset and no gap between options.\n segmented: {\n root: \"rounded-md bg-well shadow-well\",\n indicator: \"rounded-md border border-edge-strong bg-surface shadow-control\",\n },\n // The same box with nothing drawn around it: no track and no edge, the chosen option on\n // the fill. A plain row is as tall as a segmented one of its size, so its labels line\n // up with any control beside it. For in-card view switchers.\n plain: {\n root: \"gap-0.5\",\n indicator: \"rounded-md bg-fill\",\n },\n },\n // The control scale, on the options rather than the row, so a row that wraps grows by\n // whole lines and a row that pads itself keeps its options' height: md is 32px and sm 28px,\n // for a card header, both with 13px labels like every control of their size; xs is 24px\n // with 12px labels, for a control inside a menu row.\n size: {\n md: { item: \"h-control rounded-md px-2.5 text-control\" },\n sm: { item: \"h-7 rounded-md px-2 text-control\" },\n xs: { root: \"rounded\", indicator: \"rounded\", item: \"h-6 rounded px-1.5 text-xs\" },\n },\n // An option that is only an icon: a square of the option's height, the icon 14px, or 12px\n // in an xs row. `SegmentedControlItem` sets it for an option labelled by `aria-label` alone.\n icon: {\n true: { item: \"aspect-square px-0 [&_svg]:size-3.5\" },\n },\n },\n\n compoundVariants: [{ size: \"xs\", icon: true, class: { item: \"[&_svg]:size-3\" } }],\n\n defaultVariants: {\n variant: \"segmented\",\n size: \"md\",\n },\n})\n\n/** The pill's box, read from what `useSegmentedIndicator` wrote, hidden until it is measured. */\nexport const SEGMENTED_INDICATOR_BOX =\n \"hidden h-(--indicator-height) w-(--indicator-width) translate-x-(--indicator-left) translate-y-(--indicator-top) in-data-measured:block\"\n\n/** A segmented row's raised key on the checked option itself, until the pill has a box to take. */\nexport const SEGMENTED_UNMEASURED_KEY =\n \"[&:not([data-measured])_[data-checked]]:bg-surface [&:not([data-measured])_[data-checked]]:shadow-control [&:not([data-measured])_[data-checked]]:outline [&:not([data-measured])_[data-checked]]:-outline-offset-1 [&:not([data-measured])_[data-checked]]:outline-edge-strong\"\n\n/** Writes the checked option's box onto the row, where the pill reads it. */\nfunction measure(root: HTMLElement) {\n const checked = root.querySelector<HTMLElement>(\n '[role=\"radio\"][data-checked], [role=\"menuitemradio\"][data-checked]',\n )\n\n root.style.setProperty(\"--indicator-left\", `${checked?.offsetLeft ?? 0}px`)\n root.style.setProperty(\"--indicator-top\", `${checked?.offsetTop ?? 0}px`)\n root.style.setProperty(\"--indicator-width\", `${checked?.offsetWidth ?? 0}px`)\n root.style.setProperty(\"--indicator-height\", `${checked?.offsetHeight ?? 0}px`)\n root.dataset.measured = \"\"\n}\n\n/**\n * Keeps a row's pill on its checked option: measures again when `value` changes and when the\n * row resizes, as a label that wraps, a font that loads, or an option added later moves the\n * checked one. The returned ref goes on the row.\n */\nexport function useSegmentedIndicator(value: unknown): RefObject<HTMLDivElement | null> {\n const ref = useRef<HTMLDivElement>(null)\n\n useLayoutEffect(() => {\n if (ref.current) measure(ref.current)\n }, [value])\n\n useLayoutEffect(() => {\n const root = ref.current\n if (!root) return\n\n const observer = new ResizeObserver(() => measure(root))\n observer.observe(root)\n\n return () => observer.disconnect()\n }, [])\n\n return ref\n}\n"],"mappings":";;;;;;;;;;AAgBA,MAAa,oBAAoB,SAAS;CACxC,OAAO;EACL,MAAM;EAKN,WACE;EACF,MAAM,GACJ,oBAAoB,EAAE,aAAa,MAAM,CAAC,GAC1C,uFAGA,kCAKA,gKACF;CACF;CAEA,UAAU;EACR,SAAS;GAIP,WAAW;IACT,MAAM;IACN,WAAW;GACb;GAIA,OAAO;IACL,MAAM;IACN,WAAW;GACb;EACF;EAKA,MAAM;GACJ,IAAI,EAAE,MAAM,2CAA2C;GACvD,IAAI,EAAE,MAAM,mCAAmC;GAC/C,IAAI;IAAE,MAAM;IAAW,WAAW;IAAW,MAAM;GAA6B;EAClF;EAGA,MAAM,EACJ,MAAM,EAAE,MAAM,sCAAsC,EACtD;CACF;CAEA,kBAAkB,CAAC;EAAE,MAAM;EAAM,MAAM;EAAM,OAAO,EAAE,MAAM,iBAAiB;CAAE,CAAC;CAEhF,iBAAiB;EACf,SAAS;EACT,MAAM;CACR;AACF,CAAC;;AAGD,MAAa,0BACX;;AAGF,MAAa,2BACX;;AAGF,SAAS,QAAQ,MAAmB;CAClC,MAAM,UAAU,KAAK,cACnB,wEACF;CAEA,KAAK,MAAM,YAAY,oBAAoB,GAAG,SAAS,cAAc,EAAE,GAAG;CAC1E,KAAK,MAAM,YAAY,mBAAmB,GAAG,SAAS,aAAa,EAAE,GAAG;CACxE,KAAK,MAAM,YAAY,qBAAqB,GAAG,SAAS,eAAe,EAAE,GAAG;CAC5E,KAAK,MAAM,YAAY,sBAAsB,GAAG,SAAS,gBAAgB,EAAE,GAAG;CAC9E,KAAK,QAAQ,WAAW;AAC1B;;;;;;AAOA,SAAgB,sBAAsB,OAAkD;CACtF,MAAM,MAAM,OAAuB,IAAI;CAEvC,sBAAsB;EACpB,IAAI,IAAI,SAAS,QAAQ,IAAI,OAAO;CACtC,GAAG,CAAC,KAAK,CAAC;CAEV,sBAAsB;EACpB,MAAM,OAAO,IAAI;EACjB,IAAI,CAAC,MAAM;EAEX,MAAM,WAAW,IAAI,qBAAqB,QAAQ,IAAI,CAAC;EACvD,SAAS,QAAQ,IAAI;EAErB,aAAa,SAAS,WAAW;CACnC,GAAG,CAAC,CAAC;CAEL,OAAO;AACT"}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
export interface Shortcut {
|
|
2
|
+
/**
|
|
3
|
+
* react-hotkeys-hook key string: `d`, `mod+k`, `shift+?`, `left`. Matched on the character the
|
|
4
|
+
* key produces, so a letter is the key labelled with it on any layout.
|
|
5
|
+
*/
|
|
6
|
+
keys: string;
|
|
7
|
+
/** Human label shown in the reference dialog, e.g. "Today". */
|
|
8
|
+
label: string;
|
|
9
|
+
/** Section in the reference dialog, e.g. "Date range". Sections appear in registration order. */
|
|
10
|
+
group: string;
|
|
11
|
+
handler: (event: KeyboardEvent) => void;
|
|
12
|
+
/** Default true. A disabled shortcut neither fires nor shows up in the reference dialog. */
|
|
13
|
+
enabled?: boolean;
|
|
14
|
+
/** Fire while typing in inputs, textareas, selects and contenteditable. Default false. */
|
|
15
|
+
enableOnFormTags?: boolean;
|
|
16
|
+
}
|
|
17
|
+
export interface ShortcutGroup {
|
|
18
|
+
group: string;
|
|
19
|
+
shortcuts: {
|
|
20
|
+
keys: string;
|
|
21
|
+
label: string;
|
|
22
|
+
}[];
|
|
23
|
+
}
|
|
24
|
+
/** What `findShortcutRow` reads off a key press: a DOM event or React's. */
|
|
25
|
+
export interface MenuKeyEvent {
|
|
26
|
+
key: string;
|
|
27
|
+
ctrlKey: boolean;
|
|
28
|
+
metaKey: boolean;
|
|
29
|
+
altKey: boolean;
|
|
30
|
+
target: EventTarget | null;
|
|
31
|
+
}
|
|
32
|
+
type Registration = Pick<Shortcut, "group" | "keys" | "label">;
|
|
33
|
+
/** Add rows to the registry and get back the call that removes them. `useShortcuts` is the way in. */
|
|
34
|
+
export declare function registerShortcuts(entries: Registration[]): () => void;
|
|
35
|
+
/** The current list outside React, for tests. */
|
|
36
|
+
export declare function getShortcutList(): ShortcutGroup[];
|
|
37
|
+
/** The shortcuts mounted right now, grouped, for the reference dialog. Empty on the server. */
|
|
38
|
+
export declare function useShortcutList(): ShortcutGroup[];
|
|
39
|
+
/**
|
|
40
|
+
* A key string as the library reports the hotkey it matched, lower-cased and trimmed, so two can
|
|
41
|
+
* be compared like for like. A shortcut badge names its key this way in `data-shortcut`.
|
|
42
|
+
*/
|
|
43
|
+
export declare function toHotkey(keys: string): string;
|
|
44
|
+
/**
|
|
45
|
+
* Whether a key typed over `target` belongs to the widget around it rather than to the page's
|
|
46
|
+
* shortcuts. Anything typed inside an open modal belongs to that modal, the shortcuts the modal
|
|
47
|
+
* registered itself included; that is the ceiling on one flat registry, and per-modal scopes
|
|
48
|
+
* (react-hotkeys-hook's HotkeysProvider) are what lifts it. A menu or a listbox reads letters as
|
|
49
|
+
* typeahead, so it keeps every key too, except the keys a menu prints: a row's badge picks that
|
|
50
|
+
* row (`findShortcutRow`), and a hint outside the rows stays the page's. Tabs, a grid and a
|
|
51
|
+
* radio group only step with the arrow keys, Home and End: stepping through a card's tabs must
|
|
52
|
+
* not also step the date range, but a letter typed after clicking a tab still reaches the page.
|
|
53
|
+
*/
|
|
54
|
+
export declare function isWidgetKey(target: Element | null, key: string): boolean;
|
|
55
|
+
/**
|
|
56
|
+
* The row of an open menu whose badge shows the key pressed, for the menu to pick as a click
|
|
57
|
+
* would. The letters printed beside the rows answer ahead of the menu's typeahead, which would
|
|
58
|
+
* jump to the first row starting with that letter instead. Only a single character counts, with
|
|
59
|
+
* no Ctrl, Cmd or Alt held (Shift may be, for a `?`). In a field in the menu, such as its search,
|
|
60
|
+
* a key counts only while the field is empty: the search takes focus as the menu opens, and the
|
|
61
|
+
* keys printed on its rows still work then, while a query once begun keeps every key it types.
|
|
62
|
+
*/
|
|
63
|
+
export declare function findShortcutRow(menu: Element, event: MenuKeyEvent): HTMLElement | undefined;
|
|
64
|
+
/**
|
|
65
|
+
* Register any number of shortcuts for as long as the component is mounted. One `useHotkeys` call
|
|
66
|
+
* carries them all, since the list may change length between renders, and the callback routes
|
|
67
|
+
* back to the right handler by the hotkey string the library matched.
|
|
68
|
+
*/
|
|
69
|
+
export declare function useShortcuts(shortcuts: Shortcut[]): void;
|
|
70
|
+
/** A single shortcut, for the common case. */
|
|
71
|
+
export declare function useShortcut(shortcut: Shortcut): void;
|
|
72
|
+
/**
|
|
73
|
+
* Deliberately the same rule react-hotkeys-hook applies internally to decide whether `mod`
|
|
74
|
+
* means Meta or Control. It does not export it, and it only ever runs on a keystroke, so it
|
|
75
|
+
* cannot be reused, but it is the authority on what `mod` actually matches. Detecting the
|
|
76
|
+
* platform some other way (navigator.platform, userAgentData) risks a badge that says ⌘ while
|
|
77
|
+
* the matcher is waiting for Ctrl, and the label would be lying about the shortcut.
|
|
78
|
+
*/
|
|
79
|
+
export declare function isMacUserAgent(userAgent: string): boolean;
|
|
80
|
+
/**
|
|
81
|
+
* Whether to spell shortcuts the Apple way. A hook rather than a module constant because this
|
|
82
|
+
* package renders under SSR: read at import time, the server produced "Ctrl" and the client
|
|
83
|
+
* hydrated "⌘", which is a hydration mismatch on every shortcut badge. Returning false as the
|
|
84
|
+
* server snapshot makes the first client render agree, then React re-renders with the truth.
|
|
85
|
+
*/
|
|
86
|
+
export declare function useIsMac(): boolean;
|
|
87
|
+
/** A key string as badge parts: the modifiers in Apple order, then the key. Platform injectable for tests. */
|
|
88
|
+
export declare function formatKeys(keys: string, mac?: boolean): string[];
|
|
89
|
+
/**
|
|
90
|
+
* A key string as a screen reader should say it ("Command K"): the badge's glyphs would be read
|
|
91
|
+
* by their Unicode names, "place of interest sign" for ⌘. Platform injectable for tests.
|
|
92
|
+
*/
|
|
93
|
+
export declare function formatSpokenKeys(keys: string, mac?: boolean): string;
|
|
94
|
+
export {};
|
package/lib/shortcuts.js
ADDED
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { useEffect, useRef, useSyncExternalStore } from "react";
|
|
3
|
+
import { useHotkeys } from "react-hotkeys-hook";
|
|
4
|
+
// src/lib/shortcuts.ts
|
|
5
|
+
const EMPTY = [];
|
|
6
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
7
|
+
let registrations = [];
|
|
8
|
+
let snapshot = EMPTY;
|
|
9
|
+
/** Rebuilt once per change, so `useSyncExternalStore` sees a referentially stable snapshot. */
|
|
10
|
+
function publish() {
|
|
11
|
+
const groups = /* @__PURE__ */ new Map();
|
|
12
|
+
const seen = /* @__PURE__ */ new Set();
|
|
13
|
+
for (const { group, keys, label } of registrations) {
|
|
14
|
+
const id = `${group}\t${keys}\t${label}`;
|
|
15
|
+
if (seen.has(id)) continue;
|
|
16
|
+
seen.add(id);
|
|
17
|
+
const existing = groups.get(group) ?? {
|
|
18
|
+
group,
|
|
19
|
+
shortcuts: []
|
|
20
|
+
};
|
|
21
|
+
existing.shortcuts.push({
|
|
22
|
+
keys,
|
|
23
|
+
label
|
|
24
|
+
});
|
|
25
|
+
groups.set(group, existing);
|
|
26
|
+
}
|
|
27
|
+
snapshot = groups.size ? [...groups.values()] : EMPTY;
|
|
28
|
+
for (const listener of listeners) listener();
|
|
29
|
+
}
|
|
30
|
+
/** Add rows to the registry and get back the call that removes them. `useShortcuts` is the way in. */
|
|
31
|
+
function registerShortcuts(entries) {
|
|
32
|
+
registrations = [...registrations, ...entries];
|
|
33
|
+
publish();
|
|
34
|
+
return () => {
|
|
35
|
+
registrations = registrations.filter((entry) => !entries.includes(entry));
|
|
36
|
+
publish();
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
function subscribe(onChange) {
|
|
40
|
+
listeners.add(onChange);
|
|
41
|
+
return () => void listeners.delete(onChange);
|
|
42
|
+
}
|
|
43
|
+
/** The current list outside React, for tests. */
|
|
44
|
+
function getShortcutList() {
|
|
45
|
+
return snapshot;
|
|
46
|
+
}
|
|
47
|
+
/** The shortcuts mounted right now, grouped, for the reference dialog. Empty on the server. */
|
|
48
|
+
function useShortcutList() {
|
|
49
|
+
return useSyncExternalStore(subscribe, () => snapshot, () => EMPTY);
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* `useKey`: match the character the key produced, not its physical position, so `d` is the key
|
|
53
|
+
* labelled D on an AZERTY keyboard too. Form tags are filtered per shortcut below, and
|
|
54
|
+
* `preventDefault` is ours: the library would run it before knowing whether anything matched.
|
|
55
|
+
*
|
|
56
|
+
* `capture`: an open Base UI popup (a menu, a select) calls `stopPropagation` on every printable
|
|
57
|
+
* key to feed its own typeahead, so a listener on the document would never see the keys a
|
|
58
|
+
* dropdown covers. Capturing runs the page's shortcuts first, and a match stops the key there.
|
|
59
|
+
*/
|
|
60
|
+
const HOTKEY_OPTIONS = {
|
|
61
|
+
useKey: true,
|
|
62
|
+
enableOnFormTags: true,
|
|
63
|
+
enableOnContentEditable: true,
|
|
64
|
+
eventListenerOptions: { capture: true }
|
|
65
|
+
};
|
|
66
|
+
/**
|
|
67
|
+
* Widgets that take every key typed inside them: an open modal, and the popups that read a
|
|
68
|
+
* printable key as typeahead.
|
|
69
|
+
*/
|
|
70
|
+
const KEY_OWNER_SELECTOR = "[role=\"dialog\"],[role=\"menu\"],[role=\"menubar\"],[role=\"listbox\"]";
|
|
71
|
+
/** Composite widgets that move their own focus with the keys below and leave the rest alone. */
|
|
72
|
+
const NAVIGATOR_SELECTOR = "[role=\"tablist\"],[role=\"grid\"],[role=\"radiogroup\"]";
|
|
73
|
+
const NAVIGATION_KEYS = [
|
|
74
|
+
"ArrowLeft",
|
|
75
|
+
"ArrowRight",
|
|
76
|
+
"ArrowUp",
|
|
77
|
+
"ArrowDown",
|
|
78
|
+
"Home",
|
|
79
|
+
"End"
|
|
80
|
+
];
|
|
81
|
+
/** A menu's rows of every kind: an item, a radio and a checkbox. */
|
|
82
|
+
const MENU_ROW_SELECTOR = "[role=\"menuitem\"],[role=\"menuitemradio\"],[role=\"menuitemcheckbox\"]";
|
|
83
|
+
const FORM_TAGS = [
|
|
84
|
+
"INPUT",
|
|
85
|
+
"TEXTAREA",
|
|
86
|
+
"SELECT"
|
|
87
|
+
];
|
|
88
|
+
function isFormTarget(target) {
|
|
89
|
+
return !!target && (FORM_TAGS.includes(target.tagName) || target.isContentEditable);
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* A key string as the library reports the hotkey it matched, lower-cased and trimmed, so two can
|
|
93
|
+
* be compared like for like. A shortcut badge names its key this way in `data-shortcut`.
|
|
94
|
+
*/
|
|
95
|
+
function toHotkey(keys) {
|
|
96
|
+
return keys.trim().toLowerCase();
|
|
97
|
+
}
|
|
98
|
+
/** The badge an open menu prints for `key`, found by the `data-shortcut` the badge carries. */
|
|
99
|
+
function findMenuBadge(menu, key) {
|
|
100
|
+
const hotkey = toHotkey(key);
|
|
101
|
+
return [...menu.querySelectorAll("[data-shortcut]")].find((badge) => badge.dataset.shortcut === hotkey);
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Whether `key` is one an open menu prints outside its rows, a hint beside a control in the menu
|
|
105
|
+
* such as the date range's "Show by B": it stays the page's shortcut, so pressing it does what
|
|
106
|
+
* the hint says. A row's own badge belongs to the menu, which picks that row instead.
|
|
107
|
+
*/
|
|
108
|
+
function isMenuHint(owner, target, key) {
|
|
109
|
+
if (!owner.matches("[role=\"menu\"]") || isFormTarget(target)) return false;
|
|
110
|
+
const badge = findMenuBadge(owner, key);
|
|
111
|
+
return !!badge && !badge.closest(MENU_ROW_SELECTOR);
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Whether a key typed over `target` belongs to the widget around it rather than to the page's
|
|
115
|
+
* shortcuts. Anything typed inside an open modal belongs to that modal, the shortcuts the modal
|
|
116
|
+
* registered itself included; that is the ceiling on one flat registry, and per-modal scopes
|
|
117
|
+
* (react-hotkeys-hook's HotkeysProvider) are what lifts it. A menu or a listbox reads letters as
|
|
118
|
+
* typeahead, so it keeps every key too, except the keys a menu prints: a row's badge picks that
|
|
119
|
+
* row (`findShortcutRow`), and a hint outside the rows stays the page's. Tabs, a grid and a
|
|
120
|
+
* radio group only step with the arrow keys, Home and End: stepping through a card's tabs must
|
|
121
|
+
* not also step the date range, but a letter typed after clicking a tab still reaches the page.
|
|
122
|
+
*/
|
|
123
|
+
function isWidgetKey(target, key) {
|
|
124
|
+
if (!target) return false;
|
|
125
|
+
const owner = target.closest(KEY_OWNER_SELECTOR);
|
|
126
|
+
if (owner) return !isMenuHint(owner, target, key);
|
|
127
|
+
return NAVIGATION_KEYS.includes(key) && !!target.closest(NAVIGATOR_SELECTOR);
|
|
128
|
+
}
|
|
129
|
+
/** A text field with nothing typed in it yet, so a key pressed there is not part of a query. */
|
|
130
|
+
function isEmptyField(target) {
|
|
131
|
+
return (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) && target.value === "";
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* The row of an open menu whose badge shows the key pressed, for the menu to pick as a click
|
|
135
|
+
* would. The letters printed beside the rows answer ahead of the menu's typeahead, which would
|
|
136
|
+
* jump to the first row starting with that letter instead. Only a single character counts, with
|
|
137
|
+
* no Ctrl, Cmd or Alt held (Shift may be, for a `?`). In a field in the menu, such as its search,
|
|
138
|
+
* a key counts only while the field is empty: the search takes focus as the menu opens, and the
|
|
139
|
+
* keys printed on its rows still work then, while a query once begun keeps every key it types.
|
|
140
|
+
*/
|
|
141
|
+
function findShortcutRow(menu, event) {
|
|
142
|
+
const { key, ctrlKey, metaKey, altKey, target } = event;
|
|
143
|
+
if (ctrlKey || metaKey || altKey || key.length !== 1 || key === " ") return;
|
|
144
|
+
if (target instanceof Element && isFormTarget(target) && !isEmptyField(target)) return;
|
|
145
|
+
return findMenuBadge(menu, key)?.closest(MENU_ROW_SELECTOR) ?? void 0;
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Register any number of shortcuts for as long as the component is mounted. One `useHotkeys` call
|
|
149
|
+
* carries them all, since the list may change length between renders, and the callback routes
|
|
150
|
+
* back to the right handler by the hotkey string the library matched.
|
|
151
|
+
*/
|
|
152
|
+
function useShortcuts(shortcuts) {
|
|
153
|
+
const active = shortcuts.filter((shortcut) => shortcut.enabled !== false);
|
|
154
|
+
const activeRef = useRef(active);
|
|
155
|
+
useEffect(() => {
|
|
156
|
+
activeRef.current = active;
|
|
157
|
+
});
|
|
158
|
+
const hotkeys = [...new Set(active.map((shortcut) => toHotkey(shortcut.keys)))].join(",");
|
|
159
|
+
useHotkeys(hotkeys, (event, hotkeysEvent) => {
|
|
160
|
+
if (event.repeat) return;
|
|
161
|
+
const target = event.target instanceof Element ? event.target : null;
|
|
162
|
+
if (isWidgetKey(target, event.key)) return;
|
|
163
|
+
const typing = isFormTarget(target);
|
|
164
|
+
const matched = activeRef.current.filter((shortcut) => toHotkey(shortcut.keys) === hotkeysEvent.hotkey && (shortcut.enableOnFormTags === true || !typing));
|
|
165
|
+
if (matched.length === 0) return;
|
|
166
|
+
event.preventDefault();
|
|
167
|
+
event.stopPropagation();
|
|
168
|
+
for (const shortcut of matched) shortcut.handler(event);
|
|
169
|
+
}, HOTKEY_OPTIONS);
|
|
170
|
+
const signature = active.map((shortcut) => `${shortcut.group}\t${shortcut.keys}\t${shortcut.label}`).join("\n");
|
|
171
|
+
useEffect(() => {
|
|
172
|
+
return registerShortcuts(activeRef.current.map(({ group, keys, label }) => ({
|
|
173
|
+
group,
|
|
174
|
+
keys,
|
|
175
|
+
label
|
|
176
|
+
})));
|
|
177
|
+
}, [signature]);
|
|
178
|
+
}
|
|
179
|
+
/** A single shortcut, for the common case. */
|
|
180
|
+
function useShortcut(shortcut) {
|
|
181
|
+
useShortcuts([shortcut]);
|
|
182
|
+
}
|
|
183
|
+
/** In Apple order (control, option, shift, command): [mac glyph, label elsewhere]. */
|
|
184
|
+
const MODIFIERS = {
|
|
185
|
+
ctrl: ["⌃", "Ctrl"],
|
|
186
|
+
alt: ["⌥", "Alt"],
|
|
187
|
+
shift: ["⇧", "⇧"],
|
|
188
|
+
mod: ["⌘", "Ctrl"]
|
|
189
|
+
};
|
|
190
|
+
/** Each modifier as a screen reader should say it: [on a mac, elsewhere]. */
|
|
191
|
+
const SPOKEN_MODIFIERS = {
|
|
192
|
+
ctrl: ["Control", "Control"],
|
|
193
|
+
alt: ["Option", "Alt"],
|
|
194
|
+
shift: ["Shift", "Shift"],
|
|
195
|
+
mod: ["Command", "Control"]
|
|
196
|
+
};
|
|
197
|
+
const KEY_LABELS = {
|
|
198
|
+
left: "←",
|
|
199
|
+
right: "→",
|
|
200
|
+
up: "↑",
|
|
201
|
+
down: "↓",
|
|
202
|
+
esc: "Esc",
|
|
203
|
+
escape: "Esc",
|
|
204
|
+
enter: "↵",
|
|
205
|
+
space: "Space"
|
|
206
|
+
};
|
|
207
|
+
/** The keys whose badge is a glyph a screen reader would name by its Unicode name. */
|
|
208
|
+
const SPOKEN_KEYS = {
|
|
209
|
+
left: "Left arrow",
|
|
210
|
+
right: "Right arrow",
|
|
211
|
+
up: "Up arrow",
|
|
212
|
+
down: "Down arrow",
|
|
213
|
+
esc: "Escape",
|
|
214
|
+
escape: "Escape",
|
|
215
|
+
enter: "Enter"
|
|
216
|
+
};
|
|
217
|
+
/**
|
|
218
|
+
* Deliberately the same rule react-hotkeys-hook applies internally to decide whether `mod`
|
|
219
|
+
* means Meta or Control. It does not export it, and it only ever runs on a keystroke, so it
|
|
220
|
+
* cannot be reused, but it is the authority on what `mod` actually matches. Detecting the
|
|
221
|
+
* platform some other way (navigator.platform, userAgentData) risks a badge that says ⌘ while
|
|
222
|
+
* the matcher is waiting for Ctrl, and the label would be lying about the shortcut.
|
|
223
|
+
*/
|
|
224
|
+
function isMacUserAgent(userAgent) {
|
|
225
|
+
return /mac/i.test(userAgent) && !/iphone|ipad|ipod/i.test(userAgent);
|
|
226
|
+
}
|
|
227
|
+
/** Read at call time, not at import: on the server there is no navigator at all. */
|
|
228
|
+
function readIsMac() {
|
|
229
|
+
return typeof navigator !== "undefined" && isMacUserAgent(navigator.userAgent);
|
|
230
|
+
}
|
|
231
|
+
function noSubscribe() {
|
|
232
|
+
return () => {};
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Whether to spell shortcuts the Apple way. A hook rather than a module constant because this
|
|
236
|
+
* package renders under SSR: read at import time, the server produced "Ctrl" and the client
|
|
237
|
+
* hydrated "⌘", which is a hydration mismatch on every shortcut badge. Returning false as the
|
|
238
|
+
* server snapshot makes the first client render agree, then React re-renders with the truth.
|
|
239
|
+
*/
|
|
240
|
+
function useIsMac() {
|
|
241
|
+
return useSyncExternalStore(noSubscribe, readIsMac, () => false);
|
|
242
|
+
}
|
|
243
|
+
/** A key string split into its modifiers, in Apple order, and its key. */
|
|
244
|
+
function parseKeys(keys) {
|
|
245
|
+
const parts = toHotkey(keys).split("+").map((part) => part.trim());
|
|
246
|
+
const key = parts.find((part) => !(part in MODIFIERS)) ?? "";
|
|
247
|
+
const written = parts.filter((part) => part in MODIFIERS);
|
|
248
|
+
return {
|
|
249
|
+
modifiers: written.length === 1 && written[0] === "shift" && /^[^a-z0-9]$/.test(key) ? [] : Object.keys(MODIFIERS).filter((modifier) => written.includes(modifier)),
|
|
250
|
+
key
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
function formatKeyName(key) {
|
|
254
|
+
return `${key.charAt(0).toUpperCase()}${key.slice(1)}`;
|
|
255
|
+
}
|
|
256
|
+
/** A key string as badge parts: the modifiers in Apple order, then the key. Platform injectable for tests. */
|
|
257
|
+
function formatKeys(keys, mac = readIsMac()) {
|
|
258
|
+
const { modifiers, key } = parseKeys(keys);
|
|
259
|
+
return [...modifiers.map((modifier) => MODIFIERS[modifier]?.[mac ? 0 : 1] ?? modifier), KEY_LABELS[key] ?? formatKeyName(key)];
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* A key string as a screen reader should say it ("Command K"): the badge's glyphs would be read
|
|
263
|
+
* by their Unicode names, "place of interest sign" for ⌘. Platform injectable for tests.
|
|
264
|
+
*/
|
|
265
|
+
function formatSpokenKeys(keys, mac = readIsMac()) {
|
|
266
|
+
const { modifiers, key } = parseKeys(keys);
|
|
267
|
+
return [...modifiers.map((modifier) => SPOKEN_MODIFIERS[modifier]?.[mac ? 0 : 1] ?? modifier), SPOKEN_KEYS[key] ?? formatKeyName(key)].join(" ");
|
|
268
|
+
}
|
|
269
|
+
export { findShortcutRow, formatKeys, formatSpokenKeys, getShortcutList, isMacUserAgent, isWidgetKey, registerShortcuts, toHotkey, useIsMac, useShortcut, useShortcutList, useShortcuts };
|
|
270
|
+
|
|
271
|
+
//# sourceMappingURL=shortcuts.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"shortcuts.js","names":[],"sources":["../../src/lib/shortcuts.ts"],"sourcesContent":["\"use client\"\n\nimport { useEffect, useRef, useSyncExternalStore } from \"react\"\nimport { useHotkeys } from \"react-hotkeys-hook\"\n\nexport interface Shortcut {\n /**\n * react-hotkeys-hook key string: `d`, `mod+k`, `shift+?`, `left`. Matched on the character the\n * key produces, so a letter is the key labelled with it on any layout.\n */\n keys: string\n\n /** Human label shown in the reference dialog, e.g. \"Today\". */\n label: string\n\n /** Section in the reference dialog, e.g. \"Date range\". Sections appear in registration order. */\n group: string\n\n handler: (event: KeyboardEvent) => void\n\n /** Default true. A disabled shortcut neither fires nor shows up in the reference dialog. */\n enabled?: boolean\n\n /** Fire while typing in inputs, textareas, selects and contenteditable. Default false. */\n enableOnFormTags?: boolean\n}\n\nexport interface ShortcutGroup {\n group: string\n shortcuts: { keys: string; label: string }[]\n}\n\n/** What `findShortcutRow` reads off a key press: a DOM event or React's. */\nexport interface MenuKeyEvent {\n key: string\n ctrlKey: boolean\n metaKey: boolean\n altKey: boolean\n target: EventTarget | null\n}\n\n// The registry the reference dialog is built from: every mounted shortcut's metadata, in\n// registration order, behind a `useSyncExternalStore` snapshot.\n\ntype Registration = Pick<Shortcut, \"group\" | \"keys\" | \"label\">\n\nconst EMPTY: ShortcutGroup[] = []\nconst listeners = new Set<() => void>()\n\nlet registrations: Registration[] = []\nlet snapshot = EMPTY\n\n/** Rebuilt once per change, so `useSyncExternalStore` sees a referentially stable snapshot. */\nfunction publish() {\n const groups = new Map<string, ShortcutGroup>()\n const seen = new Set<string>()\n\n for (const { group, keys, label } of registrations) {\n const id = `${group}\\t${keys}\\t${label}`\n if (seen.has(id)) continue\n seen.add(id)\n\n const existing = groups.get(group) ?? { group, shortcuts: [] }\n existing.shortcuts.push({ keys, label })\n groups.set(group, existing)\n }\n\n snapshot = groups.size ? [...groups.values()] : EMPTY\n for (const listener of listeners) listener()\n}\n\n/** Add rows to the registry and get back the call that removes them. `useShortcuts` is the way in. */\nexport function registerShortcuts(entries: Registration[]) {\n registrations = [...registrations, ...entries]\n publish()\n\n return () => {\n registrations = registrations.filter(entry => !entries.includes(entry))\n publish()\n }\n}\n\nfunction subscribe(onChange: () => void) {\n listeners.add(onChange)\n return () => void listeners.delete(onChange)\n}\n\n/** The current list outside React, for tests. */\nexport function getShortcutList() {\n return snapshot\n}\n\n/** The shortcuts mounted right now, grouped, for the reference dialog. Empty on the server. */\nexport function useShortcutList(): ShortcutGroup[] {\n return useSyncExternalStore(\n subscribe,\n () => snapshot,\n () => EMPTY,\n )\n}\n\n// Matching a keystroke to a handler.\n\n/**\n * `useKey`: match the character the key produced, not its physical position, so `d` is the key\n * labelled D on an AZERTY keyboard too. Form tags are filtered per shortcut below, and\n * `preventDefault` is ours: the library would run it before knowing whether anything matched.\n *\n * `capture`: an open Base UI popup (a menu, a select) calls `stopPropagation` on every printable\n * key to feed its own typeahead, so a listener on the document would never see the keys a\n * dropdown covers. Capturing runs the page's shortcuts first, and a match stops the key there.\n */\nconst HOTKEY_OPTIONS = {\n useKey: true,\n enableOnFormTags: true,\n enableOnContentEditable: true,\n eventListenerOptions: { capture: true },\n}\n\n/**\n * Widgets that take every key typed inside them: an open modal, and the popups that read a\n * printable key as typeahead.\n */\nconst KEY_OWNER_SELECTOR = '[role=\"dialog\"],[role=\"menu\"],[role=\"menubar\"],[role=\"listbox\"]'\n\n/** Composite widgets that move their own focus with the keys below and leave the rest alone. */\nconst NAVIGATOR_SELECTOR = '[role=\"tablist\"],[role=\"grid\"],[role=\"radiogroup\"]'\nconst NAVIGATION_KEYS = [\"ArrowLeft\", \"ArrowRight\", \"ArrowUp\", \"ArrowDown\", \"Home\", \"End\"]\n\n/** A menu's rows of every kind: an item, a radio and a checkbox. */\nconst MENU_ROW_SELECTOR = '[role=\"menuitem\"],[role=\"menuitemradio\"],[role=\"menuitemcheckbox\"]'\n\nconst FORM_TAGS = [\"INPUT\", \"TEXTAREA\", \"SELECT\"]\n\nfunction isFormTarget(target: Element | null) {\n return (\n !!target && (FORM_TAGS.includes(target.tagName) || (target as HTMLElement).isContentEditable)\n )\n}\n\n/**\n * A key string as the library reports the hotkey it matched, lower-cased and trimmed, so two can\n * be compared like for like. A shortcut badge names its key this way in `data-shortcut`.\n */\nexport function toHotkey(keys: string) {\n return keys.trim().toLowerCase()\n}\n\n/** The badge an open menu prints for `key`, found by the `data-shortcut` the badge carries. */\nfunction findMenuBadge(menu: Element, key: string) {\n const hotkey = toHotkey(key)\n return [...menu.querySelectorAll<HTMLElement>(\"[data-shortcut]\")].find(\n badge => badge.dataset.shortcut === hotkey,\n )\n}\n\n/**\n * Whether `key` is one an open menu prints outside its rows, a hint beside a control in the menu\n * such as the date range's \"Show by B\": it stays the page's shortcut, so pressing it does what\n * the hint says. A row's own badge belongs to the menu, which picks that row instead.\n */\nfunction isMenuHint(owner: Element, target: Element, key: string) {\n if (!owner.matches('[role=\"menu\"]') || isFormTarget(target)) return false\n const badge = findMenuBadge(owner, key)\n return !!badge && !badge.closest(MENU_ROW_SELECTOR)\n}\n\n/**\n * Whether a key typed over `target` belongs to the widget around it rather than to the page's\n * shortcuts. Anything typed inside an open modal belongs to that modal, the shortcuts the modal\n * registered itself included; that is the ceiling on one flat registry, and per-modal scopes\n * (react-hotkeys-hook's HotkeysProvider) are what lifts it. A menu or a listbox reads letters as\n * typeahead, so it keeps every key too, except the keys a menu prints: a row's badge picks that\n * row (`findShortcutRow`), and a hint outside the rows stays the page's. Tabs, a grid and a\n * radio group only step with the arrow keys, Home and End: stepping through a card's tabs must\n * not also step the date range, but a letter typed after clicking a tab still reaches the page.\n */\nexport function isWidgetKey(target: Element | null, key: string) {\n if (!target) return false\n const owner = target.closest(KEY_OWNER_SELECTOR)\n if (owner) return !isMenuHint(owner, target, key)\n return NAVIGATION_KEYS.includes(key) && !!target.closest(NAVIGATOR_SELECTOR)\n}\n\n/** A text field with nothing typed in it yet, so a key pressed there is not part of a query. */\nfunction isEmptyField(target: Element) {\n return (\n (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) &&\n target.value === \"\"\n )\n}\n\n/**\n * The row of an open menu whose badge shows the key pressed, for the menu to pick as a click\n * would. The letters printed beside the rows answer ahead of the menu's typeahead, which would\n * jump to the first row starting with that letter instead. Only a single character counts, with\n * no Ctrl, Cmd or Alt held (Shift may be, for a `?`). In a field in the menu, such as its search,\n * a key counts only while the field is empty: the search takes focus as the menu opens, and the\n * keys printed on its rows still work then, while a query once begun keeps every key it types.\n */\nexport function findShortcutRow(menu: Element, event: MenuKeyEvent) {\n const { key, ctrlKey, metaKey, altKey, target } = event\n if (ctrlKey || metaKey || altKey || key.length !== 1 || key === \" \") return\n if (target instanceof Element && isFormTarget(target) && !isEmptyField(target)) return\n return findMenuBadge(menu, key)?.closest<HTMLElement>(MENU_ROW_SELECTOR) ?? undefined\n}\n\n/**\n * Register any number of shortcuts for as long as the component is mounted. One `useHotkeys` call\n * carries them all, since the list may change length between renders, and the callback routes\n * back to the right handler by the hotkey string the library matched.\n */\nexport function useShortcuts(shortcuts: Shortcut[]) {\n const active = shortcuts.filter(shortcut => shortcut.enabled !== false)\n\n // The latest handlers, read by the dispatch callback without re-registering anything.\n const activeRef = useRef(active)\n useEffect(() => {\n activeRef.current = active\n })\n\n const hotkeys = [...new Set(active.map(shortcut => toHotkey(shortcut.keys)))].join(\",\")\n\n useHotkeys(\n hotkeys,\n (event, hotkeysEvent) => {\n if (event.repeat) return\n\n const target = event.target instanceof Element ? event.target : null\n\n if (isWidgetKey(target, event.key)) return\n\n const typing = isFormTarget(target)\n const matched = activeRef.current.filter(\n shortcut =>\n toHotkey(shortcut.keys) === hotkeysEvent.hotkey &&\n (shortcut.enableOnFormTags === true || !typing),\n )\n\n if (matched.length === 0) return\n\n // The key belongs to the shortcut, not to whatever it was typed over: an open dropdown\n // should not also run its typeahead on it.\n event.preventDefault()\n event.stopPropagation()\n for (const shortcut of matched) shortcut.handler(event)\n },\n HOTKEY_OPTIONS,\n )\n\n // Only the metadata reaches the dialog, so re-register when that changes, not on every\n // render.\n const signature = active\n .map(shortcut => `${shortcut.group}\\t${shortcut.keys}\\t${shortcut.label}`)\n .join(\"\\n\")\n\n useEffect(() => {\n return registerShortcuts(\n activeRef.current.map(({ group, keys, label }) => ({ group, keys, label })),\n )\n }, [signature])\n}\n\n/** A single shortcut, for the common case. */\nexport function useShortcut(shortcut: Shortcut) {\n useShortcuts([shortcut])\n}\n\n// Spelling a key string out as badge parts.\n\n/** In Apple order (control, option, shift, command): [mac glyph, label elsewhere]. */\nconst MODIFIERS: Record<string, [string, string]> = {\n ctrl: [\"⌃\", \"Ctrl\"],\n alt: [\"⌥\", \"Alt\"],\n shift: [\"⇧\", \"⇧\"],\n mod: [\"⌘\", \"Ctrl\"],\n}\n\n/** Each modifier as a screen reader should say it: [on a mac, elsewhere]. */\nconst SPOKEN_MODIFIERS: Record<string, [string, string]> = {\n ctrl: [\"Control\", \"Control\"],\n alt: [\"Option\", \"Alt\"],\n shift: [\"Shift\", \"Shift\"],\n mod: [\"Command\", \"Control\"],\n}\n\nconst KEY_LABELS: Record<string, string> = {\n left: \"←\",\n right: \"→\",\n up: \"↑\",\n down: \"↓\",\n esc: \"Esc\",\n escape: \"Esc\",\n enter: \"↵\",\n space: \"Space\",\n}\n\n/** The keys whose badge is a glyph a screen reader would name by its Unicode name. */\nconst SPOKEN_KEYS: Record<string, string> = {\n left: \"Left arrow\",\n right: \"Right arrow\",\n up: \"Up arrow\",\n down: \"Down arrow\",\n esc: \"Escape\",\n escape: \"Escape\",\n enter: \"Enter\",\n}\n\n/**\n * Deliberately the same rule react-hotkeys-hook applies internally to decide whether `mod`\n * means Meta or Control. It does not export it, and it only ever runs on a keystroke, so it\n * cannot be reused, but it is the authority on what `mod` actually matches. Detecting the\n * platform some other way (navigator.platform, userAgentData) risks a badge that says ⌘ while\n * the matcher is waiting for Ctrl, and the label would be lying about the shortcut.\n */\nexport function isMacUserAgent(userAgent: string): boolean {\n return /mac/i.test(userAgent) && !/iphone|ipad|ipod/i.test(userAgent)\n}\n\n/** Read at call time, not at import: on the server there is no navigator at all. */\nfunction readIsMac() {\n return typeof navigator !== \"undefined\" && isMacUserAgent(navigator.userAgent)\n}\n\n// The platform never changes within a document, so the store never notifies.\nfunction noSubscribe() {\n return () => {}\n}\n\n/**\n * Whether to spell shortcuts the Apple way. A hook rather than a module constant because this\n * package renders under SSR: read at import time, the server produced \"Ctrl\" and the client\n * hydrated \"⌘\", which is a hydration mismatch on every shortcut badge. Returning false as the\n * server snapshot makes the first client render agree, then React re-renders with the truth.\n */\nexport function useIsMac() {\n return useSyncExternalStore(noSubscribe, readIsMac, () => false)\n}\n\ninterface ParsedKeys {\n /** In Apple order. */\n modifiers: string[]\n key: string\n}\n\n/** A key string split into its modifiers, in Apple order, and its key. */\nfunction parseKeys(keys: string): ParsedKeys {\n const parts = toHotkey(keys)\n .split(\"+\")\n .map(part => part.trim())\n const key = parts.find(part => !(part in MODIFIERS)) ?? \"\"\n const written = parts.filter(part => part in MODIFIERS)\n\n // `shift+?` is typed as one key; the shift is only there so the library can match it.\n const shiftedSymbol = written.length === 1 && written[0] === \"shift\" && /^[^a-z0-9]$/.test(key)\n const modifiers = shiftedSymbol\n ? []\n : Object.keys(MODIFIERS).filter(modifier => written.includes(modifier))\n\n return { modifiers, key }\n}\n\nfunction formatKeyName(key: string) {\n return `${key.charAt(0).toUpperCase()}${key.slice(1)}`\n}\n\n/** A key string as badge parts: the modifiers in Apple order, then the key. Platform injectable for tests. */\nexport function formatKeys(keys: string, mac = readIsMac()): string[] {\n const { modifiers, key } = parseKeys(keys)\n\n return [\n ...modifiers.map(modifier => MODIFIERS[modifier]?.[mac ? 0 : 1] ?? modifier),\n KEY_LABELS[key] ?? formatKeyName(key),\n ]\n}\n\n/**\n * A key string as a screen reader should say it (\"Command K\"): the badge's glyphs would be read\n * by their Unicode names, \"place of interest sign\" for ⌘. Platform injectable for tests.\n */\nexport function formatSpokenKeys(keys: string, mac = readIsMac()) {\n const { modifiers, key } = parseKeys(keys)\n\n return [\n ...modifiers.map(modifier => SPOKEN_MODIFIERS[modifier]?.[mac ? 0 : 1] ?? modifier),\n SPOKEN_KEYS[key] ?? formatKeyName(key),\n ].join(\" \")\n}\n"],"mappings":";;;;AA8CA,MAAM,QAAyB,CAAC;AAChC,MAAM,4BAAY,IAAI,IAAgB;AAEtC,IAAI,gBAAgC,CAAC;AACrC,IAAI,WAA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AI,MAAM,QAAQ,GAC3E,WAAW,QAAQ,cAAc,GAAG,CACtC;AACF;;;;;AAMA,SAAgB,iBAAiB,MAAc,MAAM,UAAU,GAAG;CAChE,MAAM,EAAE,WAAW,QAAQ,UAAU,IAAI;CAEzC,OAAO,CACL,GAAG,UAAU,KAAI,aAAY,iBAAiB,SAAS,GAAG,MAAM,IAAI,MAAM,QAAQ,GAClF,YAAY,QAAQ,cAAc,GAAG,CACvC,CAAC,CAAC,KAAK,GAAG;AACZ"}
|
package/lib/slot.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { ReactNode } from "react";
|
|
2
|
+
/**
|
|
3
|
+
* Merges props onto a React element without adding a wrapper DOM node.
|
|
4
|
+
* Uses Base UI's `mergeProps` for type-safe className concatenation,
|
|
5
|
+
* event handler composition, and style merging.
|
|
6
|
+
*
|
|
7
|
+
* Returns the element as-is if it's not a valid React element (null, undefined, text).
|
|
8
|
+
*/
|
|
9
|
+
export declare function slot(element: ReactNode, props: Record<string, unknown>): ReactNode;
|
package/lib/slot.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { mergeProps } from "@base-ui/react";
|
|
2
|
+
import { cloneElement, isValidElement } from "react";
|
|
3
|
+
// src/lib/slot.ts
|
|
4
|
+
/**
|
|
5
|
+
* Merges props onto a React element without adding a wrapper DOM node.
|
|
6
|
+
* Uses Base UI's `mergeProps` for type-safe className concatenation,
|
|
7
|
+
* event handler composition, and style merging.
|
|
8
|
+
*
|
|
9
|
+
* Returns the element as-is if it's not a valid React element (null, undefined, text).
|
|
10
|
+
*/
|
|
11
|
+
function slot(element, props) {
|
|
12
|
+
if (!isValidElement(element)) return element;
|
|
13
|
+
const target = element;
|
|
14
|
+
return cloneElement(target, mergeProps(props, target.props));
|
|
15
|
+
}
|
|
16
|
+
export { slot };
|
|
17
|
+
|
|
18
|
+
//# sourceMappingURL=slot.js.map
|
package/lib/slot.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"slot.js","names":[],"sources":["../../src/lib/slot.ts"],"sourcesContent":["import { mergeProps } from \"@base-ui/react\"\nimport { cloneElement, isValidElement, type ReactElement, type ReactNode } from \"react\"\n\n/**\n * Merges props onto a React element without adding a wrapper DOM node.\n * Uses Base UI's `mergeProps` for type-safe className concatenation,\n * event handler composition, and style merging.\n *\n * Returns the element as-is if it's not a valid React element (null, undefined, text).\n */\nexport function slot(element: ReactNode, props: Record<string, unknown>): ReactNode {\n if (!isValidElement(element)) {\n return element\n }\n\n const target = element as ReactElement<Record<string, unknown>>\n\n return cloneElement(target, mergeProps(props, target.props))\n}\n"],"mappings":";;;;;;;;;;AAUA,SAAgB,KAAK,SAAoB,OAA2C;CAClF,IAAI,CAAC,eAAe,OAAO,GACzB,OAAO;CAGT,MAAM,SAAS;CAEf,OAAO,aAAa,QAAQ,WAAW,OAAO,OAAO,KAAK,CAAC;AAC7D"}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The arithmetic behind `TimeSeriesChart`: its point and note shapes, round grid lines, evenly
|
|
3
|
+
* spaced date ticks, and notes folded onto the buckets that hold them. Pure, so it is tested
|
|
4
|
+
* without rendering a chart.
|
|
5
|
+
*/
|
|
6
|
+
export interface TimeSeriesSeries {
|
|
7
|
+
/** Reads `point.values[key]`. */
|
|
8
|
+
key: string;
|
|
9
|
+
label: string;
|
|
10
|
+
/** One of the `--color-chart-*` tokens; defaults to `SERIES_COLORS` by index. */
|
|
11
|
+
color?: string;
|
|
12
|
+
}
|
|
13
|
+
/** The hues of a multi-series chart's lines, in series order; a fourth line wraps to the first. */
|
|
14
|
+
export declare const SERIES_COLORS: string[];
|
|
15
|
+
export interface TimeSeriesPoint {
|
|
16
|
+
date: Date;
|
|
17
|
+
value: number;
|
|
18
|
+
/**
|
|
19
|
+
* The same bucket in a compared period, drawn as a dashed, unfilled line.
|
|
20
|
+
*/
|
|
21
|
+
previous?: number;
|
|
22
|
+
/**
|
|
23
|
+
* An optional second series drawn as bars behind the line, on its own left-hand axis
|
|
24
|
+
* (a different unit, e.g. revenue against a traffic line). Shown when any point is above zero.
|
|
25
|
+
*/
|
|
26
|
+
bar?: number;
|
|
27
|
+
/**
|
|
28
|
+
* A segment stacked on `bar`, drawn as a dashed outline: the part the bar lost (a refund
|
|
29
|
+
* over net revenue). Drawn, and listed in the tooltip, once any point is above zero.
|
|
30
|
+
*/
|
|
31
|
+
outline?: number;
|
|
32
|
+
/** Multi-series mode: one figure per `TimeSeriesSeries.key`. */
|
|
33
|
+
values?: Record<string, number>;
|
|
34
|
+
/**
|
|
35
|
+
* The bucket covers only part of its period, so its figures read low: the last buckets while
|
|
36
|
+
* they are still running, or the first when a rolling range starts mid-bucket. The line
|
|
37
|
+
* reaches them dashed and their bars are dashed outlines, so a partial bucket never reads as
|
|
38
|
+
* a drop.
|
|
39
|
+
*/
|
|
40
|
+
partial?: boolean;
|
|
41
|
+
/**
|
|
42
|
+
* Figures of the bucket that the chart does not draw, already formatted, listed in its
|
|
43
|
+
* tooltip under a hairline.
|
|
44
|
+
*/
|
|
45
|
+
details?: {
|
|
46
|
+
label: string;
|
|
47
|
+
value: string;
|
|
48
|
+
}[];
|
|
49
|
+
}
|
|
50
|
+
export interface TimeSeriesNote {
|
|
51
|
+
date: Date;
|
|
52
|
+
text: string;
|
|
53
|
+
/** Who wrote it; the tooltip's small line over the text ("Piotr · Sep 10"). */
|
|
54
|
+
author?: string;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* The wash under a line, as `TimeSeriesChart` and `Sparkline` draw it: a quarter of the series'
|
|
58
|
+
* hue at the line, fading to nothing at the baseline. Offsets run from the top of the plot.
|
|
59
|
+
*/
|
|
60
|
+
export declare const AREA_FADE: readonly [{
|
|
61
|
+
readonly offset: 0.05;
|
|
62
|
+
readonly opacity: 0.25;
|
|
63
|
+
}, {
|
|
64
|
+
readonly offset: 0.95;
|
|
65
|
+
readonly opacity: 0.01;
|
|
66
|
+
}];
|
|
67
|
+
/** How many buckets at the end of the series are still running. */
|
|
68
|
+
export declare function countRunning(data: Pick<TimeSeriesPoint, "partial">[]): number;
|
|
69
|
+
/** How many partial buckets open the series, leaving out the running ones at its end. */
|
|
70
|
+
export declare function countPartialStart(data: Pick<TimeSeriesPoint, "partial">[]): number;
|
|
71
|
+
/** The sum of one series over the range, for the legend; a point without the key counts as zero. */
|
|
72
|
+
export declare function seriesTotal(data: TimeSeriesPoint[], key: string): number;
|
|
73
|
+
/**
|
|
74
|
+
* Grid lines from 0 up past `max`, all on round numbers. A plain step (1, 2, 5) wins unless the
|
|
75
|
+
* data would fill less than three quarters of the scale it makes, and steps whose ticks render
|
|
76
|
+
* the same label are ruled out: a currency axis over a few cents otherwise reads "$0.01,
|
|
77
|
+
* $0.01". An empty series is a plain 0–4.
|
|
78
|
+
*/
|
|
79
|
+
export declare function niceTicks(max: number, { integer, format }?: {
|
|
80
|
+
integer?: boolean;
|
|
81
|
+
format?: (value: number) => string;
|
|
82
|
+
}): number[];
|
|
83
|
+
/** Grid lines over a fixed scale (a rate pinned to `[0, 100]`), in equal intervals. */
|
|
84
|
+
export declare function domainTicks([low, high]: [number, number]): number[];
|
|
85
|
+
/**
|
|
86
|
+
* Tick instants on a time axis: every nth bucket from the first, with the smallest whole n
|
|
87
|
+
* that fits `count` labels. Ticks land on real buckets and the gaps are equal, so the labels
|
|
88
|
+
* step by a constant amount ("2 AM, 4 AM, 6 AM") instead of drifting between 1 and 2. The
|
|
89
|
+
* tail bucket is dropped when it doesn't fall on the step rather than crowding the last gap.
|
|
90
|
+
*/
|
|
91
|
+
export declare function pickTicks(times: number[], count: number): number[];
|
|
92
|
+
/**
|
|
93
|
+
* Notes grouped onto the bucket that holds them: a note belongs to the last bucket starting at
|
|
94
|
+
* or before it, so a week bucket folds in its seven days and an hourly chart shows a midnight
|
|
95
|
+
* note on its 00:00 bucket. Anything past the trailing bucket's `end` is outside the range and
|
|
96
|
+
* dropped, as is anything before the first bucket. Without an `end` the trailing bucket is taken
|
|
97
|
+
* to be as wide as the one before it (wrong for months, hence the parameter); a lone bucket
|
|
98
|
+
* then has no width to infer from, so only a note on its exact instant lands.
|
|
99
|
+
*/
|
|
100
|
+
export declare function bucketNotes(times: number[], notes: TimeSeriesNote[], endOfLast?: number): Map<number, TimeSeriesNote[]>;
|