@trackunit/react-components 8.0.9-alpha-3123793ad15.0 → 8.0.9
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/index.cjs.js +1433 -474
- package/index.esm.js +1427 -477
- package/migrations/assets/react-router-components/package.json +6 -6
- package/package.json +6 -6
- package/src/components/Card/Card.d.ts +1 -7
- package/src/components/Card/Card.variants.d.ts +1 -15
- package/src/components/ShortcutKeys/ShortcutKeys.d.ts +63 -0
- package/src/components/ShortcutKeys/ShortcutKeys.variants.d.ts +74 -0
- package/src/hooks/useAction/actionRegistry.d.ts +231 -0
- package/src/hooks/useAction/useAction.d.ts +118 -0
- package/src/hooks/useAction/useActionIssueReporter.d.ts +15 -0
- package/src/hooks/useAction/useActionRelay.d.ts +17 -0
- package/src/hooks/useAction/useActions.d.ts +45 -0
- package/src/hooks/useAction/useRegisterAction.d.ts +8 -0
- package/src/hooks/useAction/useRegisteredActions.d.ts +12 -0
- package/src/hooks/useAction/useRegistrationOwner.d.ts +8 -0
- package/src/hooks/useAction/utils/shortcutTakenBy/shortcutTakenBy.d.ts +13 -0
- package/src/hooks/useAction/utils/toRegistered/toRegistered.d.ts +12 -0
- package/src/hooks/useKeyboardShortcut/claimShortcutEvent.d.ts +11 -0
- package/src/hooks/useKeyboardShortcut/formatShortcutLabel.d.ts +26 -2
- package/src/hooks/useKeyboardShortcut/isTypedInFieldInside.d.ts +13 -0
- package/src/hooks/useKeyboardShortcut/reservedShortcutTypes.d.ts +8 -4
- package/src/hooks/useKeyboardShortcut/shortcutMatcher.d.ts +13 -2
- package/src/hooks/useKeyboardShortcut/types.d.ts +32 -1
- package/src/hooks/useKeyboardShortcut/useKeyboardShortcut.d.ts +16 -7
- package/src/hooks/useKeyboardShortcut/useShortcutHelpers.d.ts +17 -0
- package/src/index.d.ts +23 -0
- package/migrations/entry.js.map +0 -1
- package/migrations/utils/jsx-utils.js.map +0 -1
- package/migrations/utils/move-named-imports.js.map +0 -1
- package/migrations/utils/package-json-utils.js.map +0 -1
- package/migrations/v2-0-0/breadcrumb-remove-deprecated-props.js.map +0 -1
- package/migrations/v2-0-0/cardheader-onclickclose-to-actions.js.map +0 -1
- package/migrations/v2-0-0/iconbutton-add-required-name.js.map +0 -1
- package/migrations/v2-0-0/kpi-tooltiplabel-to-wrapper.js.map +0 -1
- package/migrations/v2-0-0/notice-tooltiplabel-to-wrapper.js.map +0 -1
- package/migrations/v2-0-0/pagination-add-required-titles.js.map +0 -1
- package/migrations/v2-0-0/tag-add-removetaglabel.js.map +0 -1
- package/migrations/v2-0-0/togglegroup-remove-item-style.js.map +0 -1
- package/migrations/v2-6-0/menulist-rename-to-menucontent.js.map +0 -1
- package/migrations/v3-0-0/copyabletext-to-text-copybutton.js.map +0 -1
- package/migrations/v4-0-0/move-to-router-components.js.map +0 -1
- package/migrations/v8-0-0/collapse-native-details.js.map +0 -1
package/index.esm.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { jsx, Fragment, jsxs } from 'react/jsx-runtime';
|
|
2
2
|
import { registerTranslations, useNamespaceTranslation } from '@trackunit/i18n-library-translation';
|
|
3
3
|
import { twMerge } from 'tailwind-merge';
|
|
4
|
-
import { objectKeys, uuidv4, parseTailwindArbitraryValue, nonNullable, objectValues, validateState, writeToStorage, readFromStorage, identityFingerprint, listHashKeys, readHashKey, unwrapUrlOwner, writeHashKey, objectEntries, filterByMultiple } from '@trackunit/shared-utils';
|
|
4
|
+
import { objectKeys, uuidv4, parseTailwindArbitraryValue, nonNullable, objectValues, validateState, writeToStorage, readFromStorage, identityFingerprint, listHashKeys, readHashKey, unwrapUrlOwner, writeHashKey, matchesShortcutKey, isSymbolShortcutKey, objectEntries, filterByMultiple } from '@trackunit/shared-utils';
|
|
5
5
|
export { storageSerializer } from '@trackunit/shared-utils';
|
|
6
|
-
import { useRef, useMemo, useEffect, useSyncExternalStore, useState, useLayoutEffect, createContext, useContext, isValidElement, cloneElement, createElement, useId, useCallback, Fragment as Fragment$1, memo, forwardRef, useReducer, Children } from 'react';
|
|
6
|
+
import { useRef, useMemo, useEffect, useSyncExternalStore, useState, useLayoutEffect, createContext, useContext, isValidElement, cloneElement, createElement, useId, useCallback, Fragment as Fragment$1, memo, forwardRef, useReducer, Children, captureOwnerStack } from 'react';
|
|
7
7
|
import { rentalStatusPalette, sitesPalette, utilizationPalette, activityPalette, criticalityPalette, trackunitBrandingPalette, generalPalette, intentPalette, themeContainerSize, color, themeScreenSizeAsNumber } from '@trackunit/ui-design-tokens';
|
|
8
8
|
import { iconNames } from '@trackunit/ui-icons';
|
|
9
9
|
import IconSpriteMicro from '@trackunit/ui-icons/icons-sprite-micro.svg';
|
|
@@ -600,7 +600,7 @@ const listeners = new Set();
|
|
|
600
600
|
let listenerRefCount = 0;
|
|
601
601
|
/** Last real pointer position seen anywhere on the page, in viewport (`clientX`/`clientY`) coordinates. */
|
|
602
602
|
let lastPointerPosition = null;
|
|
603
|
-
const notify = () => {
|
|
603
|
+
const notify$1 = () => {
|
|
604
604
|
listeners.forEach(listener => listener());
|
|
605
605
|
};
|
|
606
606
|
const setSuppressed = (next) => {
|
|
@@ -614,7 +614,7 @@ const setSuppressed = (next) => {
|
|
|
614
614
|
else {
|
|
615
615
|
document.documentElement.removeAttribute(HOVER_SCROLL_SUPPRESSED_ATTR);
|
|
616
616
|
}
|
|
617
|
-
notify();
|
|
617
|
+
notify$1();
|
|
618
618
|
};
|
|
619
619
|
const clearSettleTimeout = () => {
|
|
620
620
|
if (settleTimeoutId !== null) {
|
|
@@ -2969,18 +2969,10 @@ const cvaCard = cva({
|
|
|
2969
2969
|
false: "",
|
|
2970
2970
|
true: "h-full",
|
|
2971
2971
|
},
|
|
2972
|
-
// overflow-clip is not a scroll container, so as a flex/grid item the card keeps
|
|
2973
|
-
// min-width/min-height: auto and grows to fit its content. Content that scrolls on its own
|
|
2974
|
-
// (e.g. a Table) needs the card to stay within the space its parent gives it instead.
|
|
2975
|
-
scrollableContent: {
|
|
2976
|
-
false: "",
|
|
2977
|
-
true: ["min-h-0", "min-w-0"],
|
|
2978
|
-
},
|
|
2979
2972
|
},
|
|
2980
2973
|
defaultVariants: {
|
|
2981
2974
|
clickable: false,
|
|
2982
2975
|
fullHeight: false,
|
|
2983
|
-
scrollableContent: false,
|
|
2984
2976
|
},
|
|
2985
2977
|
});
|
|
2986
2978
|
const cvaCardFooterContainerRoot = cva({
|
|
@@ -3095,8 +3087,8 @@ const ROLE_CARD = "region";
|
|
|
3095
3087
|
* @param {CardProps} props - The props for the Card component
|
|
3096
3088
|
* @returns {ReactElement} Card component
|
|
3097
3089
|
*/
|
|
3098
|
-
const Card = ({ children, onClick, fullHeight = false,
|
|
3099
|
-
return (jsx("div", { className: cvaCard({ fullHeight,
|
|
3090
|
+
const Card = ({ children, onClick, fullHeight = false, onMouseEnter, onMouseLeave, className, "data-testid": dataTestId, ref, ...rest }) => {
|
|
3091
|
+
return (jsx("div", { className: cvaCard({ fullHeight, clickable: Boolean(onClick), className }), "data-card": true, "data-testid": dataTestId, onClick: onClick, onMouseEnter: onMouseEnter, onMouseLeave: onMouseLeave, ref: ref, role: ROLE_CARD, ...rest, children: children }));
|
|
3100
3092
|
};
|
|
3101
3093
|
Card.displayName = "Card";
|
|
3102
3094
|
|
|
@@ -12259,6 +12251,226 @@ const useSheet = (props) => {
|
|
|
12259
12251
|
}), [isOpen, state, variant, open, close, snap, floatingUi, onGeometryChange, onSnap, onClickHandle, onCloseGesture]);
|
|
12260
12252
|
};
|
|
12261
12253
|
|
|
12254
|
+
/**
|
|
12255
|
+
* Detects the current platform based on the user agent.
|
|
12256
|
+
*
|
|
12257
|
+
* @returns {Platform} The detected platform: "mac", "windows", or "linux"
|
|
12258
|
+
*/
|
|
12259
|
+
const getPlatform = () => {
|
|
12260
|
+
if (typeof navigator === "undefined") {
|
|
12261
|
+
// SSR default - most users are on Windows
|
|
12262
|
+
return "windows";
|
|
12263
|
+
}
|
|
12264
|
+
const ua = navigator.userAgent.toLowerCase();
|
|
12265
|
+
if (ua.includes("mac")) {
|
|
12266
|
+
return "mac";
|
|
12267
|
+
}
|
|
12268
|
+
if (ua.includes("linux")) {
|
|
12269
|
+
return "linux";
|
|
12270
|
+
}
|
|
12271
|
+
return "windows";
|
|
12272
|
+
};
|
|
12273
|
+
|
|
12274
|
+
/** Display order for modifiers: mod first, then alt, then shift */
|
|
12275
|
+
const MODIFIER_DISPLAY_ORDER = ["mod", "alt", "shift"];
|
|
12276
|
+
/** Labels for each modifier, mapped per platform */
|
|
12277
|
+
const MODIFIER_LABELS = {
|
|
12278
|
+
mod: { mac: "Cmd", other: "Ctrl" },
|
|
12279
|
+
alt: { mac: "Option", other: "Alt" },
|
|
12280
|
+
shift: { mac: "Shift", other: "Shift" },
|
|
12281
|
+
};
|
|
12282
|
+
/**
|
|
12283
|
+
* Maps a semantic modifier to a display label based on the current platform.
|
|
12284
|
+
*/
|
|
12285
|
+
const getModifierLabel = (mod) => {
|
|
12286
|
+
const labels = MODIFIER_LABELS[mod];
|
|
12287
|
+
return getPlatform() === "mac" ? labels.mac : labels.other;
|
|
12288
|
+
};
|
|
12289
|
+
/**
|
|
12290
|
+
* Maps a key to a more readable display label.
|
|
12291
|
+
*/
|
|
12292
|
+
const getKeyLabel = (key) => {
|
|
12293
|
+
const keyLabels = {
|
|
12294
|
+
arrowup: "↑",
|
|
12295
|
+
arrowdown: "↓",
|
|
12296
|
+
arrowleft: "←",
|
|
12297
|
+
arrowright: "→",
|
|
12298
|
+
enter: "Enter",
|
|
12299
|
+
escape: "Esc",
|
|
12300
|
+
tab: "Tab",
|
|
12301
|
+
space: "Space",
|
|
12302
|
+
backspace: "Backspace",
|
|
12303
|
+
delete: "Delete",
|
|
12304
|
+
home: "Home",
|
|
12305
|
+
end: "End",
|
|
12306
|
+
pageup: "Page Up",
|
|
12307
|
+
pagedown: "Page Down",
|
|
12308
|
+
};
|
|
12309
|
+
const lowerKey = key.toLowerCase();
|
|
12310
|
+
return keyLabels[lowerKey] ?? key.toUpperCase();
|
|
12311
|
+
};
|
|
12312
|
+
/**
|
|
12313
|
+
* Formats a shortcut definition into a human-readable label.
|
|
12314
|
+
*
|
|
12315
|
+
* The label is platform-aware:
|
|
12316
|
+
* - Mac: "Cmd + K", "Option + Shift + L"
|
|
12317
|
+
* - Windows/Linux: "Ctrl + K", "Alt + Shift + L"
|
|
12318
|
+
*
|
|
12319
|
+
* Accepts loosely typed input, like `formatShortcutKeys`, so keys no definition names (a lone modifier) get a label too.
|
|
12320
|
+
*
|
|
12321
|
+
* @param shortcut - The shortcut definition to format
|
|
12322
|
+
* @param shortcut.key - The key, e.g. "k" or "Escape"
|
|
12323
|
+
* @param shortcut.modifiers - "+"-joined semantic modifiers, e.g. "mod+shift"
|
|
12324
|
+
* @param separator - The separator between parts (default: " + ")
|
|
12325
|
+
* @returns {string} A formatted string like "Cmd + K" or "Ctrl + Shift + L"
|
|
12326
|
+
* @example
|
|
12327
|
+
* formatShortcutLabel({ key: "k", modifiers: "mod" })
|
|
12328
|
+
* // Mac: "Cmd + K"
|
|
12329
|
+
* // Windows: "Ctrl + K"
|
|
12330
|
+
* @example
|
|
12331
|
+
* formatShortcutLabel({ key: "l", modifiers: "mod+shift" })
|
|
12332
|
+
* // Mac: "Cmd + Shift + L"
|
|
12333
|
+
* // Windows: "Ctrl + Shift + L"
|
|
12334
|
+
* @example
|
|
12335
|
+
* formatShortcutLabel({ key: "Escape" })
|
|
12336
|
+
* // "Esc"
|
|
12337
|
+
*/
|
|
12338
|
+
const formatShortcutLabel = (shortcut, separator = " + ") => {
|
|
12339
|
+
// Parse modifier string and sort in display order (mod, alt, shift)
|
|
12340
|
+
const modifierSet = new Set(shortcut.modifiers?.split("+") ?? []);
|
|
12341
|
+
const sortedModifiers = MODIFIER_DISPLAY_ORDER.filter(mod => modifierSet.has(mod));
|
|
12342
|
+
const modLabels = sortedModifiers.map(getModifierLabel);
|
|
12343
|
+
const keyLabel = getKeyLabel(shortcut.key);
|
|
12344
|
+
return [...modLabels, keyLabel].join(separator);
|
|
12345
|
+
};
|
|
12346
|
+
const MODIFIER_SYMBOLS = {
|
|
12347
|
+
mod: { mac: "⌘", other: "Ctrl" },
|
|
12348
|
+
alt: { mac: "⌥", other: "Alt" },
|
|
12349
|
+
shift: { mac: "⇧", other: "Shift" },
|
|
12350
|
+
};
|
|
12351
|
+
const KEY_SYMBOLS = {
|
|
12352
|
+
arrowup: "↑",
|
|
12353
|
+
arrowdown: "↓",
|
|
12354
|
+
arrowleft: "←",
|
|
12355
|
+
arrowright: "→",
|
|
12356
|
+
enter: "↵",
|
|
12357
|
+
escape: "Esc",
|
|
12358
|
+
tab: "⇥",
|
|
12359
|
+
space: "Space",
|
|
12360
|
+
backspace: "⌫",
|
|
12361
|
+
delete: "Del",
|
|
12362
|
+
home: "Home",
|
|
12363
|
+
end: "End",
|
|
12364
|
+
pageup: "PgUp",
|
|
12365
|
+
pagedown: "PgDn",
|
|
12366
|
+
};
|
|
12367
|
+
const isSemanticModifier = (value) => value === "mod" || value === "alt" || value === "shift";
|
|
12368
|
+
/**
|
|
12369
|
+
* Formats a shortcut into the individual keycaps a user presses, using platform symbols.
|
|
12370
|
+
*
|
|
12371
|
+
* Accepts loosely typed input so shortcuts relayed from Iris app iframes can be formatted too.
|
|
12372
|
+
*
|
|
12373
|
+
* @param shortcut - The key and optional modifiers
|
|
12374
|
+
* @param shortcut.key - The key, e.g. "k" or "ArrowUp"
|
|
12375
|
+
* @param shortcut.modifiers - "+"-joined semantic modifiers, e.g. "mod+shift"
|
|
12376
|
+
* @returns {ReadonlyArray<string>} Keycaps in press order, e.g. ["⌘", "⇧", "L"] on Mac or ["Ctrl", "Shift", "L"] elsewhere
|
|
12377
|
+
* @example
|
|
12378
|
+
* formatShortcutKeys({ key: "k", modifiers: "mod" })
|
|
12379
|
+
* // Mac: ["⌘", "K"]
|
|
12380
|
+
* // Windows: ["Ctrl", "K"]
|
|
12381
|
+
*/
|
|
12382
|
+
const formatShortcutKeys = (shortcut) => {
|
|
12383
|
+
const platform = getPlatform() === "mac" ? "mac" : "other";
|
|
12384
|
+
const modifierSet = new Set((shortcut.modifiers?.split("+") ?? []).filter(isSemanticModifier));
|
|
12385
|
+
const modifiers = MODIFIER_DISPLAY_ORDER.filter(mod => modifierSet.has(mod)).map(mod => MODIFIER_SYMBOLS[mod][platform]);
|
|
12386
|
+
const key = KEY_SYMBOLS[shortcut.key.toLowerCase()] ?? shortcut.key.toUpperCase();
|
|
12387
|
+
return [...modifiers, key];
|
|
12388
|
+
};
|
|
12389
|
+
|
|
12390
|
+
const cvaShortcutKeys = cva({ base: ["inline-flex", "items-center", "gap-1"] });
|
|
12391
|
+
const cvaShortcutKeysKeycap = cva({
|
|
12392
|
+
base: [
|
|
12393
|
+
"inline-flex",
|
|
12394
|
+
"items-center",
|
|
12395
|
+
"justify-center",
|
|
12396
|
+
"font-sans",
|
|
12397
|
+
"font-medium",
|
|
12398
|
+
"leading-none",
|
|
12399
|
+
"transition-colors",
|
|
12400
|
+
"duration-150",
|
|
12401
|
+
"motion-reduce:transition-none",
|
|
12402
|
+
],
|
|
12403
|
+
variants: {
|
|
12404
|
+
size: {
|
|
12405
|
+
small: ["h-4.5", "min-w-4.5", "rounded-sm", "bg-neutral-200", "px-1", "text-xs", "text-neutral-500"],
|
|
12406
|
+
medium: [
|
|
12407
|
+
"h-6",
|
|
12408
|
+
"min-w-6",
|
|
12409
|
+
"rounded-md",
|
|
12410
|
+
"bg-neutral-100",
|
|
12411
|
+
"px-1.5",
|
|
12412
|
+
"text-xs",
|
|
12413
|
+
"text-neutral-600",
|
|
12414
|
+
"ring-1",
|
|
12415
|
+
"ring-inset",
|
|
12416
|
+
"ring-neutral-200",
|
|
12417
|
+
],
|
|
12418
|
+
},
|
|
12419
|
+
pressed: {
|
|
12420
|
+
true: ["bg-primary-600", "text-white", "ring-primary-600"],
|
|
12421
|
+
false: [],
|
|
12422
|
+
},
|
|
12423
|
+
},
|
|
12424
|
+
defaultVariants: { size: "medium", pressed: false },
|
|
12425
|
+
});
|
|
12426
|
+
const cvaShortcutKeysTitle = cva({
|
|
12427
|
+
base: ["transition-colors", "duration-150", "motion-reduce:transition-none"],
|
|
12428
|
+
variants: {
|
|
12429
|
+
size: {
|
|
12430
|
+
small: ["text-xs", "text-neutral-400"],
|
|
12431
|
+
medium: ["text-sm", "text-neutral-500"],
|
|
12432
|
+
},
|
|
12433
|
+
},
|
|
12434
|
+
defaultVariants: { size: "medium" },
|
|
12435
|
+
});
|
|
12436
|
+
|
|
12437
|
+
const toFormatted = (shortcut) => "keys" in shortcut ? shortcut : { keys: formatShortcutKeys(shortcut), label: formatShortcutLabel(shortcut) };
|
|
12438
|
+
/**
|
|
12439
|
+
* Shows the keys of a keyboard shortcut as keycaps, with the platform's symbols: ⌘ K on Mac, Ctrl K elsewhere.
|
|
12440
|
+
* Optionally followed by a title saying what the shortcut does.
|
|
12441
|
+
*
|
|
12442
|
+
* It only displays a shortcut. Use `useKeyboardShortcut` to make it work (or `useAction`, to also register it
|
|
12443
|
+
* as an action with the host), and pass what it returns here, so the keys shown are always the keys that run it.
|
|
12444
|
+
*
|
|
12445
|
+
* _**Do use** it next to the control a shortcut runs, in tooltips, and in footers listing the keys that work right now._
|
|
12446
|
+
*
|
|
12447
|
+
* _**Do not use** it for shortcuts that aren't active where it's shown._
|
|
12448
|
+
*
|
|
12449
|
+
* @example Show the shortcut that runs an action
|
|
12450
|
+
* ```tsx
|
|
12451
|
+
* import { Button, ShortcutKeys, useKeyboardShortcut } from "@trackunit/react-components";
|
|
12452
|
+
*
|
|
12453
|
+
* const ExportButton = ({ onExport }: { onExport: () => void }) => {
|
|
12454
|
+
* const shortcut = useKeyboardShortcut({ key: "e", modifiers: "mod" }, { onTrigger: onExport, preventDefault: "always" });
|
|
12455
|
+
* return (
|
|
12456
|
+
* <Button onClick={onExport} suffix={<ShortcutKeys shortcut={shortcut} size="small" />}>
|
|
12457
|
+
* Export
|
|
12458
|
+
* </Button>
|
|
12459
|
+
* );
|
|
12460
|
+
* };
|
|
12461
|
+
* ```
|
|
12462
|
+
* @example A key hint with a title, as in a footer
|
|
12463
|
+
* ```tsx
|
|
12464
|
+
* <ShortcutKeys shortcut={{ key: "Enter" }} size="small" title="Open" />
|
|
12465
|
+
* ```
|
|
12466
|
+
* @param {ShortcutKeysProps} props - The props for the ShortcutKeys component
|
|
12467
|
+
* @returns {ReactElement} ShortcutKeys component
|
|
12468
|
+
*/
|
|
12469
|
+
const ShortcutKeys = ({ shortcut, title, size = "medium", pressed = false, className, style, ref, "data-testid": dataTestId, }) => {
|
|
12470
|
+
const { keys, label } = toFormatted(shortcut);
|
|
12471
|
+
return (jsxs("span", { className: cvaShortcutKeys({ className }), "data-testid": dataTestId, ref: ref, style: style, children: [jsx("kbd", { "aria-hidden": label !== undefined ? true : undefined, className: cvaShortcutKeys(), "data-testid": dataTestId ? `${dataTestId}-keys` : undefined, children: keys.map((key, index) => (jsx("kbd", { className: cvaShortcutKeysKeycap({ size, pressed }), "data-pressed": pressed ? true : undefined, "data-testid": dataTestId ? `${dataTestId}-key` : undefined, children: key }, `${key}-${index}`))) }), label !== undefined ? jsx("span", { className: "sr-only", children: label }) : null, title !== undefined && title !== null ? jsx("span", { className: cvaShortcutKeysTitle({ size }), children: title }) : null] }));
|
|
12472
|
+
};
|
|
12473
|
+
|
|
12262
12474
|
const cvaSidebar = cva({ base: ["apply", "grid", "grid-cols-fr-min", "items-center"] });
|
|
12263
12475
|
const cvaSidebarChildContainer = cva({
|
|
12264
12476
|
base: ["apply", "flex", "overflow-hidden", "gap-2", "p-1", "max-w-full"],
|
|
@@ -13800,471 +14012,418 @@ const useStripForeignIdentityHash = () => {
|
|
|
13800
14012
|
}, [decode]);
|
|
13801
14013
|
};
|
|
13802
14014
|
|
|
13803
|
-
const
|
|
13804
|
-
|
|
13805
|
-
const
|
|
14015
|
+
const MAX_SERVER_TOOL_LENGTH = 128;
|
|
14016
|
+
/** The strictest reading: changes data, may delete or overwrite it, and has no known tool. */
|
|
14017
|
+
const UNKNOWN_ACTION_AI = { hints: { readOnlyHint: false, destructiveHint: true }, serverTool: null };
|
|
14018
|
+
const booleanField = (value, field) => {
|
|
14019
|
+
const fieldValue = Reflect.get(value, field);
|
|
14020
|
+
return typeof fieldValue === "boolean" ? fieldValue : undefined;
|
|
14021
|
+
};
|
|
13806
14022
|
/**
|
|
13807
|
-
*
|
|
13808
|
-
*
|
|
14023
|
+
* Reads an `ai` that can't be trusted to match `ActionAi`: from an untyped caller (a plain-JS Iris
|
|
14024
|
+
* app) or relayed from an iframe. Anything missing or malformed reads the strictest way: only
|
|
14025
|
+
* `readOnlyHint: true` makes an action read-only, and only `destructiveHint: false` makes one that
|
|
14026
|
+
* changes data non-destructive, so a hint can never loosen what's left out. A `serverTool` that
|
|
14027
|
+
* isn't a short string counts as none. Sets `destructiveHint` and `serverTool` on an action that
|
|
14028
|
+
* changes data, so readers don't have to apply the defaults.
|
|
13809
14029
|
*
|
|
13810
|
-
*
|
|
13811
|
-
* scroll position at both ends and triggers the appropriate pagination
|
|
13812
|
-
* direction.
|
|
14030
|
+
* @internal
|
|
13813
14031
|
*/
|
|
13814
|
-
const
|
|
13815
|
-
|
|
13816
|
-
|
|
13817
|
-
|
|
13818
|
-
|
|
13819
|
-
|
|
13820
|
-
|
|
13821
|
-
|
|
13822
|
-
|
|
13823
|
-
|
|
13824
|
-
|
|
13825
|
-
|
|
13826
|
-
|
|
14032
|
+
const parseActionAi = (value) => {
|
|
14033
|
+
if (typeof value !== "object" || value === null) {
|
|
14034
|
+
return UNKNOWN_ACTION_AI;
|
|
14035
|
+
}
|
|
14036
|
+
const hints = Reflect.get(value, "hints");
|
|
14037
|
+
if (typeof hints !== "object" || hints === null) {
|
|
14038
|
+
return UNKNOWN_ACTION_AI;
|
|
14039
|
+
}
|
|
14040
|
+
const rawServerTool = Reflect.get(value, "serverTool");
|
|
14041
|
+
const serverTool = typeof rawServerTool === "string" && rawServerTool.length > 0 && rawServerTool.length <= MAX_SERVER_TOOL_LENGTH
|
|
14042
|
+
? rawServerTool
|
|
14043
|
+
: undefined;
|
|
14044
|
+
const openWorldHint = booleanField(hints, "openWorldHint");
|
|
14045
|
+
const openWorld = openWorldHint === undefined ? {} : { openWorldHint };
|
|
14046
|
+
if (Reflect.get(hints, "readOnlyHint") === true) {
|
|
14047
|
+
return { hints: { readOnlyHint: true, ...openWorld }, ...(serverTool === undefined ? {} : { serverTool }) };
|
|
14048
|
+
}
|
|
14049
|
+
const idempotentHint = booleanField(hints, "idempotentHint");
|
|
14050
|
+
return {
|
|
14051
|
+
hints: {
|
|
14052
|
+
readOnlyHint: false,
|
|
14053
|
+
destructiveHint: booleanField(hints, "destructiveHint") !== false,
|
|
14054
|
+
...(idempotentHint === undefined ? {} : { idempotentHint }),
|
|
14055
|
+
...openWorld,
|
|
14056
|
+
},
|
|
14057
|
+
serverTool: serverTool ?? null,
|
|
14058
|
+
...(Reflect.get(value, "alwaysAllow") === false ? { alwaysAllow: false } : {}),
|
|
14059
|
+
};
|
|
14060
|
+
};
|
|
14061
|
+
/**
|
|
14062
|
+
* DOM event fired on `window` inside an Iris app iframe whenever its actions change, with
|
|
14063
|
+
* `detail: { actions: Array<SerializedAction> }`. The iris-app-loader relays the list to the host.
|
|
14064
|
+
*
|
|
14065
|
+
* @internal
|
|
14066
|
+
*/
|
|
14067
|
+
const ACTIONS_CHANGED_EVENT = "trackunit:actions-changed";
|
|
14068
|
+
/**
|
|
14069
|
+
* DOM event the iris-app-loader fires on `window` inside an Iris app iframe, with `detail: { id }`,
|
|
14070
|
+
* when the host runs one of the app's actions.
|
|
14071
|
+
*
|
|
14072
|
+
* @internal
|
|
14073
|
+
*/
|
|
14074
|
+
const INVOKE_ACTION_EVENT = "trackunit:invoke-action";
|
|
14075
|
+
const ACTION_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_:-]{0,79}$/;
|
|
14076
|
+
/**
|
|
14077
|
+
* Whether `id` can identify an action: 1 to 80 ASCII letters, digits, `-`, `_` or `:`, starting
|
|
14078
|
+
* with a letter or digit. Prefer kebab-case, like `create-group`, and `:` to compose one from a
|
|
14079
|
+
* list, like `map-style:satellite`. `.` and `/` are left out so ids registered in the host never
|
|
14080
|
+
* clash with the `<app id>/<extension id>.<action id>` the host gives relayed actions.
|
|
14081
|
+
*/
|
|
14082
|
+
const isValidActionId = (id) => typeof id === "string" && ACTION_ID_PATTERN.test(id);
|
|
14083
|
+
const EMPTY = [];
|
|
14084
|
+
// Shared through `window` so every copy of react-components on the page (Module
|
|
14085
|
+
// Federation can load several versions) feeds the same registry.
|
|
14086
|
+
const REGISTRY_KEY = Symbol.for("@trackunit/react-components/action-registry");
|
|
14087
|
+
const isInIframe = () => window.parent !== window;
|
|
14088
|
+
/** Fills in whatever fields `shared` lacks, on the shared object itself so every copy sees them. */
|
|
14089
|
+
const completeRegistry = (shared) => Object.assign(shared, {
|
|
14090
|
+
local: shared.local ?? [],
|
|
14091
|
+
owners: shared.owners ?? new WeakMap(),
|
|
14092
|
+
remote: shared.remote ?? new Map(),
|
|
14093
|
+
listeners: shared.listeners ?? new Set(),
|
|
14094
|
+
snapshot: shared.snapshot ?? EMPTY,
|
|
14095
|
+
publishScheduled: shared.publishScheduled ?? false,
|
|
14096
|
+
issueReporter: shared.issueReporter,
|
|
14097
|
+
reportedDuplicateIds: shared.reportedDuplicateIds ?? new Set(),
|
|
14098
|
+
pendingIssues: shared.pendingIssues ?? [],
|
|
14099
|
+
});
|
|
14100
|
+
let lastRegistry;
|
|
14101
|
+
const getRegistry = () => {
|
|
14102
|
+
const target = window;
|
|
14103
|
+
const existing = target[REGISTRY_KEY];
|
|
14104
|
+
if (lastRegistry !== undefined && existing === lastRegistry) {
|
|
14105
|
+
return lastRegistry;
|
|
14106
|
+
}
|
|
14107
|
+
if (existing) {
|
|
14108
|
+
lastRegistry = completeRegistry(existing);
|
|
14109
|
+
return lastRegistry;
|
|
14110
|
+
}
|
|
14111
|
+
const created = completeRegistry({});
|
|
14112
|
+
target[REGISTRY_KEY] = created;
|
|
14113
|
+
lastRegistry = created;
|
|
14114
|
+
if (isInIframe()) {
|
|
14115
|
+
// Only ids this window registered can run, so a forged id is a no-op.
|
|
14116
|
+
window.addEventListener(INVOKE_ACTION_EVENT, event => {
|
|
14117
|
+
const detail = event instanceof CustomEvent ? event.detail : undefined;
|
|
14118
|
+
if (typeof detail === "object" && detail !== null && "id" in detail && typeof detail.id === "string") {
|
|
14119
|
+
const { id } = detail;
|
|
14120
|
+
created.local.findLast(action => action.id === id)?.perform();
|
|
14121
|
+
}
|
|
14122
|
+
});
|
|
14123
|
+
}
|
|
14124
|
+
return created;
|
|
14125
|
+
};
|
|
14126
|
+
/** One action per id: the one registered last, where it was registered. */
|
|
14127
|
+
const latestPerId = (actions) => {
|
|
14128
|
+
const lastIndex = new Map(actions.map((action, index) => [action.id, index]));
|
|
14129
|
+
return actions.filter((action, index) => lastIndex.get(action.id) === index);
|
|
14130
|
+
};
|
|
14131
|
+
/**
|
|
14132
|
+
* Says in the console why an action isn't listed the way it was registered, which nothing else on the page would.
|
|
14133
|
+
*
|
|
14134
|
+
* @internal
|
|
14135
|
+
*/
|
|
14136
|
+
const logToDevelopers = (level, message) => {
|
|
14137
|
+
// eslint-disable-next-line no-console -- Development warning for two actions sharing an id, and why an action isn't listed at all
|
|
14138
|
+
console[level](message);
|
|
14139
|
+
};
|
|
14140
|
+
/** Whether the browser can copy `value` across frames as it is: strings, numbers, booleans, and arrays and plain objects of them. */
|
|
14141
|
+
const isPlainData = (value) => {
|
|
14142
|
+
if (value === undefined || value === null || ["string", "number", "boolean"].includes(typeof value)) {
|
|
14143
|
+
return true;
|
|
14144
|
+
}
|
|
14145
|
+
if (Array.isArray(value)) {
|
|
14146
|
+
return value.every(isPlainData);
|
|
14147
|
+
}
|
|
14148
|
+
return (typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype && Object.values(value).every(isPlainData));
|
|
14149
|
+
};
|
|
14150
|
+
const plainOrUndefined = (value) => (isPlainData(value) ? value : undefined);
|
|
14151
|
+
const OPTIONAL_FIELDS = [
|
|
14152
|
+
"subtitle",
|
|
14153
|
+
"group",
|
|
14154
|
+
"keywords",
|
|
14155
|
+
"icon",
|
|
14156
|
+
"submenu",
|
|
14157
|
+
"label",
|
|
14158
|
+
"checked",
|
|
14159
|
+
"shortcut",
|
|
14160
|
+
"scoped",
|
|
14161
|
+
];
|
|
14162
|
+
/**
|
|
14163
|
+
* What crosses to the iris-app-loader. A plain-JS app can register anything, like a React element
|
|
14164
|
+
* as `icon`, which would make the whole list fail to send, so a field that isn't plain data is left
|
|
14165
|
+
* out, and an action whose title or description isn't a string isn't sent. Development says which.
|
|
14166
|
+
*/
|
|
14167
|
+
const serialize = (action) => {
|
|
14168
|
+
const { id, ai, hiddenFromAssistantBecause } = action;
|
|
14169
|
+
const title = action.title;
|
|
14170
|
+
const description = action.description;
|
|
14171
|
+
const inDevelopment = process.env.NODE_ENV !== "production";
|
|
14172
|
+
if (typeof title !== "string" || typeof description !== "string") {
|
|
14173
|
+
if (inDevelopment) {
|
|
14174
|
+
logToDevelopers("error", `[useAction] "${id}" isn't sent to the host: its title and description must be strings.`);
|
|
13827
14175
|
}
|
|
13828
|
-
|
|
13829
|
-
|
|
13830
|
-
|
|
13831
|
-
|
|
13832
|
-
|
|
13833
|
-
|
|
14176
|
+
return [];
|
|
14177
|
+
}
|
|
14178
|
+
const dropped = OPTIONAL_FIELDS.filter(field => !isPlainData(action[field]));
|
|
14179
|
+
if (dropped.length > 0 && inDevelopment) {
|
|
14180
|
+
logToDevelopers("error", `[useAction] "${id}" is sent to the host without its ${dropped.join(", ")}: the browser can't copy a React element or a function to it. Give icons and titles as strings.`);
|
|
14181
|
+
}
|
|
14182
|
+
return [
|
|
14183
|
+
{
|
|
14184
|
+
id,
|
|
14185
|
+
title,
|
|
14186
|
+
description,
|
|
14187
|
+
ai,
|
|
14188
|
+
subtitle: plainOrUndefined(action.subtitle),
|
|
14189
|
+
group: plainOrUndefined(action.group),
|
|
14190
|
+
keywords: plainOrUndefined(action.keywords),
|
|
14191
|
+
icon: plainOrUndefined(action.icon),
|
|
14192
|
+
submenu: plainOrUndefined(action.submenu),
|
|
14193
|
+
label: plainOrUndefined(action.label),
|
|
14194
|
+
checked: plainOrUndefined(action.checked),
|
|
14195
|
+
shortcut: plainOrUndefined(action.shortcut),
|
|
14196
|
+
scoped: plainOrUndefined(action.scoped),
|
|
14197
|
+
hiddenFromAssistantBecause,
|
|
14198
|
+
},
|
|
14199
|
+
];
|
|
14200
|
+
};
|
|
14201
|
+
const publishToParent = (registry) => {
|
|
14202
|
+
if (!isInIframe() || registry.publishScheduled) {
|
|
14203
|
+
return;
|
|
14204
|
+
}
|
|
14205
|
+
// Batch registrations from the same render so the host gets one message per change.
|
|
14206
|
+
registry.publishScheduled = true;
|
|
14207
|
+
queueMicrotask(() => {
|
|
14208
|
+
registry.publishScheduled = false;
|
|
14209
|
+
const actions = latestPerId(registry.local).flatMap(serialize);
|
|
14210
|
+
window.dispatchEvent(new CustomEvent(ACTIONS_CHANGED_EVENT, { detail: { actions } }));
|
|
14211
|
+
});
|
|
14212
|
+
};
|
|
14213
|
+
/**
|
|
14214
|
+
* Publishes one action per id. Of two registrations with the same id (see `checkForDuplicate`), the
|
|
14215
|
+
* one registered last is listed and run, in its place in registration order; when it unregisters,
|
|
14216
|
+
* the other is listed again. Relayed actions follow the same rule, so of two iframes of the same extension,
|
|
14217
|
+
* the one that started relaying last is listed, and running it reaches the iframe that relayed it.
|
|
14218
|
+
*/
|
|
14219
|
+
const notify = (registry) => {
|
|
14220
|
+
registry.snapshot = latestPerId([...registry.local, ...[...registry.remote.values()].flat()]);
|
|
14221
|
+
registry.listeners.forEach(listener => listener());
|
|
14222
|
+
publishToParent(registry);
|
|
14223
|
+
};
|
|
14224
|
+
const describeOwner = (owner) => owner ?? "\n (unknown component)";
|
|
14225
|
+
/**
|
|
14226
|
+
* Two registrations in this window with the same id at once: the later one hides the earlier, even
|
|
14227
|
+
* with the same title. Development warns every time, naming both components; production tells
|
|
14228
|
+
* the host's reporter, once per id per page load. Relayed actions aren't checked: their ids are
|
|
14229
|
+
* prefixed per extension, and two iframes of the same extension relaying the same id is expected.
|
|
14230
|
+
*/
|
|
14231
|
+
const checkForDuplicate = (registry, action, owner) => {
|
|
14232
|
+
const earlier = registry.local.findLast(existing => existing.id === action.id);
|
|
14233
|
+
if (earlier === undefined) {
|
|
14234
|
+
return;
|
|
14235
|
+
}
|
|
14236
|
+
if (process.env.NODE_ENV !== "production") {
|
|
14237
|
+
logToDevelopers("warn", `[useAction] The id "${action.id}" is registered twice, by "${earlier.title}" and "${action.title}". Only the one registered last counts. Give each action its own id, or register it from one component only.` +
|
|
14238
|
+
`\n\nRegistered first by:${describeOwner(registry.owners.get(earlier))}` +
|
|
14239
|
+
`\n\nRegistered last by:${describeOwner(owner)}`);
|
|
14240
|
+
return;
|
|
14241
|
+
}
|
|
14242
|
+
if (registry.reportedDuplicateIds.has(action.id)) {
|
|
14243
|
+
return;
|
|
14244
|
+
}
|
|
14245
|
+
registry.reportedDuplicateIds.add(action.id);
|
|
14246
|
+
const issue = { kind: "duplicate-action-id", id: action.id, titles: [earlier.title, action.title] };
|
|
14247
|
+
if (registry.issueReporter === undefined) {
|
|
14248
|
+
registry.pendingIssues.push(issue);
|
|
14249
|
+
}
|
|
14250
|
+
else {
|
|
14251
|
+
registry.issueReporter(issue);
|
|
14252
|
+
}
|
|
14253
|
+
};
|
|
14254
|
+
const NO_REASON_GIVEN = "No reason given";
|
|
14255
|
+
/**
|
|
14256
|
+
* Reads `hiddenFromAssistantBecause` from an untyped caller (a plain-JS Iris app). Anything set,
|
|
14257
|
+
* even malformed, keeps the action hidden.
|
|
14258
|
+
*/
|
|
14259
|
+
const parseHiddenReason = (value) => {
|
|
14260
|
+
if (value === undefined) {
|
|
14261
|
+
return undefined;
|
|
14262
|
+
}
|
|
14263
|
+
return typeof value === "string" && value.length > 0 ? value : NO_REASON_GIVEN;
|
|
14264
|
+
};
|
|
14265
|
+
/**
|
|
14266
|
+
* Adds a list of actions to the registry, in order, and tells listeners once. Used by useActions.
|
|
14267
|
+
* Each action is registered as `registerAction` would; one with an id `isValidActionId` rejects
|
|
14268
|
+
* isn't registered, and an id repeated within the list counts as a duplicate.
|
|
14269
|
+
*
|
|
14270
|
+
* - `owner`: who registers them, e.g. the owner stack React's `captureOwnerStack()` gives during
|
|
14271
|
+
* render, named in the development warning for a duplicate id. Never listed.
|
|
14272
|
+
*
|
|
14273
|
+
* @internal
|
|
14274
|
+
* @returns {() => void} Unregister function, which removes them all and tells listeners once
|
|
14275
|
+
*/
|
|
14276
|
+
const registerActions = (actions, owner) => {
|
|
14277
|
+
const registry = getRegistry();
|
|
14278
|
+
const entries = actions.flatMap(action => {
|
|
14279
|
+
if (!isValidActionId(action.id)) {
|
|
14280
|
+
logToDevelopers("error", `[useAction] "${action.title}" isn't registered: its id ${JSON.stringify(action.id)} must be 1 to 80 letters, digits, "-", "_" or ":", starting with a letter or digit.`);
|
|
14281
|
+
return [];
|
|
13834
14282
|
}
|
|
13835
|
-
|
|
13836
|
-
|
|
13837
|
-
|
|
13838
|
-
|
|
13839
|
-
|
|
13840
|
-
|
|
13841
|
-
|
|
13842
|
-
|
|
13843
|
-
|
|
14283
|
+
checkForDuplicate(registry, action, owner);
|
|
14284
|
+
const hiddenFromAssistantBecause = parseHiddenReason(action.hiddenFromAssistantBecause);
|
|
14285
|
+
const entry = {
|
|
14286
|
+
...action,
|
|
14287
|
+
ai: parseActionAi(action.ai),
|
|
14288
|
+
...(hiddenFromAssistantBecause === undefined ? {} : { hiddenFromAssistantBecause }),
|
|
14289
|
+
};
|
|
14290
|
+
registry.local.push(entry);
|
|
14291
|
+
if (owner !== undefined) {
|
|
14292
|
+
registry.owners.set(entry, owner);
|
|
13844
14293
|
}
|
|
13845
|
-
|
|
13846
|
-
}, [onChange, tryLoadNextPage]);
|
|
13847
|
-
const handleEstimateSize = useCallback((index) => estimateSize?.(index) ?? DEFAULT_ROW_HEIGHT, [estimateSize]);
|
|
13848
|
-
// eslint-plugin-react-hooks hardcodes `useVirtualizer` as a known-incompatible
|
|
13849
|
-
// API (its returned functions can't be memoized), so this warning is emitted
|
|
13850
|
-
// regardless of the installed version. The React Compiler already auto-skips
|
|
13851
|
-
// memoizing this hook, so the behaviour is safe.
|
|
13852
|
-
// eslint-disable-next-line react-hooks/incompatible-library
|
|
13853
|
-
const rowVirtualizer = useVirtualizer({
|
|
13854
|
-
count,
|
|
13855
|
-
getScrollElement: () => scrollElementRef.current,
|
|
13856
|
-
estimateSize: handleEstimateSize,
|
|
13857
|
-
overscan: overscan ?? OVERSCAN,
|
|
13858
|
-
onChange: handleChange,
|
|
13859
|
-
getItemKey,
|
|
13860
|
-
useAnimationFrameWithResizeObserver: true,
|
|
13861
|
-
// Let the virtualizer write item positions and container size straight to
|
|
13862
|
-
// the DOM, only re-rendering when the visible index range changes. This
|
|
13863
|
-
// removes the imperative transform/height races that made scrolling jumpy.
|
|
13864
|
-
directDomUpdates: true,
|
|
13865
|
-
directDomUpdatesMode: "transform",
|
|
13866
|
-
useFlushSync: false,
|
|
14294
|
+
return [entry];
|
|
13867
14295
|
});
|
|
13868
|
-
|
|
13869
|
-
|
|
13870
|
-
|
|
13871
|
-
|
|
13872
|
-
|
|
13873
|
-
|
|
13874
|
-
|
|
13875
|
-
|
|
13876
|
-
|
|
13877
|
-
if (isLoadingBackwardRef.current && !pagination.isLoading && count > previousCount) {
|
|
13878
|
-
if (container) {
|
|
13879
|
-
const estimatedRowHeight = estimateSize?.(0) ?? DEFAULT_ROW_HEIGHT;
|
|
13880
|
-
container.scrollTop += (count - previousCount) * estimatedRowHeight;
|
|
14296
|
+
if (entries.length === 0) {
|
|
14297
|
+
return () => undefined;
|
|
14298
|
+
}
|
|
14299
|
+
notify(registry);
|
|
14300
|
+
return () => {
|
|
14301
|
+
const removed = entries.filter(entry => {
|
|
14302
|
+
const index = registry.local.indexOf(entry);
|
|
14303
|
+
if (index === -1) {
|
|
14304
|
+
return false;
|
|
13881
14305
|
}
|
|
13882
|
-
|
|
13883
|
-
|
|
13884
|
-
|
|
13885
|
-
|
|
13886
|
-
|
|
13887
|
-
}, [count, pagination.isLoading, scrollElementRef, estimateSize]);
|
|
13888
|
-
// Reset scroll to top when pagination is reset (e.g. new search).
|
|
13889
|
-
// Keyed on resetCount rather than pageInfo: a forward page without pageInfo
|
|
13890
|
-
// also clears endCursor, and must not move the user back to the top.
|
|
13891
|
-
useEffect(() => {
|
|
13892
|
-
if (pagination.resetCount === lastResetCountRef.current) {
|
|
13893
|
-
return;
|
|
13894
|
-
}
|
|
13895
|
-
lastResetCountRef.current = pagination.resetCount;
|
|
13896
|
-
isLoadingBackwardRef.current = false;
|
|
13897
|
-
const container = scrollElementRef.current;
|
|
13898
|
-
if (container) {
|
|
13899
|
-
container.scrollTop = 0;
|
|
13900
|
-
}
|
|
13901
|
-
}, [pagination.resetCount, scrollElementRef]);
|
|
13902
|
-
// Forward loading: scroll reached bottom or insufficient content
|
|
13903
|
-
useEffect(() => {
|
|
13904
|
-
tryLoadNextPage(rowVirtualizer);
|
|
13905
|
-
}, [tryLoadNextPage, rowVirtualizer, virtualItems, count, pagination.pageInfo?.hasNextPage, pagination.isLoading]);
|
|
13906
|
-
// Backward loading: fires when the scroll container is at the very top.
|
|
13907
|
-
// Uses scrollTop instead of virtualItems[0].index because after data
|
|
13908
|
-
// prepends the scroll-offset effect adjusts scrollTop away from 0,
|
|
13909
|
-
// which correctly prevents re-triggering. virtualItems[0].index would
|
|
13910
|
-
// still be 0 (overscan always renders from the start) causing a loop.
|
|
13911
|
-
useEffect(() => {
|
|
13912
|
-
if (skip || !pagination.pageInfo?.hasPreviousPage || pagination.isLoading) {
|
|
13913
|
-
return;
|
|
13914
|
-
}
|
|
13915
|
-
const container = scrollElementRef.current;
|
|
13916
|
-
if (!container || container.scrollTop !== 0) {
|
|
13917
|
-
return;
|
|
13918
|
-
}
|
|
13919
|
-
isLoadingBackwardRef.current = true;
|
|
13920
|
-
pagination.previousPage();
|
|
13921
|
-
}, [
|
|
13922
|
-
skip,
|
|
13923
|
-
pagination.pageInfo?.hasPreviousPage,
|
|
13924
|
-
pagination.previousPage,
|
|
13925
|
-
pagination.isLoading,
|
|
13926
|
-
pagination,
|
|
13927
|
-
scrollElementRef,
|
|
13928
|
-
virtualItems,
|
|
13929
|
-
]);
|
|
13930
|
-
return rowVirtualizer;
|
|
13931
|
-
};
|
|
13932
|
-
|
|
13933
|
-
/**
|
|
13934
|
-
* Custom hook to handle click outside events.
|
|
13935
|
-
*
|
|
13936
|
-
* @param {RefObject<HTMLElement> | Array<RefObject<HTMLElement>>} el - The reference(s) to the element(s) to watch for click outside events.
|
|
13937
|
-
* @param {object} [options={}] - Configuration options.
|
|
13938
|
-
* @param {Function} [options.onClick] - The event handler for the click outside event.
|
|
13939
|
-
* @param {boolean} [options.active=true] - Whether the click outside event listener should be active.
|
|
13940
|
-
*/
|
|
13941
|
-
const useClickOutside = (el, options) => {
|
|
13942
|
-
const els = Array.isArray(el) ? el : [el];
|
|
13943
|
-
const active = options.active !== undefined ? options.active : true;
|
|
13944
|
-
const handler = (ev) => {
|
|
13945
|
-
// eslint-disable-next-line @trackunit/no-typescript-assertion
|
|
13946
|
-
const target = ev.target;
|
|
13947
|
-
if (els.every(ref => !ref.current || !ref.current.contains(target))) {
|
|
13948
|
-
options.onClick(ev);
|
|
14306
|
+
registry.local.splice(index, 1);
|
|
14307
|
+
return true;
|
|
14308
|
+
});
|
|
14309
|
+
if (removed.length > 0) {
|
|
14310
|
+
notify(registry);
|
|
13949
14311
|
}
|
|
13950
14312
|
};
|
|
13951
|
-
const cleanup = () => window.removeEventListener("click", handler);
|
|
13952
|
-
useEffect(() => {
|
|
13953
|
-
if (active) {
|
|
13954
|
-
window.addEventListener("click", handler);
|
|
13955
|
-
}
|
|
13956
|
-
else {
|
|
13957
|
-
cleanup();
|
|
13958
|
-
}
|
|
13959
|
-
return cleanup;
|
|
13960
|
-
});
|
|
13961
|
-
};
|
|
13962
|
-
|
|
13963
|
-
/**
|
|
13964
|
-
* Maps size keys to their corresponding state property names.
|
|
13965
|
-
*/
|
|
13966
|
-
const breakpointPropsMap = {
|
|
13967
|
-
xs: "isXs",
|
|
13968
|
-
sm: "isSm",
|
|
13969
|
-
md: "isMd",
|
|
13970
|
-
lg: "isLg",
|
|
13971
|
-
xl: "isXl",
|
|
13972
|
-
"2xl": "is2xl",
|
|
13973
|
-
"3xl": "is3xl",
|
|
13974
14313
|
};
|
|
13975
14314
|
/**
|
|
13976
|
-
*
|
|
14315
|
+
* Adds an action to the registry. Used by useAction. An action with an id `isValidActionId`
|
|
14316
|
+
* rejects isn't registered.
|
|
14317
|
+
*
|
|
14318
|
+
* - `owner`: who registers it, e.g. the owner stack React's `captureOwnerStack()` gives during
|
|
14319
|
+
* render, named in the development warning for a duplicate id. Never listed.
|
|
14320
|
+
*
|
|
14321
|
+
* @internal
|
|
14322
|
+
* @returns {() => void} Unregister function
|
|
13977
14323
|
*/
|
|
13978
|
-
const
|
|
13979
|
-
isXs: false,
|
|
13980
|
-
isSm: false,
|
|
13981
|
-
isMd: false,
|
|
13982
|
-
isLg: false,
|
|
13983
|
-
isXl: false,
|
|
13984
|
-
is2xl: false,
|
|
13985
|
-
is3xl: false,
|
|
13986
|
-
};
|
|
14324
|
+
const registerAction = (action, owner) => registerActions([action], owner);
|
|
13987
14325
|
/**
|
|
13988
|
-
*
|
|
14326
|
+
* Sets what's told, in production, about actions registered wrongly, like two with the same id at
|
|
14327
|
+
* once. The host plugs in its error reporting; issues found before it's set are kept, one per id,
|
|
14328
|
+
* and told to it when it is. Shared through `window` with the registry, so it hears from every
|
|
14329
|
+
* copy of react-components on the page. Pass `undefined` to unset it.
|
|
14330
|
+
*
|
|
14331
|
+
* @internal
|
|
13989
14332
|
*/
|
|
13990
|
-
const
|
|
13991
|
-
|
|
13992
|
-
|
|
13993
|
-
|
|
13994
|
-
|
|
14333
|
+
const setActionIssueReporter = (reporter) => {
|
|
14334
|
+
const registry = getRegistry();
|
|
14335
|
+
registry.issueReporter = reporter;
|
|
14336
|
+
if (reporter !== undefined) {
|
|
14337
|
+
registry.pendingIssues.splice(0).forEach(issue => reporter(issue));
|
|
14338
|
+
}
|
|
13995
14339
|
};
|
|
13996
|
-
|
|
13997
14340
|
/**
|
|
13998
|
-
*
|
|
14341
|
+
* Replaces the actions relayed from one Iris app iframe. Pass an empty list when the iframe goes away.
|
|
13999
14342
|
*
|
|
14000
|
-
*
|
|
14001
|
-
*
|
|
14343
|
+
* - `sourceId`: the iframe's mount, unique on the page. It only routes; it's never part of an action id.
|
|
14344
|
+
* - `idPrefix`: who the actions come from, the app and extension, e.g. `@trackunit/fleet-insights/fleet-main`.
|
|
14345
|
+
* Each action is listed as `<idPrefix>.<the app's id>`.
|
|
14346
|
+
* - `invoke`: runs an action in this iframe by the app's own id.
|
|
14002
14347
|
*
|
|
14003
|
-
*
|
|
14004
|
-
*
|
|
14005
|
-
* @param {boolean} [options.skip] - Whether to skip observing for breakpoint changes (default: false)
|
|
14006
|
-
* @returns {BreakpointState} An object containing boolean values for each container size breakpoint.
|
|
14007
|
-
* @example
|
|
14008
|
-
* const MyComponent = () => {
|
|
14009
|
-
* const containerRef = useRef<HTMLDivElement>(null);
|
|
14010
|
-
* const containerSize = useContainerBreakpoints(containerRef);
|
|
14348
|
+
* The registry is the last word on what an app may claim: an action whose id breaks
|
|
14349
|
+
* `isValidActionId`'s rules is dropped, and `ai` is read the strictest way (`parseActionAi`).
|
|
14011
14350
|
*
|
|
14012
|
-
*
|
|
14013
|
-
*
|
|
14014
|
-
*
|
|
14015
|
-
* <LargeLayout />
|
|
14016
|
-
* ) : containerSize.isMd ? (
|
|
14017
|
-
* <MediumLayout />
|
|
14018
|
-
* ) : (
|
|
14019
|
-
* <SmallLayout />
|
|
14020
|
-
* )}
|
|
14021
|
-
* </div>
|
|
14022
|
-
* );
|
|
14023
|
-
* }
|
|
14351
|
+
* Used by the host's iframe event forwarder.
|
|
14352
|
+
*
|
|
14353
|
+
* @internal
|
|
14024
14354
|
*/
|
|
14025
|
-
const
|
|
14026
|
-
const
|
|
14027
|
-
|
|
14028
|
-
|
|
14029
|
-
if (skip) {
|
|
14030
|
-
return;
|
|
14031
|
-
}
|
|
14032
|
-
if (process.env.NODE_ENV === "development" && !ref.current) {
|
|
14033
|
-
// eslint-disable-next-line no-console
|
|
14034
|
-
console.warn("useContainerBreakpoints: The provided ref is not attached to any element. " +
|
|
14035
|
-
"Make sure to pass the ref to an element using the ref prop, like: <div ref={myRef}>", "\nComponent:", ref.current);
|
|
14036
|
-
}
|
|
14037
|
-
}, [ref, skip]);
|
|
14038
|
-
const updateContainerSize = useCallback(() => {
|
|
14039
|
-
if (!ref.current) {
|
|
14040
|
-
return;
|
|
14041
|
-
}
|
|
14042
|
-
const width = ref.current.getBoundingClientRect().width;
|
|
14043
|
-
setContainerSize(createBreakpointState({ width }));
|
|
14044
|
-
}, [ref]);
|
|
14045
|
-
useEffect(() => {
|
|
14046
|
-
if (skip) {
|
|
14047
|
-
return;
|
|
14048
|
-
}
|
|
14049
|
-
const element = ref.current;
|
|
14050
|
-
if (!element) {
|
|
14355
|
+
const setRelayedActions = (sourceId, idPrefix, actions, invoke) => {
|
|
14356
|
+
const registry = getRegistry();
|
|
14357
|
+
if (actions.length === 0) {
|
|
14358
|
+
if (!registry.remote.delete(sourceId)) {
|
|
14051
14359
|
return;
|
|
14052
14360
|
}
|
|
14053
|
-
|
|
14054
|
-
|
|
14055
|
-
|
|
14056
|
-
|
|
14057
|
-
|
|
14058
|
-
|
|
14059
|
-
|
|
14060
|
-
|
|
14061
|
-
|
|
14062
|
-
|
|
14361
|
+
}
|
|
14362
|
+
else {
|
|
14363
|
+
registry.remote.set(sourceId, actions.flatMap(action => isValidActionId(action.id)
|
|
14364
|
+
? [
|
|
14365
|
+
{
|
|
14366
|
+
...action,
|
|
14367
|
+
id: `${idPrefix}.${action.id}`,
|
|
14368
|
+
ai: parseActionAi(action.ai),
|
|
14369
|
+
perform: () => invoke?.(action.id),
|
|
14370
|
+
},
|
|
14371
|
+
]
|
|
14372
|
+
: []));
|
|
14373
|
+
}
|
|
14374
|
+
notify(registry);
|
|
14063
14375
|
};
|
|
14064
|
-
|
|
14065
|
-
// Copied from https://github.com/rexxars/use-device-pixel-ratio
|
|
14066
14376
|
/**
|
|
14067
|
-
*
|
|
14068
|
-
* Will emit new values if it changes.
|
|
14377
|
+
* Calls `listener` whenever the registered actions change. For `useRegisteredActions`.
|
|
14069
14378
|
*
|
|
14070
|
-
* @
|
|
14071
|
-
* @returns {
|
|
14379
|
+
* @internal
|
|
14380
|
+
* @returns {() => void} Unsubscribe function
|
|
14072
14381
|
*/
|
|
14073
|
-
|
|
14074
|
-
const
|
|
14075
|
-
|
|
14076
|
-
|
|
14077
|
-
|
|
14078
|
-
|
|
14079
|
-
|
|
14080
|
-
}
|
|
14081
|
-
const canListen = typeof window !== "undefined" && "matchMedia" in window;
|
|
14082
|
-
if (!canListen) {
|
|
14083
|
-
return;
|
|
14084
|
-
}
|
|
14085
|
-
const updateDpr = () => setCurrentDpr(getDevicePixelRatio({ defaultDpr, maxDpr, round }));
|
|
14086
|
-
const mediaMatcher = window.matchMedia(`screen and (resolution: ${currentDpr}dppx)`);
|
|
14087
|
-
mediaMatcher.addEventListener("change", updateDpr);
|
|
14088
|
-
return () => {
|
|
14089
|
-
mediaMatcher.removeEventListener("change", updateDpr);
|
|
14090
|
-
};
|
|
14091
|
-
}, [currentDpr, defaultDpr, maxDpr, round, skip]);
|
|
14092
|
-
return currentDpr;
|
|
14093
|
-
}
|
|
14382
|
+
const subscribeToActions = (listener) => {
|
|
14383
|
+
const registry = getRegistry();
|
|
14384
|
+
registry.listeners.add(listener);
|
|
14385
|
+
return () => {
|
|
14386
|
+
registry.listeners.delete(listener);
|
|
14387
|
+
};
|
|
14388
|
+
};
|
|
14094
14389
|
/**
|
|
14095
|
-
*
|
|
14390
|
+
* Every action currently registered in this window, plus those relayed from Iris app iframes. The
|
|
14391
|
+
* same array until they change.
|
|
14096
14392
|
*
|
|
14097
|
-
* @
|
|
14098
|
-
* @returns { number } current device pixel ratio
|
|
14393
|
+
* @internal
|
|
14099
14394
|
*/
|
|
14100
|
-
|
|
14101
|
-
const { defaultDpr = 1, maxDpr = 3, round = true } = options || {};
|
|
14102
|
-
const hasDprProp = typeof window !== "undefined" && typeof window.devicePixelRatio === "number";
|
|
14103
|
-
const dpr = hasDprProp ? window.devicePixelRatio : defaultDpr;
|
|
14104
|
-
return Math.min(Math.max(1, round ? Math.floor(dpr) : dpr), maxDpr);
|
|
14105
|
-
}
|
|
14106
|
-
|
|
14395
|
+
const getActionsSnapshot = () => getRegistry().snapshot;
|
|
14107
14396
|
/**
|
|
14108
|
-
*
|
|
14109
|
-
* Useful when you _want_ to be able to control the reducer state of a component
|
|
14110
|
-
* from a parent component but keep the simplicity of not _having_ to.
|
|
14111
|
-
*
|
|
14112
|
-
* If no custom reducer state is provided, the fallback reducer state will be used and it works like a normal useReducer hook.
|
|
14397
|
+
* What `useRegisteredActions` lists during server rendering: nothing.
|
|
14113
14398
|
*
|
|
14114
|
-
* @
|
|
14115
|
-
* const [state, dispatch] = useElevatedReducer(reducer, initialState, elevatedReducerState);
|
|
14399
|
+
* @internal
|
|
14116
14400
|
*/
|
|
14117
|
-
const
|
|
14118
|
-
const [fallbackValue, fallbackDispatch] = useReducer(reducer, initialState);
|
|
14119
|
-
return useMemo(() => customState ?? [fallbackValue, fallbackDispatch], [customState, fallbackValue, fallbackDispatch]);
|
|
14120
|
-
};
|
|
14401
|
+
const getServerActionsSnapshot = () => EMPTY;
|
|
14121
14402
|
|
|
14403
|
+
/** Time window in ms for the browser fallback escape hatch. */
|
|
14404
|
+
const REPEAT_WINDOW_MS = 400;
|
|
14122
14405
|
/**
|
|
14123
|
-
*
|
|
14124
|
-
*
|
|
14125
|
-
* from a parent component but keep the simplicity of not _having_ to.
|
|
14406
|
+
* Applies a shortcut's `preventDefault` mode to a key event that matched it, and says whether the
|
|
14407
|
+
* shortcut should run. In `"once"` mode, a second press within the repeat window goes to the browser.
|
|
14126
14408
|
*
|
|
14127
|
-
*
|
|
14409
|
+
* @param event - The matched key event
|
|
14410
|
+
* @param mode - The shortcut's preventDefault mode
|
|
14411
|
+
* @param lastTrigger - When the shortcut last ran, in ms since the epoch
|
|
14412
|
+
* @returns {number | undefined} The time to record as the shortcut's last run, or undefined if it shouldn't run
|
|
14128
14413
|
*/
|
|
14129
|
-
const
|
|
14130
|
-
const
|
|
14131
|
-
|
|
14414
|
+
const claimShortcutEvent = (event, mode, lastTrigger) => {
|
|
14415
|
+
const now = Date.now();
|
|
14416
|
+
if (mode === "once" && now - lastTrigger < REPEAT_WINDOW_MS) {
|
|
14417
|
+
return undefined;
|
|
14418
|
+
}
|
|
14419
|
+
if (mode !== "never") {
|
|
14420
|
+
event.preventDefault();
|
|
14421
|
+
}
|
|
14422
|
+
return now;
|
|
14132
14423
|
};
|
|
14133
14424
|
|
|
14134
14425
|
/**
|
|
14135
|
-
*
|
|
14136
|
-
* that content (e.g. inside a closing drawer) can keep rendering its last known value while an
|
|
14137
|
-
* exit animation plays, instead of flashing to a new/empty value mid-animation.
|
|
14138
|
-
*
|
|
14139
|
-
* It is a pure value-holding primitive: it has no knowledge of animation duration and does not
|
|
14140
|
-
* debounce or delay anything. As soon as `isExiting` flips back to `false`, the live `value` is
|
|
14141
|
-
* returned immediately.
|
|
14142
|
-
*
|
|
14143
|
-
* @example
|
|
14144
|
-
* const heldValue = useHold(value, isExiting);
|
|
14145
|
-
*/
|
|
14146
|
-
const useHold = (value, isExiting) => {
|
|
14147
|
-
const ref = useRef(value);
|
|
14148
|
-
useEffect(() => {
|
|
14149
|
-
if (!isExiting) {
|
|
14150
|
-
ref.current = value;
|
|
14151
|
-
}
|
|
14152
|
-
}, [value, isExiting]);
|
|
14153
|
-
// Wrapped in a getter (rather than reading `ref.current` directly during render) to satisfy
|
|
14154
|
-
// the `react-hooks/refs` lint rule, which forbids accessing ref values during render. The memo
|
|
14155
|
-
// must depend on `[isExiting, value]` (unlike usePrevious's stable `[]`-deps wrapper) because
|
|
14156
|
-
// the getter itself branches on the current render's `isExiting`/`value`, not just on `ref`.
|
|
14157
|
-
const wrapper = useMemo(() => ({
|
|
14158
|
-
get current() {
|
|
14159
|
-
return isExiting ? ref.current : value;
|
|
14160
|
-
},
|
|
14161
|
-
}), [isExiting, value]);
|
|
14162
|
-
return wrapper.current;
|
|
14163
|
-
};
|
|
14164
|
-
|
|
14165
|
-
/**
|
|
14166
|
-
* Custom hook for checking if the browser is in fullscreen mode.
|
|
14167
|
-
*/
|
|
14168
|
-
const useIsFullscreen = () => {
|
|
14169
|
-
const [isFullScreen, setIsFullScreen] = useState(false);
|
|
14170
|
-
document.addEventListener("fullscreenchange", () => {
|
|
14171
|
-
if (document.fullscreenElement) {
|
|
14172
|
-
setIsFullScreen(true);
|
|
14173
|
-
}
|
|
14174
|
-
else {
|
|
14175
|
-
setIsFullScreen(false);
|
|
14176
|
-
}
|
|
14177
|
-
});
|
|
14178
|
-
return isFullScreen;
|
|
14179
|
-
};
|
|
14180
|
-
|
|
14181
|
-
/**
|
|
14182
|
-
* Detects the current platform based on the user agent.
|
|
14183
|
-
*
|
|
14184
|
-
* @returns {Platform} The detected platform: "mac", "windows", or "linux"
|
|
14185
|
-
*/
|
|
14186
|
-
const getPlatform = () => {
|
|
14187
|
-
if (typeof navigator === "undefined") {
|
|
14188
|
-
// SSR default - most users are on Windows
|
|
14189
|
-
return "windows";
|
|
14190
|
-
}
|
|
14191
|
-
const ua = navigator.userAgent.toLowerCase();
|
|
14192
|
-
if (ua.includes("mac")) {
|
|
14193
|
-
return "mac";
|
|
14194
|
-
}
|
|
14195
|
-
if (ua.includes("linux")) {
|
|
14196
|
-
return "linux";
|
|
14197
|
-
}
|
|
14198
|
-
return "windows";
|
|
14199
|
-
};
|
|
14200
|
-
|
|
14201
|
-
/** Display order for modifiers: mod first, then alt, then shift */
|
|
14202
|
-
const MODIFIER_DISPLAY_ORDER = ["mod", "alt", "shift"];
|
|
14203
|
-
/** Labels for each modifier, mapped per platform */
|
|
14204
|
-
const MODIFIER_LABELS = {
|
|
14205
|
-
mod: { mac: "Cmd", other: "Ctrl" },
|
|
14206
|
-
alt: { mac: "Option", other: "Alt" },
|
|
14207
|
-
shift: { mac: "Shift", other: "Shift" },
|
|
14208
|
-
};
|
|
14209
|
-
/**
|
|
14210
|
-
* Maps a semantic modifier to a display label based on the current platform.
|
|
14211
|
-
*/
|
|
14212
|
-
const getModifierLabel = (mod) => {
|
|
14213
|
-
const labels = MODIFIER_LABELS[mod];
|
|
14214
|
-
return getPlatform() === "mac" ? labels.mac : labels.other;
|
|
14215
|
-
};
|
|
14216
|
-
/**
|
|
14217
|
-
* Maps a key to a more readable display label.
|
|
14218
|
-
*/
|
|
14219
|
-
const getKeyLabel = (key) => {
|
|
14220
|
-
const keyLabels = {
|
|
14221
|
-
arrowup: "↑",
|
|
14222
|
-
arrowdown: "↓",
|
|
14223
|
-
arrowleft: "←",
|
|
14224
|
-
arrowright: "→",
|
|
14225
|
-
enter: "Enter",
|
|
14226
|
-
escape: "Esc",
|
|
14227
|
-
tab: "Tab",
|
|
14228
|
-
space: "Space",
|
|
14229
|
-
backspace: "Backspace",
|
|
14230
|
-
delete: "Delete",
|
|
14231
|
-
};
|
|
14232
|
-
const lowerKey = key.toLowerCase();
|
|
14233
|
-
return keyLabels[lowerKey] ?? key.toUpperCase();
|
|
14234
|
-
};
|
|
14235
|
-
/**
|
|
14236
|
-
* Formats a shortcut definition into a human-readable label.
|
|
14237
|
-
*
|
|
14238
|
-
* The label is platform-aware:
|
|
14239
|
-
* - Mac: "Cmd + K", "Option + Shift + L"
|
|
14240
|
-
* - Windows/Linux: "Ctrl + K", "Alt + Shift + L"
|
|
14241
|
-
*
|
|
14242
|
-
* @param shortcut - The shortcut definition to format
|
|
14243
|
-
* @param separator - The separator between parts (default: " + ")
|
|
14244
|
-
* @returns {string} A formatted string like "Cmd + K" or "Ctrl + Shift + L"
|
|
14245
|
-
* @example
|
|
14246
|
-
* formatShortcutLabel({ key: "k", modifiers: "mod" })
|
|
14247
|
-
* // Mac: "Cmd + K"
|
|
14248
|
-
* // Windows: "Ctrl + K"
|
|
14249
|
-
* @example
|
|
14250
|
-
* formatShortcutLabel({ key: "l", modifiers: "mod+shift" })
|
|
14251
|
-
* // Mac: "Cmd + Shift + L"
|
|
14252
|
-
* // Windows: "Ctrl + Shift + L"
|
|
14253
|
-
* @example
|
|
14254
|
-
* formatShortcutLabel({ key: "Escape" })
|
|
14255
|
-
* // "Esc"
|
|
14256
|
-
*/
|
|
14257
|
-
const formatShortcutLabel = (shortcut, separator = " + ") => {
|
|
14258
|
-
// Parse modifier string and sort in display order (mod, alt, shift)
|
|
14259
|
-
const modifierSet = new Set(shortcut.modifiers?.split("+") ?? []);
|
|
14260
|
-
const sortedModifiers = MODIFIER_DISPLAY_ORDER.filter(mod => modifierSet.has(mod));
|
|
14261
|
-
const modLabels = sortedModifiers.map(getModifierLabel);
|
|
14262
|
-
const keyLabel = getKeyLabel(shortcut.key);
|
|
14263
|
-
return [...modLabels, keyLabel].join(separator);
|
|
14264
|
-
};
|
|
14265
|
-
|
|
14266
|
-
/**
|
|
14267
|
-
* Parses a modifier string into a Set for easy lookup.
|
|
14426
|
+
* Parses a modifier string into a Set for easy lookup.
|
|
14268
14427
|
*
|
|
14269
14428
|
* @param modifiers - The modifier string (e.g., "mod+shift")
|
|
14270
14429
|
* @returns {Set<string>} A Set containing the individual modifiers
|
|
@@ -14279,10 +14438,14 @@ const parseModifiers = (modifiers) => {
|
|
|
14279
14438
|
* Checks if a keyboard event matches the shortcut definition.
|
|
14280
14439
|
*
|
|
14281
14440
|
* This is a pure function that handles:
|
|
14282
|
-
* -
|
|
14441
|
+
* - Keyboard layouts: the key is the character typed, and letters and digits fall back to their
|
|
14442
|
+
* US QWERTY position where the layout types something else (Ctrl+K on a Russian layout types
|
|
14443
|
+
* "л"; see `matchesShortcutKey`), except with Alt held, where Option and AltGr type accented
|
|
14444
|
+
* letters and only the typed character counts
|
|
14283
14445
|
* - Platform-aware modifier key checking (Cmd on Mac, Ctrl on Windows/Linux)
|
|
14284
14446
|
* - Space key normalization
|
|
14285
|
-
* - Extra modifier rejection (ensures only expected modifiers are pressed)
|
|
14447
|
+
* - Extra modifier rejection (ensures only expected modifiers are pressed), except Shift for a
|
|
14448
|
+
* symbol without other modifiers, which may take Shift to type (`=` is Shift+0 on a German keyboard)
|
|
14286
14449
|
*
|
|
14287
14450
|
* @param event - The keyboard event to check
|
|
14288
14451
|
* @param shortcut - The shortcut definition to match against
|
|
@@ -14292,14 +14455,8 @@ const parseModifiers = (modifiers) => {
|
|
|
14292
14455
|
* const isMatch = matchesShortcut(event, { key: "k", modifiers: "mod" });
|
|
14293
14456
|
*/
|
|
14294
14457
|
const matchesShortcut = (event, shortcut) => {
|
|
14295
|
-
//
|
|
14296
|
-
|
|
14297
|
-
const shortcutKey = shortcut.key.toLowerCase();
|
|
14298
|
-
// Handle special keys that might have different representations
|
|
14299
|
-
// Normalize both to the same representation for comparison
|
|
14300
|
-
const normalizedEventKey = eventKey === " " ? "space" : eventKey;
|
|
14301
|
-
const normalizedShortcutKey = shortcutKey === " " ? "space" : shortcutKey;
|
|
14302
|
-
if (normalizedEventKey !== normalizedShortcutKey) {
|
|
14458
|
+
// With Alt held, only the typed character counts: Option and AltGr type accented letters, which are not a key position
|
|
14459
|
+
if (!matchesShortcutKey(event, shortcut.key, { codeFallback: !event.altKey })) {
|
|
14303
14460
|
return false;
|
|
14304
14461
|
}
|
|
14305
14462
|
const modifiers = parseModifiers(shortcut.modifiers);
|
|
@@ -14316,7 +14473,8 @@ const matchesShortcut = (event, shortcut) => {
|
|
|
14316
14473
|
}
|
|
14317
14474
|
// Check "shift" modifier
|
|
14318
14475
|
const expectShift = modifiers.has("shift");
|
|
14319
|
-
|
|
14476
|
+
const shiftTypesSymbol = modifiers.size === 0 && isSymbolShortcutKey(shortcut.key);
|
|
14477
|
+
if (expectShift !== event.shiftKey && !shiftTypesSymbol) {
|
|
14320
14478
|
return false;
|
|
14321
14479
|
}
|
|
14322
14480
|
// Make sure no extra modifiers are pressed
|
|
@@ -14338,6 +14496,42 @@ const matchesShortcut = (event, shortcut) => {
|
|
|
14338
14496
|
return true;
|
|
14339
14497
|
};
|
|
14340
14498
|
|
|
14499
|
+
const INPUT_TYPES_WITHOUT_TEXT = new Set([
|
|
14500
|
+
"checkbox",
|
|
14501
|
+
"radio",
|
|
14502
|
+
"button",
|
|
14503
|
+
"submit",
|
|
14504
|
+
"reset",
|
|
14505
|
+
"range",
|
|
14506
|
+
"color",
|
|
14507
|
+
"file",
|
|
14508
|
+
"image",
|
|
14509
|
+
]);
|
|
14510
|
+
const KEYS_THAT_DONT_EDIT = new Set(["Escape"]);
|
|
14511
|
+
const isEditable = (element) => (element instanceof HTMLInputElement && !INPUT_TYPES_WITHOUT_TEXT.has(element.type)) ||
|
|
14512
|
+
element instanceof HTMLTextAreaElement ||
|
|
14513
|
+
element instanceof HTMLSelectElement ||
|
|
14514
|
+
(element.closest("[contenteditable]")?.getAttribute("contenteditable") ?? "false") !== "false";
|
|
14515
|
+
/**
|
|
14516
|
+
* Whether a key event reached an element-bound shortcut from a text field, select or contenteditable
|
|
14517
|
+
* inside that element. There a key without Cmd/Ctrl or Alt types (or moves the caret), so it isn't
|
|
14518
|
+
* the shortcut. Escape doesn't edit text, so it still counts as the shortcut, as does any key when
|
|
14519
|
+
* the field is the listening element itself.
|
|
14520
|
+
*
|
|
14521
|
+
* @param event - The keyboard event
|
|
14522
|
+
* @param listener - The element the shortcut listens on, or undefined for the window, where any field counts
|
|
14523
|
+
* @param shortcut - The shortcut definition
|
|
14524
|
+
* @returns {boolean} true if the shortcut should leave the event alone
|
|
14525
|
+
*/
|
|
14526
|
+
const isTypedInFieldInside = (event, listener, shortcut) => {
|
|
14527
|
+
const modifiers = parseModifiers(shortcut.modifiers);
|
|
14528
|
+
if (modifiers.has("mod") || modifiers.has("alt") || KEYS_THAT_DONT_EDIT.has(shortcut.key)) {
|
|
14529
|
+
return false;
|
|
14530
|
+
}
|
|
14531
|
+
const origin = event.target;
|
|
14532
|
+
return origin instanceof Element && origin !== listener && isEditable(origin);
|
|
14533
|
+
};
|
|
14534
|
+
|
|
14341
14535
|
/**
|
|
14342
14536
|
* Reserved application shortcuts.
|
|
14343
14537
|
* These are host-level shortcuts that are blocked at the type level.
|
|
@@ -14402,6 +14596,7 @@ const BROWSER_SHORTCUTS = {
|
|
|
14402
14596
|
"mod+0": "Reset zoom",
|
|
14403
14597
|
"mod+-": "Zoom out",
|
|
14404
14598
|
"mod+=": "Zoom in",
|
|
14599
|
+
"mod++": "Zoom in",
|
|
14405
14600
|
};
|
|
14406
14601
|
|
|
14407
14602
|
/**
|
|
@@ -14471,11 +14666,12 @@ const useShortcutConflicts = (shortcut, options) => {
|
|
|
14471
14666
|
return conflictInfo;
|
|
14472
14667
|
};
|
|
14473
14668
|
|
|
14474
|
-
/** Time window in ms for the browser fallback escape hatch. */
|
|
14475
|
-
const REPEAT_WINDOW_MS = 400;
|
|
14476
14669
|
/**
|
|
14477
14670
|
* Hook for handling keyboard shortcuts with platform-aware modifiers.
|
|
14478
14671
|
*
|
|
14672
|
+
* It only binds the key. Something the user can do on the page, with or without a shortcut, is an
|
|
14673
|
+
* action: use `useAction` to register it with the host.
|
|
14674
|
+
*
|
|
14479
14675
|
* Reserved shortcuts are blocked at the type level and will show specific error messages.
|
|
14480
14676
|
* There are two categories:
|
|
14481
14677
|
*
|
|
@@ -14490,7 +14686,7 @@ const REPEAT_WINDOW_MS = 400;
|
|
|
14490
14686
|
* - Navigation: mod+r (Reload), mod+shift+r (Hard reload), mod+t (New tab),
|
|
14491
14687
|
* mod+w (Close tab), mod+shift+t (Reopen tab), mod+n (New window),
|
|
14492
14688
|
* mod+shift+n (Incognito), mod+l (Address bar), mod+d (Bookmark)
|
|
14493
|
-
* - Zoom: mod+= (Zoom in), mod+- (Zoom out), mod+0 (Reset zoom)
|
|
14689
|
+
* - Zoom: mod+= and mod++ (Zoom in), mod+- (Zoom out), mod+0 (Reset zoom)
|
|
14494
14690
|
* - Other: mod+p (Print), mod+s (Save), mod+o (Open), mod+h (History/Hide),
|
|
14495
14691
|
* mod+j (Downloads), mod+q (Quit Mac)
|
|
14496
14692
|
*
|
|
@@ -14504,8 +14700,16 @@ const REPEAT_WINDOW_MS = 400;
|
|
|
14504
14700
|
* - `"never"` (default) - Browser handles the event normally
|
|
14505
14701
|
* - `"once"` - Prevent default, but rapid repeat (within 400ms) passes to browser
|
|
14506
14702
|
* - `"always"` - Always prevent default, no browser escape hatch
|
|
14507
|
-
* @param options.target - Target element for the listener (default: "window")
|
|
14508
|
-
*
|
|
14703
|
+
* @param options.target - Target element for the listener (default: "window"). On an element, a
|
|
14704
|
+
* shortcut without Cmd/Ctrl or Alt ignores keys typed in a field (input, textarea, select or
|
|
14705
|
+
* contenteditable) inside it. Escape still fires.
|
|
14706
|
+
* @param options.acceptKey - Runs the shortcut only for key events this returns true for (default: every key event)
|
|
14707
|
+
* @param options.ignoreKeysTypedInFields - Do the same on the window target (default: false)
|
|
14708
|
+
* @returns {FormattedShortcut} The readable label (e.g. "Cmd + K") and the keycaps (e.g. ["⌘", "K"]). Pass it to `ShortcutKeys` to show it.
|
|
14709
|
+
* @example
|
|
14710
|
+
* // Show the shortcut next to the button it runs
|
|
14711
|
+
* const shortcut = useKeyboardShortcut({ key: "Enter", modifiers: "mod" }, { onTrigger: submit });
|
|
14712
|
+
* <Button onClick={submit} suffix={<ShortcutKeys shortcut={shortcut} size="small" />}>Submit</Button>
|
|
14509
14713
|
* @example
|
|
14510
14714
|
* // Simple Escape key handler (no preventDefault)
|
|
14511
14715
|
* const { label } = useKeyboardShortcut(
|
|
@@ -14524,35 +14728,42 @@ const REPEAT_WINDOW_MS = 400;
|
|
|
14524
14728
|
* );
|
|
14525
14729
|
* // label = "Cmd + M" (Mac) or "Ctrl + M" (Windows/Linux)
|
|
14526
14730
|
*/
|
|
14527
|
-
const useKeyboardShortcut = (shortcut, { onTrigger, disabled = false, preventDefault = "never", target = "window" }) => {
|
|
14731
|
+
const useKeyboardShortcut = (shortcut, { onTrigger, disabled = false, preventDefault = "never", target = "window", acceptKey, ignoreKeysTypedInFields = false, }) => {
|
|
14732
|
+
// Callers usually write the shortcut inline, so key the listener on its values rather than its identity.
|
|
14733
|
+
const { key, modifiers } = shortcut;
|
|
14734
|
+
const stableShortcut = useMemo(() => (modifiers === undefined ? { key } : { key, modifiers }), [key, modifiers]);
|
|
14528
14735
|
// Use refs to avoid recreating the handler on every render
|
|
14529
14736
|
const onTriggerRef = useRef(onTrigger);
|
|
14530
14737
|
const preventDefaultRef = useRef(preventDefault);
|
|
14738
|
+
const acceptKeyRef = useRef(acceptKey);
|
|
14531
14739
|
// Track when the shortcut was last triggered for browser fallback
|
|
14532
14740
|
const lastTriggerRef = useRef(0);
|
|
14533
14741
|
// Keep refs up to date
|
|
14534
14742
|
useEffect(() => {
|
|
14535
14743
|
onTriggerRef.current = onTrigger;
|
|
14536
14744
|
preventDefaultRef.current = preventDefault;
|
|
14537
|
-
|
|
14745
|
+
acceptKeyRef.current = acceptKey;
|
|
14746
|
+
}, [onTrigger, preventDefault, acceptKey]);
|
|
14538
14747
|
// Check for conflicts and warn in development (handled internally by the hook)
|
|
14539
|
-
useShortcutConflicts(
|
|
14540
|
-
const handleKeyDown = useCallback((event) => {
|
|
14541
|
-
if (matchesShortcut(event,
|
|
14542
|
-
|
|
14543
|
-
|
|
14544
|
-
|
|
14545
|
-
|
|
14546
|
-
|
|
14547
|
-
|
|
14548
|
-
|
|
14549
|
-
|
|
14550
|
-
|
|
14551
|
-
|
|
14552
|
-
|
|
14553
|
-
|
|
14748
|
+
useShortcutConflicts(stableShortcut, { disabled });
|
|
14749
|
+
const handleKeyDown = useCallback((event, listener) => {
|
|
14750
|
+
if (!matchesShortcut(event, stableShortcut)) {
|
|
14751
|
+
return;
|
|
14752
|
+
}
|
|
14753
|
+
if ((listener !== undefined || ignoreKeysTypedInFields) &&
|
|
14754
|
+
isTypedInFieldInside(event, listener, stableShortcut)) {
|
|
14755
|
+
return;
|
|
14756
|
+
}
|
|
14757
|
+
if (acceptKeyRef.current !== undefined && !acceptKeyRef.current(event)) {
|
|
14758
|
+
return;
|
|
14759
|
+
}
|
|
14760
|
+
const triggeredAt = claimShortcutEvent(event, preventDefaultRef.current, lastTriggerRef.current);
|
|
14761
|
+
if (triggeredAt === undefined) {
|
|
14762
|
+
return;
|
|
14554
14763
|
}
|
|
14555
|
-
|
|
14764
|
+
lastTriggerRef.current = triggeredAt;
|
|
14765
|
+
onTriggerRef.current();
|
|
14766
|
+
}, [stableShortcut, ignoreKeysTypedInFields]);
|
|
14556
14767
|
useEffect(() => {
|
|
14557
14768
|
if (disabled) {
|
|
14558
14769
|
return;
|
|
@@ -14561,10 +14772,11 @@ const useKeyboardShortcut = (shortcut, { onTrigger, disabled = false, preventDef
|
|
|
14561
14772
|
if (!targetElement) {
|
|
14562
14773
|
return;
|
|
14563
14774
|
}
|
|
14775
|
+
const listener = targetElement instanceof HTMLElement ? targetElement : undefined;
|
|
14564
14776
|
// Use a wrapper that properly handles the event type for both Window and HTMLElement
|
|
14565
14777
|
const keydownHandler = (e) => {
|
|
14566
14778
|
if (e instanceof KeyboardEvent) {
|
|
14567
|
-
handleKeyDown(e);
|
|
14779
|
+
handleKeyDown(e, listener);
|
|
14568
14780
|
}
|
|
14569
14781
|
};
|
|
14570
14782
|
targetElement.addEventListener("keydown", keydownHandler);
|
|
@@ -14573,11 +14785,749 @@ const useKeyboardShortcut = (shortcut, { onTrigger, disabled = false, preventDef
|
|
|
14573
14785
|
};
|
|
14574
14786
|
}, [disabled, target, handleKeyDown]);
|
|
14575
14787
|
// Compute the human-readable label for the shortcut
|
|
14576
|
-
const label = useMemo(() => formatShortcutLabel(
|
|
14788
|
+
const label = useMemo(() => formatShortcutLabel(stableShortcut), [stableShortcut]);
|
|
14789
|
+
const keys = useMemo(() => formatShortcutKeys({ key, modifiers }), [key, modifiers]);
|
|
14577
14790
|
// Memoize the return object for referential stability
|
|
14578
|
-
return useMemo(() => ({ label }), [label]);
|
|
14791
|
+
return useMemo(() => ({ label, keys }), [label, keys]);
|
|
14792
|
+
};
|
|
14793
|
+
|
|
14794
|
+
/**
|
|
14795
|
+
* The owner stack of the component calling the hook, read once during its first render, for
|
|
14796
|
+
* `registerAction`'s duplicate id warning. Undefined in production.
|
|
14797
|
+
*
|
|
14798
|
+
* @internal
|
|
14799
|
+
* @returns {string | undefined} The owner stack, e.g. "\n at AssetList\n at App"
|
|
14800
|
+
*/
|
|
14801
|
+
const useRegistrationOwner = () => useState(() =>
|
|
14802
|
+
// Production builds of React don't export `captureOwnerStack`, and React 19.0 (allowed by the peer
|
|
14803
|
+
// range) has none at all, so it's only called in development when it exists.
|
|
14804
|
+
process.env.NODE_ENV === "production" || typeof captureOwnerStack !== "function"
|
|
14805
|
+
? undefined
|
|
14806
|
+
: (captureOwnerStack() ?? undefined))[0];
|
|
14807
|
+
|
|
14808
|
+
/**
|
|
14809
|
+
* Registers `action` while it's defined, naming the calling component as its owner. `perform` is
|
|
14810
|
+
* read through a ref, so a new callback every render doesn't re-register.
|
|
14811
|
+
*
|
|
14812
|
+
* @internal
|
|
14813
|
+
*/
|
|
14814
|
+
const useRegisterAction = (action) => {
|
|
14815
|
+
const owner = useRegistrationOwner();
|
|
14816
|
+
const performRef = useRef(action?.perform);
|
|
14817
|
+
useEffect(() => {
|
|
14818
|
+
performRef.current = action?.perform;
|
|
14819
|
+
});
|
|
14820
|
+
const registered = action !== undefined;
|
|
14821
|
+
const { id, title = "", description = "", subtitle, group, icon, scoped, keywords, hiddenFromAssistantBecause, label, checked, } = action ?? {};
|
|
14822
|
+
const submenuId = action?.submenu?.id;
|
|
14823
|
+
const submenuTitle = action?.submenu?.title;
|
|
14824
|
+
const submenuIcon = action?.submenu?.icon;
|
|
14825
|
+
const key = action?.shortcut?.key;
|
|
14826
|
+
const modifiers = action?.shortcut?.modifiers;
|
|
14827
|
+
const keywordsKey = keywords?.join("\n");
|
|
14828
|
+
// Untyped callers (plain-JS Iris apps) can leave `ai` out or get it wrong; they get the strictest reading, as relayed actions do.
|
|
14829
|
+
const ai = parseActionAi(action?.ai);
|
|
14830
|
+
const { hints, serverTool } = ai;
|
|
14831
|
+
const { readOnlyHint, openWorldHint } = hints;
|
|
14832
|
+
const destructiveHint = hints.readOnlyHint ? undefined : hints.destructiveHint;
|
|
14833
|
+
const idempotentHint = hints.readOnlyHint ? undefined : hints.idempotentHint;
|
|
14834
|
+
const alwaysAllow = "alwaysAllow" in ai ? ai.alwaysAllow : undefined;
|
|
14835
|
+
useEffect(() => {
|
|
14836
|
+
if (!registered) {
|
|
14837
|
+
return;
|
|
14838
|
+
}
|
|
14839
|
+
return registerAction({
|
|
14840
|
+
// Untyped callers (plain-JS Iris apps) can leave it out; registerAction then refuses the action.
|
|
14841
|
+
id: id ?? "",
|
|
14842
|
+
title,
|
|
14843
|
+
description,
|
|
14844
|
+
ai: parseActionAi({
|
|
14845
|
+
hints: { readOnlyHint, destructiveHint, idempotentHint, openWorldHint },
|
|
14846
|
+
serverTool,
|
|
14847
|
+
alwaysAllow,
|
|
14848
|
+
}),
|
|
14849
|
+
subtitle,
|
|
14850
|
+
group,
|
|
14851
|
+
icon,
|
|
14852
|
+
scoped,
|
|
14853
|
+
keywords: keywordsKey === undefined ? undefined : keywordsKey.split("\n"),
|
|
14854
|
+
shortcut: key === undefined ? undefined : { key, modifiers },
|
|
14855
|
+
hiddenFromAssistantBecause,
|
|
14856
|
+
submenu: submenuId === undefined || submenuTitle === undefined
|
|
14857
|
+
? undefined
|
|
14858
|
+
: { id: submenuId, title: submenuTitle, icon: submenuIcon },
|
|
14859
|
+
label,
|
|
14860
|
+
checked,
|
|
14861
|
+
perform: () => performRef.current?.(),
|
|
14862
|
+
}, owner);
|
|
14863
|
+
}, [
|
|
14864
|
+
registered,
|
|
14865
|
+
owner,
|
|
14866
|
+
id,
|
|
14867
|
+
title,
|
|
14868
|
+
description,
|
|
14869
|
+
readOnlyHint,
|
|
14870
|
+
destructiveHint,
|
|
14871
|
+
idempotentHint,
|
|
14872
|
+
openWorldHint,
|
|
14873
|
+
serverTool,
|
|
14874
|
+
alwaysAllow,
|
|
14875
|
+
subtitle,
|
|
14876
|
+
group,
|
|
14877
|
+
icon,
|
|
14878
|
+
scoped,
|
|
14879
|
+
keywordsKey,
|
|
14880
|
+
key,
|
|
14881
|
+
modifiers,
|
|
14882
|
+
hiddenFromAssistantBecause,
|
|
14883
|
+
submenuId,
|
|
14884
|
+
submenuTitle,
|
|
14885
|
+
submenuIcon,
|
|
14886
|
+
label,
|
|
14887
|
+
checked,
|
|
14888
|
+
]);
|
|
14889
|
+
};
|
|
14890
|
+
|
|
14891
|
+
const NO_SHORTCUT = { key: "F12" };
|
|
14892
|
+
/**
|
|
14893
|
+
* Registers something the user can do on the current page with the host, while the calling
|
|
14894
|
+
* component is mounted and the action isn't disabled. Give it a `shortcut` to also bind a key
|
|
14895
|
+
* combination; the key runs the same `perform` as the host does. Registering actions gets all the
|
|
14896
|
+
* more useful as the host gains more ways to use them.
|
|
14897
|
+
*
|
|
14898
|
+
* `useKeyboardShortcut` only binds a key and registers nothing. For a list of actions that comes
|
|
14899
|
+
* from data, use `useActions`.
|
|
14900
|
+
*
|
|
14901
|
+
* Inside an Iris app the action is relayed to the host, and when the host runs it, `perform` runs
|
|
14902
|
+
* in the app.
|
|
14903
|
+
*
|
|
14904
|
+
* @returns {FormattedShortcut | undefined} The shortcut's label and keycaps, for `ShortcutKeys`, when it has one
|
|
14905
|
+
* @example
|
|
14906
|
+
* useAction({
|
|
14907
|
+
* id: "export-assets",
|
|
14908
|
+
* title: t("exportAssets"),
|
|
14909
|
+
* description: t("exportAssets.description"),
|
|
14910
|
+
* ai: { hints: { readOnlyHint: false, destructiveHint: false }, serverTool: null },
|
|
14911
|
+
* icon: "CloudArrowDown",
|
|
14912
|
+
* keywords: ["download", "csv"],
|
|
14913
|
+
* shortcut: { key: "e", modifiers: "mod+shift" },
|
|
14914
|
+
* perform: exportAssets,
|
|
14915
|
+
* });
|
|
14916
|
+
* @example
|
|
14917
|
+
* // Show the shortcut on the button that runs it
|
|
14918
|
+
* const shortcut = useAction({ id: "export-assets", title: t("exportAssets"), description: t("exportAssets.description"), ai: { hints: { readOnlyHint: false, destructiveHint: false }, serverTool: null }, shortcut: { key: "e", modifiers: "mod+shift" }, perform: exportAssets });
|
|
14919
|
+
* <Button suffix={shortcut ? <ShortcutKeys shortcut={shortcut} size="small" /> : null}>{t("export")}</Button>
|
|
14920
|
+
* @example
|
|
14921
|
+
* // A key that only works while the map has focus
|
|
14922
|
+
* useAction({ id: "map-zoom-in", title: t("zoomIn"), description: t("zoomIn.description"), ai: { hints: { readOnlyHint: true } }, group: t("map"), shortcut: { key: "=" }, target: mapRef, perform: zoomIn });
|
|
14923
|
+
*/
|
|
14924
|
+
const useAction = ({ id, title, description, ai, perform, subtitle, group, keywords, icon, submenu, label, checked, shortcut, target = "window", acceptKey, preventDefault = "once", disabled = false, hiddenFromAssistantBecause, }) => {
|
|
14925
|
+
const binding = shortcut ?? NO_SHORTCUT;
|
|
14926
|
+
const formatted = useKeyboardShortcut(binding, {
|
|
14927
|
+
onTrigger: perform,
|
|
14928
|
+
disabled: disabled || !shortcut,
|
|
14929
|
+
preventDefault,
|
|
14930
|
+
target,
|
|
14931
|
+
acceptKey,
|
|
14932
|
+
// Like `useActions`, a key typed in a field is typing, not the action
|
|
14933
|
+
ignoreKeysTypedInFields: true,
|
|
14934
|
+
});
|
|
14935
|
+
useRegisterAction(disabled
|
|
14936
|
+
? undefined
|
|
14937
|
+
: {
|
|
14938
|
+
id,
|
|
14939
|
+
title,
|
|
14940
|
+
description,
|
|
14941
|
+
ai,
|
|
14942
|
+
perform,
|
|
14943
|
+
subtitle,
|
|
14944
|
+
group,
|
|
14945
|
+
keywords,
|
|
14946
|
+
icon,
|
|
14947
|
+
submenu,
|
|
14948
|
+
label,
|
|
14949
|
+
checked,
|
|
14950
|
+
shortcut,
|
|
14951
|
+
scoped: shortcut !== undefined && target !== "window",
|
|
14952
|
+
hiddenFromAssistantBecause,
|
|
14953
|
+
});
|
|
14954
|
+
return shortcut ? formatted : undefined;
|
|
14955
|
+
};
|
|
14956
|
+
|
|
14957
|
+
/**
|
|
14958
|
+
* Lets the host's and Iris apps' providers plug their error reporting into the action registry.
|
|
14959
|
+
* The returned object is stable.
|
|
14960
|
+
*
|
|
14961
|
+
* @internal
|
|
14962
|
+
*/
|
|
14963
|
+
const useActionIssueReporter = () => useMemo(() => ({ setActionIssueReporter }), []);
|
|
14964
|
+
|
|
14965
|
+
/**
|
|
14966
|
+
* Lets the host put actions registered in another window (an app's iframe) into this window's
|
|
14967
|
+
* action registry. The returned object is stable.
|
|
14968
|
+
*
|
|
14969
|
+
* Used by the host's iframe event forwarder.
|
|
14970
|
+
*
|
|
14971
|
+
* @internal
|
|
14972
|
+
*/
|
|
14973
|
+
const useActionRelay = () => useMemo(() => ({ setRelayedActions }), []);
|
|
14974
|
+
|
|
14975
|
+
/**
|
|
14976
|
+
* What already uses a key combination, the host or the browser, when it's one `useAction` rejects
|
|
14977
|
+
* at compile time. For shortcuts that come from data, which no type can check, so the modifiers
|
|
14978
|
+
* may come in any order (`"shift+mod"`).
|
|
14979
|
+
*
|
|
14980
|
+
* @param shortcut - The shortcut to check
|
|
14981
|
+
* @returns {string | undefined} What uses it, e.g. `the host's "Global Search"`, or undefined when it's free
|
|
14982
|
+
*/
|
|
14983
|
+
const shortcutTakenBy = (shortcut) => {
|
|
14984
|
+
const key = [...[...parseModifiers(shortcut.modifiers)].sort(), shortcut.key.toLowerCase()].join("+");
|
|
14985
|
+
const reserved = RESERVED_SHORTCUTS[key];
|
|
14986
|
+
if (reserved !== undefined) {
|
|
14987
|
+
return `the host's "${reserved.name}"`;
|
|
14988
|
+
}
|
|
14989
|
+
const browserAction = BROWSER_SHORTCUTS[key];
|
|
14990
|
+
return browserAction === undefined ? undefined : `the browser's "${browserAction}"`;
|
|
14991
|
+
};
|
|
14992
|
+
|
|
14993
|
+
/**
|
|
14994
|
+
* The fields of a `useActions` entry the registry lists, without `perform`. Anything else on the
|
|
14995
|
+
* entry, like `target` or a field an untyped caller added, is left out; a `target` other than the
|
|
14996
|
+
* window marks the action as scoped. A shortcut the host or the browser already uses (see
|
|
14997
|
+
* `shortcutTakenBy`) is left out too, as `useActions` doesn't bind it.
|
|
14998
|
+
*
|
|
14999
|
+
* @param entry - One entry of the list given to `useActions`
|
|
15000
|
+
* @returns {Omit<RegisteredAction, "perform">} The action as the registry lists it
|
|
15001
|
+
*/
|
|
15002
|
+
const toRegistered = (entry) => ({
|
|
15003
|
+
id: entry.id,
|
|
15004
|
+
title: entry.title,
|
|
15005
|
+
description: entry.description,
|
|
15006
|
+
ai: entry.ai,
|
|
15007
|
+
subtitle: entry.subtitle,
|
|
15008
|
+
group: entry.group,
|
|
15009
|
+
keywords: entry.keywords,
|
|
15010
|
+
icon: entry.icon,
|
|
15011
|
+
submenu: entry.submenu,
|
|
15012
|
+
label: entry.label,
|
|
15013
|
+
checked: entry.checked,
|
|
15014
|
+
shortcut: entry.shortcut === undefined || shortcutTakenBy(entry.shortcut) !== undefined ? undefined : entry.shortcut,
|
|
15015
|
+
scoped: entry.target !== undefined && entry.target !== "window",
|
|
15016
|
+
hiddenFromAssistantBecause: entry.hiddenFromAssistantBecause,
|
|
15017
|
+
});
|
|
15018
|
+
|
|
15019
|
+
/**
|
|
15020
|
+
* Registers a list of actions with the host while the calling component is mounted, like calling
|
|
15021
|
+
* `useAction` once per entry. For lists that come from data, where the number
|
|
15022
|
+
* of actions changes and a hook per action can't be written, such as the actions a map's controls
|
|
15023
|
+
* declare. To hide an action, leave it out of the list.
|
|
15024
|
+
*
|
|
15025
|
+
* Each entry is registered under its `id`, and `perform` is read when the action runs, so passing a
|
|
15026
|
+
* new list with new callbacks every render doesn't re-register anything. An entry is re-registered
|
|
15027
|
+
* when anything else about it changes, e.g. its `checked` state or its title.
|
|
15028
|
+
*
|
|
15029
|
+
* Entries with a `shortcut` bind it on their `target`, the window by default, and the key runs the
|
|
15030
|
+
* entry's latest `perform`, as `useAction` does. A shortcut without Cmd/Ctrl or Alt ignores keys typed
|
|
15031
|
+
* in a text field, select or contenteditable, wherever it listens. The rules for ids, `ai` and duplicate ids are the
|
|
15032
|
+
* same as for `useAction`.
|
|
15033
|
+
*
|
|
15034
|
+
* @param actions - The actions to offer, each with a stable `id`. See `ActionListEntry`.
|
|
15035
|
+
* @example
|
|
15036
|
+
* useActions(options.map(option => ({
|
|
15037
|
+
* id: `map-style:${option.value}`,
|
|
15038
|
+
* title: option.title,
|
|
15039
|
+
* description: option.description,
|
|
15040
|
+
* ai: { hints: { readOnlyHint: true } },
|
|
15041
|
+
* submenu: { id: "map-style", title: t("mapStyle"), icon: "Map" },
|
|
15042
|
+
* label: option.label,
|
|
15043
|
+
* checked: option.value === style,
|
|
15044
|
+
* perform: () => setStyle(option.value),
|
|
15045
|
+
* })));
|
|
15046
|
+
*/
|
|
15047
|
+
const useActions = (actions) => {
|
|
15048
|
+
const owner = useRegistrationOwner();
|
|
15049
|
+
const actionsRef = useRef(actions);
|
|
15050
|
+
useEffect(() => {
|
|
15051
|
+
actionsRef.current = actions;
|
|
15052
|
+
});
|
|
15053
|
+
const signature = JSON.stringify(actions.map(toRegistered));
|
|
15054
|
+
const takenShortcutWarnings = actions
|
|
15055
|
+
.flatMap(({ title, shortcut }) => {
|
|
15056
|
+
const takenBy = shortcut === undefined ? undefined : shortcutTakenBy(shortcut);
|
|
15057
|
+
return shortcut === undefined || takenBy === undefined
|
|
15058
|
+
? []
|
|
15059
|
+
: [
|
|
15060
|
+
`[useActions] The shortcut "${shortcutToString(shortcut)}" of "${title}" isn't bound or listed: ${takenBy} uses it. Pick a combination nothing else uses, or leave the shortcut out.`,
|
|
15061
|
+
];
|
|
15062
|
+
})
|
|
15063
|
+
.join("\n");
|
|
15064
|
+
useEffect(() => {
|
|
15065
|
+
if (takenShortcutWarnings !== "" && process.env.NODE_ENV !== "production") {
|
|
15066
|
+
logToDevelopers("warn", takenShortcutWarnings);
|
|
15067
|
+
}
|
|
15068
|
+
}, [takenShortcutWarnings]);
|
|
15069
|
+
useEffect(() => registerActions(actionsRef.current.map(action => {
|
|
15070
|
+
const { id } = action;
|
|
15071
|
+
return {
|
|
15072
|
+
...toRegistered(action),
|
|
15073
|
+
perform: () => actionsRef.current.findLast(candidate => candidate.id === id)?.perform(),
|
|
15074
|
+
};
|
|
15075
|
+
}), owner), [signature, owner]);
|
|
15076
|
+
// Bound to the elements the targets point to when the effect runs, compared on every render, so a
|
|
15077
|
+
// new ref object, or a ref pointing elsewhere, moves the shortcut instead of leaving it unbound.
|
|
15078
|
+
const bindingRef = useRef(undefined);
|
|
15079
|
+
useEffect(() => {
|
|
15080
|
+
const resolve = (target) => target === "window" || target === undefined ? window : target.current;
|
|
15081
|
+
const elements = [
|
|
15082
|
+
...new Set(actionsRef.current.flatMap(action => {
|
|
15083
|
+
if (action.shortcut === undefined || shortcutTakenBy(action.shortcut) !== undefined) {
|
|
15084
|
+
return [];
|
|
15085
|
+
}
|
|
15086
|
+
const element = resolve(action.target);
|
|
15087
|
+
return element === null ? [] : [element];
|
|
15088
|
+
})),
|
|
15089
|
+
];
|
|
15090
|
+
const bound = bindingRef.current;
|
|
15091
|
+
if (bound !== undefined &&
|
|
15092
|
+
bound.elements.length === elements.length &&
|
|
15093
|
+
bound.elements.every((element, index) => element === elements[index])) {
|
|
15094
|
+
return;
|
|
15095
|
+
}
|
|
15096
|
+
bound?.unbind();
|
|
15097
|
+
const lastTriggers = new Map();
|
|
15098
|
+
const removers = elements.map(element => {
|
|
15099
|
+
const listener = element instanceof HTMLElement ? element : undefined;
|
|
15100
|
+
const onKeyDown = (event) => {
|
|
15101
|
+
if (!(event instanceof KeyboardEvent)) {
|
|
15102
|
+
return;
|
|
15103
|
+
}
|
|
15104
|
+
const action = actionsRef.current.find(candidate => resolve(candidate.target) === element &&
|
|
15105
|
+
candidate.shortcut !== undefined &&
|
|
15106
|
+
shortcutTakenBy(candidate.shortcut) === undefined &&
|
|
15107
|
+
matchesShortcut(event, candidate.shortcut) &&
|
|
15108
|
+
!isTypedInFieldInside(event, listener, candidate.shortcut) &&
|
|
15109
|
+
(candidate.acceptKey?.(event) ?? true));
|
|
15110
|
+
if (action === undefined) {
|
|
15111
|
+
return;
|
|
15112
|
+
}
|
|
15113
|
+
const triggeredAt = claimShortcutEvent(event, action.preventDefault ?? "once", lastTriggers.get(action.id) ?? 0);
|
|
15114
|
+
if (triggeredAt === undefined) {
|
|
15115
|
+
return;
|
|
15116
|
+
}
|
|
15117
|
+
lastTriggers.set(action.id, triggeredAt);
|
|
15118
|
+
action.perform();
|
|
15119
|
+
};
|
|
15120
|
+
element.addEventListener("keydown", onKeyDown);
|
|
15121
|
+
return () => element.removeEventListener("keydown", onKeyDown);
|
|
15122
|
+
});
|
|
15123
|
+
bindingRef.current = { elements, unbind: () => removers.forEach(remove => remove()) };
|
|
15124
|
+
});
|
|
15125
|
+
useEffect(() => () => {
|
|
15126
|
+
bindingRef.current?.unbind();
|
|
15127
|
+
bindingRef.current = undefined;
|
|
15128
|
+
}, []);
|
|
14579
15129
|
};
|
|
14580
15130
|
|
|
15131
|
+
/**
|
|
15132
|
+
* Every action currently registered in this window, plus those relayed from Iris app iframes.
|
|
15133
|
+
* For the host's surfaces that list or run actions.
|
|
15134
|
+
*
|
|
15135
|
+
* The list is in registration order, and an action that registers again (its `checked`, `subtitle`
|
|
15136
|
+
* or `title` changed) moves to the end. A surface that shows a stable order must sort the list.
|
|
15137
|
+
*
|
|
15138
|
+
* @internal
|
|
15139
|
+
* @returns {ReadonlyArray<RegisteredAction>} Active actions
|
|
15140
|
+
*/
|
|
15141
|
+
const useRegisteredActions = () => useSyncExternalStore(subscribeToActions, getActionsSnapshot, getServerActionsSnapshot);
|
|
15142
|
+
|
|
15143
|
+
const OVERSCAN = 10;
|
|
15144
|
+
const DEFAULT_ROW_HEIGHT = 50;
|
|
15145
|
+
const SCROLL_END_THRESHOLD_PX = 1;
|
|
15146
|
+
/**
|
|
15147
|
+
* Bidirectional infinite scroll hook that supports both forward (nextPage)
|
|
15148
|
+
* and backward (previousPage) pagination with TanStack Virtual.
|
|
15149
|
+
*
|
|
15150
|
+
* Unlike `useInfiniteScroll` which only loads forward, this hook detects
|
|
15151
|
+
* scroll position at both ends and triggers the appropriate pagination
|
|
15152
|
+
* direction.
|
|
15153
|
+
*/
|
|
15154
|
+
const useBidirectionalScroll = ({ pagination, scrollElementRef, count, estimateSize, overscan, onChange, skip = false, onTopItemChange, getItemKey, }) => {
|
|
15155
|
+
const onTopItemChangeRef = useRef(onTopItemChange);
|
|
15156
|
+
useEffect(() => {
|
|
15157
|
+
onTopItemChangeRef.current = onTopItemChange;
|
|
15158
|
+
}, [onTopItemChange]);
|
|
15159
|
+
const lastReportedTopIndex = useRef(-1);
|
|
15160
|
+
const tryLoadNextPage = useCallback((virtualizer) => {
|
|
15161
|
+
if (skip || !pagination.pageInfo?.hasNextPage || pagination.isLoading) {
|
|
15162
|
+
return;
|
|
15163
|
+
}
|
|
15164
|
+
const container = scrollElementRef.current;
|
|
15165
|
+
if (!container) {
|
|
15166
|
+
return;
|
|
15167
|
+
}
|
|
15168
|
+
const lastItem = virtualizer.getVirtualItems().at(-1);
|
|
15169
|
+
const reachedLastVirtualRow = lastItem !== undefined && lastItem.index >= count - 1;
|
|
15170
|
+
const hasInsufficientContent = container.scrollHeight <= container.clientHeight;
|
|
15171
|
+
const isAtScrollEnd = container.scrollHeight - container.scrollTop - container.clientHeight <= SCROLL_END_THRESHOLD_PX;
|
|
15172
|
+
if (!reachedLastVirtualRow && !hasInsufficientContent && !isAtScrollEnd) {
|
|
15173
|
+
return;
|
|
15174
|
+
}
|
|
15175
|
+
pagination.nextPage();
|
|
15176
|
+
}, [count, pagination, scrollElementRef, skip]);
|
|
15177
|
+
const handleChange = useCallback((virtualizer) => {
|
|
15178
|
+
onChange?.(virtualizer);
|
|
15179
|
+
const scrollOffset = virtualizer.scrollOffset ?? 0;
|
|
15180
|
+
const firstVisibleItem = virtualizer.getVirtualItems().find(item => item.start + item.size > scrollOffset);
|
|
15181
|
+
if (firstVisibleItem !== undefined && firstVisibleItem.index !== lastReportedTopIndex.current) {
|
|
15182
|
+
lastReportedTopIndex.current = firstVisibleItem.index;
|
|
15183
|
+
onTopItemChangeRef.current?.(firstVisibleItem.index);
|
|
15184
|
+
}
|
|
15185
|
+
tryLoadNextPage(virtualizer);
|
|
15186
|
+
}, [onChange, tryLoadNextPage]);
|
|
15187
|
+
const handleEstimateSize = useCallback((index) => estimateSize?.(index) ?? DEFAULT_ROW_HEIGHT, [estimateSize]);
|
|
15188
|
+
// eslint-plugin-react-hooks hardcodes `useVirtualizer` as a known-incompatible
|
|
15189
|
+
// API (its returned functions can't be memoized), so this warning is emitted
|
|
15190
|
+
// regardless of the installed version. The React Compiler already auto-skips
|
|
15191
|
+
// memoizing this hook, so the behaviour is safe.
|
|
15192
|
+
// eslint-disable-next-line react-hooks/incompatible-library
|
|
15193
|
+
const rowVirtualizer = useVirtualizer({
|
|
15194
|
+
count,
|
|
15195
|
+
getScrollElement: () => scrollElementRef.current,
|
|
15196
|
+
estimateSize: handleEstimateSize,
|
|
15197
|
+
overscan: overscan ?? OVERSCAN,
|
|
15198
|
+
onChange: handleChange,
|
|
15199
|
+
getItemKey,
|
|
15200
|
+
useAnimationFrameWithResizeObserver: true,
|
|
15201
|
+
// Let the virtualizer write item positions and container size straight to
|
|
15202
|
+
// the DOM, only re-rendering when the visible index range changes. This
|
|
15203
|
+
// removes the imperative transform/height races that made scrolling jumpy.
|
|
15204
|
+
directDomUpdates: true,
|
|
15205
|
+
directDomUpdatesMode: "transform",
|
|
15206
|
+
useFlushSync: false,
|
|
15207
|
+
});
|
|
15208
|
+
const virtualItems = rowVirtualizer.getVirtualItems();
|
|
15209
|
+
// Track count before backward fetch so we can offset scroll position
|
|
15210
|
+
// after items are prepended, preventing an infinite backward-load loop.
|
|
15211
|
+
const prevCountRef = useRef(count);
|
|
15212
|
+
const isLoadingBackwardRef = useRef(false);
|
|
15213
|
+
const lastResetCountRef = useRef(pagination.resetCount);
|
|
15214
|
+
useEffect(() => {
|
|
15215
|
+
const container = scrollElementRef.current;
|
|
15216
|
+
const previousCount = prevCountRef.current;
|
|
15217
|
+
if (isLoadingBackwardRef.current && !pagination.isLoading && count > previousCount) {
|
|
15218
|
+
if (container) {
|
|
15219
|
+
const estimatedRowHeight = estimateSize?.(0) ?? DEFAULT_ROW_HEIGHT;
|
|
15220
|
+
container.scrollTop += (count - previousCount) * estimatedRowHeight;
|
|
15221
|
+
}
|
|
15222
|
+
isLoadingBackwardRef.current = false;
|
|
15223
|
+
prevCountRef.current = count;
|
|
15224
|
+
return;
|
|
15225
|
+
}
|
|
15226
|
+
prevCountRef.current = count;
|
|
15227
|
+
}, [count, pagination.isLoading, scrollElementRef, estimateSize]);
|
|
15228
|
+
// Reset scroll to top when pagination is reset (e.g. new search).
|
|
15229
|
+
// Keyed on resetCount rather than pageInfo: a forward page without pageInfo
|
|
15230
|
+
// also clears endCursor, and must not move the user back to the top.
|
|
15231
|
+
useEffect(() => {
|
|
15232
|
+
if (pagination.resetCount === lastResetCountRef.current) {
|
|
15233
|
+
return;
|
|
15234
|
+
}
|
|
15235
|
+
lastResetCountRef.current = pagination.resetCount;
|
|
15236
|
+
isLoadingBackwardRef.current = false;
|
|
15237
|
+
const container = scrollElementRef.current;
|
|
15238
|
+
if (container) {
|
|
15239
|
+
container.scrollTop = 0;
|
|
15240
|
+
}
|
|
15241
|
+
}, [pagination.resetCount, scrollElementRef]);
|
|
15242
|
+
// Forward loading: scroll reached bottom or insufficient content
|
|
15243
|
+
useEffect(() => {
|
|
15244
|
+
tryLoadNextPage(rowVirtualizer);
|
|
15245
|
+
}, [tryLoadNextPage, rowVirtualizer, virtualItems, count, pagination.pageInfo?.hasNextPage, pagination.isLoading]);
|
|
15246
|
+
// Backward loading: fires when the scroll container is at the very top.
|
|
15247
|
+
// Uses scrollTop instead of virtualItems[0].index because after data
|
|
15248
|
+
// prepends the scroll-offset effect adjusts scrollTop away from 0,
|
|
15249
|
+
// which correctly prevents re-triggering. virtualItems[0].index would
|
|
15250
|
+
// still be 0 (overscan always renders from the start) causing a loop.
|
|
15251
|
+
useEffect(() => {
|
|
15252
|
+
if (skip || !pagination.pageInfo?.hasPreviousPage || pagination.isLoading) {
|
|
15253
|
+
return;
|
|
15254
|
+
}
|
|
15255
|
+
const container = scrollElementRef.current;
|
|
15256
|
+
if (!container || container.scrollTop !== 0) {
|
|
15257
|
+
return;
|
|
15258
|
+
}
|
|
15259
|
+
isLoadingBackwardRef.current = true;
|
|
15260
|
+
pagination.previousPage();
|
|
15261
|
+
}, [
|
|
15262
|
+
skip,
|
|
15263
|
+
pagination.pageInfo?.hasPreviousPage,
|
|
15264
|
+
pagination.previousPage,
|
|
15265
|
+
pagination.isLoading,
|
|
15266
|
+
pagination,
|
|
15267
|
+
scrollElementRef,
|
|
15268
|
+
virtualItems,
|
|
15269
|
+
]);
|
|
15270
|
+
return rowVirtualizer;
|
|
15271
|
+
};
|
|
15272
|
+
|
|
15273
|
+
/**
|
|
15274
|
+
* Custom hook to handle click outside events.
|
|
15275
|
+
*
|
|
15276
|
+
* @param {RefObject<HTMLElement> | Array<RefObject<HTMLElement>>} el - The reference(s) to the element(s) to watch for click outside events.
|
|
15277
|
+
* @param {object} [options={}] - Configuration options.
|
|
15278
|
+
* @param {Function} [options.onClick] - The event handler for the click outside event.
|
|
15279
|
+
* @param {boolean} [options.active=true] - Whether the click outside event listener should be active.
|
|
15280
|
+
*/
|
|
15281
|
+
const useClickOutside = (el, options) => {
|
|
15282
|
+
const els = Array.isArray(el) ? el : [el];
|
|
15283
|
+
const active = options.active !== undefined ? options.active : true;
|
|
15284
|
+
const handler = (ev) => {
|
|
15285
|
+
// eslint-disable-next-line @trackunit/no-typescript-assertion
|
|
15286
|
+
const target = ev.target;
|
|
15287
|
+
if (els.every(ref => !ref.current || !ref.current.contains(target))) {
|
|
15288
|
+
options.onClick(ev);
|
|
15289
|
+
}
|
|
15290
|
+
};
|
|
15291
|
+
const cleanup = () => window.removeEventListener("click", handler);
|
|
15292
|
+
useEffect(() => {
|
|
15293
|
+
if (active) {
|
|
15294
|
+
window.addEventListener("click", handler);
|
|
15295
|
+
}
|
|
15296
|
+
else {
|
|
15297
|
+
cleanup();
|
|
15298
|
+
}
|
|
15299
|
+
return cleanup;
|
|
15300
|
+
});
|
|
15301
|
+
};
|
|
15302
|
+
|
|
15303
|
+
/**
|
|
15304
|
+
* Maps size keys to their corresponding state property names.
|
|
15305
|
+
*/
|
|
15306
|
+
const breakpointPropsMap = {
|
|
15307
|
+
xs: "isXs",
|
|
15308
|
+
sm: "isSm",
|
|
15309
|
+
md: "isMd",
|
|
15310
|
+
lg: "isLg",
|
|
15311
|
+
xl: "isXl",
|
|
15312
|
+
"2xl": "is2xl",
|
|
15313
|
+
"3xl": "is3xl",
|
|
15314
|
+
};
|
|
15315
|
+
/**
|
|
15316
|
+
* The default state for sizes, with all values set to false.
|
|
15317
|
+
*/
|
|
15318
|
+
const defaultBreakpointState = {
|
|
15319
|
+
isXs: false,
|
|
15320
|
+
isSm: false,
|
|
15321
|
+
isMd: false,
|
|
15322
|
+
isLg: false,
|
|
15323
|
+
isXl: false,
|
|
15324
|
+
is2xl: false,
|
|
15325
|
+
is3xl: false,
|
|
15326
|
+
};
|
|
15327
|
+
/**
|
|
15328
|
+
* Creates a breakpoint state object based on a width value
|
|
15329
|
+
*/
|
|
15330
|
+
const createBreakpointState = ({ width }) => {
|
|
15331
|
+
return objectEntries(themeScreenSizeAsNumber).reduce((acc, [size, minWidth]) => ({
|
|
15332
|
+
...acc,
|
|
15333
|
+
[breakpointPropsMap[size]]: width >= minWidth,
|
|
15334
|
+
}), { ...defaultBreakpointState });
|
|
15335
|
+
};
|
|
15336
|
+
|
|
15337
|
+
/**
|
|
15338
|
+
* A custom React hook that provides real-time information about a container's size.
|
|
15339
|
+
*
|
|
15340
|
+
* This hook uses ResizeObserver to monitor changes in the container's width and returns
|
|
15341
|
+
* an object with boolean values indicating which breakpoints are currently active.
|
|
15342
|
+
*
|
|
15343
|
+
* @param {RefObject<HTMLElement>} ref - Reference to the container element to observe
|
|
15344
|
+
* @param {object} [options] - Configuration options
|
|
15345
|
+
* @param {boolean} [options.skip] - Whether to skip observing for breakpoint changes (default: false)
|
|
15346
|
+
* @returns {BreakpointState} An object containing boolean values for each container size breakpoint.
|
|
15347
|
+
* @example
|
|
15348
|
+
* const MyComponent = () => {
|
|
15349
|
+
* const containerRef = useRef<HTMLDivElement>(null);
|
|
15350
|
+
* const containerSize = useContainerBreakpoints(containerRef);
|
|
15351
|
+
*
|
|
15352
|
+
* return (
|
|
15353
|
+
* <div ref={containerRef}>
|
|
15354
|
+
* {containerSize.isLg ? (
|
|
15355
|
+
* <LargeLayout />
|
|
15356
|
+
* ) : containerSize.isMd ? (
|
|
15357
|
+
* <MediumLayout />
|
|
15358
|
+
* ) : (
|
|
15359
|
+
* <SmallLayout />
|
|
15360
|
+
* )}
|
|
15361
|
+
* </div>
|
|
15362
|
+
* );
|
|
15363
|
+
* }
|
|
15364
|
+
*/
|
|
15365
|
+
const useContainerBreakpoints = (ref, options = {}) => {
|
|
15366
|
+
const { skip = false } = options;
|
|
15367
|
+
const [containerSize, setContainerSize] = useState(() => defaultBreakpointState);
|
|
15368
|
+
useEffect(() => {
|
|
15369
|
+
if (skip) {
|
|
15370
|
+
return;
|
|
15371
|
+
}
|
|
15372
|
+
if (process.env.NODE_ENV === "development" && !ref.current) {
|
|
15373
|
+
// eslint-disable-next-line no-console
|
|
15374
|
+
console.warn("useContainerBreakpoints: The provided ref is not attached to any element. " +
|
|
15375
|
+
"Make sure to pass the ref to an element using the ref prop, like: <div ref={myRef}>", "\nComponent:", ref.current);
|
|
15376
|
+
}
|
|
15377
|
+
}, [ref, skip]);
|
|
15378
|
+
const updateContainerSize = useCallback(() => {
|
|
15379
|
+
if (!ref.current) {
|
|
15380
|
+
return;
|
|
15381
|
+
}
|
|
15382
|
+
const width = ref.current.getBoundingClientRect().width;
|
|
15383
|
+
setContainerSize(createBreakpointState({ width }));
|
|
15384
|
+
}, [ref]);
|
|
15385
|
+
useEffect(() => {
|
|
15386
|
+
if (skip) {
|
|
15387
|
+
return;
|
|
15388
|
+
}
|
|
15389
|
+
const element = ref.current;
|
|
15390
|
+
if (!element) {
|
|
15391
|
+
return;
|
|
15392
|
+
}
|
|
15393
|
+
// Initial check
|
|
15394
|
+
updateContainerSize();
|
|
15395
|
+
// Set up ResizeObserver
|
|
15396
|
+
const resizeObserver = new ResizeObserver(updateContainerSize);
|
|
15397
|
+
resizeObserver.observe(element);
|
|
15398
|
+
return () => {
|
|
15399
|
+
resizeObserver.disconnect();
|
|
15400
|
+
};
|
|
15401
|
+
}, [updateContainerSize, ref, skip]);
|
|
15402
|
+
return containerSize;
|
|
15403
|
+
};
|
|
15404
|
+
|
|
15405
|
+
// Copied from https://github.com/rexxars/use-device-pixel-ratio
|
|
15406
|
+
/**
|
|
15407
|
+
* Get the device pixel ratio, potentially rounded and capped.
|
|
15408
|
+
* Will emit new values if it changes.
|
|
15409
|
+
*
|
|
15410
|
+
* @param {DevicePixelRatioOptions} options the options object
|
|
15411
|
+
* @returns { number } The current device pixel ratio, or the default if none can be resolved
|
|
15412
|
+
*/
|
|
15413
|
+
function useDevicePixelRatio(options) {
|
|
15414
|
+
const dpr = getDevicePixelRatio(options);
|
|
15415
|
+
const [currentDpr, setCurrentDpr] = useState(dpr);
|
|
15416
|
+
const { defaultDpr, maxDpr, round, skip = false } = options || {};
|
|
15417
|
+
useEffect(() => {
|
|
15418
|
+
if (skip) {
|
|
15419
|
+
return;
|
|
15420
|
+
}
|
|
15421
|
+
const canListen = typeof window !== "undefined" && "matchMedia" in window;
|
|
15422
|
+
if (!canListen) {
|
|
15423
|
+
return;
|
|
15424
|
+
}
|
|
15425
|
+
const updateDpr = () => setCurrentDpr(getDevicePixelRatio({ defaultDpr, maxDpr, round }));
|
|
15426
|
+
const mediaMatcher = window.matchMedia(`screen and (resolution: ${currentDpr}dppx)`);
|
|
15427
|
+
mediaMatcher.addEventListener("change", updateDpr);
|
|
15428
|
+
return () => {
|
|
15429
|
+
mediaMatcher.removeEventListener("change", updateDpr);
|
|
15430
|
+
};
|
|
15431
|
+
}, [currentDpr, defaultDpr, maxDpr, round, skip]);
|
|
15432
|
+
return currentDpr;
|
|
15433
|
+
}
|
|
15434
|
+
/**
|
|
15435
|
+
* Returns the current device pixel ratio (DPR) given the passed options
|
|
15436
|
+
*
|
|
15437
|
+
* @param { DevicePixelRatioOptions } options the options object
|
|
15438
|
+
* @returns { number } current device pixel ratio
|
|
15439
|
+
*/
|
|
15440
|
+
function getDevicePixelRatio(options) {
|
|
15441
|
+
const { defaultDpr = 1, maxDpr = 3, round = true } = options || {};
|
|
15442
|
+
const hasDprProp = typeof window !== "undefined" && typeof window.devicePixelRatio === "number";
|
|
15443
|
+
const dpr = hasDprProp ? window.devicePixelRatio : defaultDpr;
|
|
15444
|
+
return Math.min(Math.max(1, round ? Math.floor(dpr) : dpr), maxDpr);
|
|
15445
|
+
}
|
|
15446
|
+
|
|
15447
|
+
/**
|
|
15448
|
+
* Use this hook if you want to optionally elevate the reducer state of a component.
|
|
15449
|
+
* Useful when you _want_ to be able to control the reducer state of a component
|
|
15450
|
+
* from a parent component but keep the simplicity of not _having_ to.
|
|
15451
|
+
*
|
|
15452
|
+
* If no custom reducer state is provided, the fallback reducer state will be used and it works like a normal useReducer hook.
|
|
15453
|
+
*
|
|
15454
|
+
* @example
|
|
15455
|
+
* const [state, dispatch] = useElevatedReducer(reducer, initialState, elevatedReducerState);
|
|
15456
|
+
*/
|
|
15457
|
+
const useElevatedReducer = (reducer, initialState, customState) => {
|
|
15458
|
+
const [fallbackValue, fallbackDispatch] = useReducer(reducer, initialState);
|
|
15459
|
+
return useMemo(() => customState ?? [fallbackValue, fallbackDispatch], [customState, fallbackValue, fallbackDispatch]);
|
|
15460
|
+
};
|
|
15461
|
+
|
|
15462
|
+
/**
|
|
15463
|
+
* Use this hook if you want to optionally elevate the state of a component.
|
|
15464
|
+
* Useful when you _want_ to be able to control the state of a component
|
|
15465
|
+
* from a parent component but keep the simplicity of not _having_ to.
|
|
15466
|
+
*
|
|
15467
|
+
* If no custom state is provided, the fallback state will be used and it works like a normal useState hook.
|
|
15468
|
+
*/
|
|
15469
|
+
const useElevatedState = (initialState, customState) => {
|
|
15470
|
+
const [fallbackValue, fallbackSetter] = useState(initialState);
|
|
15471
|
+
return useMemo(() => customState ?? [fallbackValue, fallbackSetter], [customState, fallbackValue, fallbackSetter]);
|
|
15472
|
+
};
|
|
15473
|
+
|
|
15474
|
+
/**
|
|
15475
|
+
* The useHold hook freezes a value at its last non-exiting state while `isExiting` is true, so
|
|
15476
|
+
* that content (e.g. inside a closing drawer) can keep rendering its last known value while an
|
|
15477
|
+
* exit animation plays, instead of flashing to a new/empty value mid-animation.
|
|
15478
|
+
*
|
|
15479
|
+
* It is a pure value-holding primitive: it has no knowledge of animation duration and does not
|
|
15480
|
+
* debounce or delay anything. As soon as `isExiting` flips back to `false`, the live `value` is
|
|
15481
|
+
* returned immediately.
|
|
15482
|
+
*
|
|
15483
|
+
* @example
|
|
15484
|
+
* const heldValue = useHold(value, isExiting);
|
|
15485
|
+
*/
|
|
15486
|
+
const useHold = (value, isExiting) => {
|
|
15487
|
+
const ref = useRef(value);
|
|
15488
|
+
useEffect(() => {
|
|
15489
|
+
if (!isExiting) {
|
|
15490
|
+
ref.current = value;
|
|
15491
|
+
}
|
|
15492
|
+
}, [value, isExiting]);
|
|
15493
|
+
// Wrapped in a getter (rather than reading `ref.current` directly during render) to satisfy
|
|
15494
|
+
// the `react-hooks/refs` lint rule, which forbids accessing ref values during render. The memo
|
|
15495
|
+
// must depend on `[isExiting, value]` (unlike usePrevious's stable `[]`-deps wrapper) because
|
|
15496
|
+
// the getter itself branches on the current render's `isExiting`/`value`, not just on `ref`.
|
|
15497
|
+
const wrapper = useMemo(() => ({
|
|
15498
|
+
get current() {
|
|
15499
|
+
return isExiting ? ref.current : value;
|
|
15500
|
+
},
|
|
15501
|
+
}), [isExiting, value]);
|
|
15502
|
+
return wrapper.current;
|
|
15503
|
+
};
|
|
15504
|
+
|
|
15505
|
+
/**
|
|
15506
|
+
* Custom hook for checking if the browser is in fullscreen mode.
|
|
15507
|
+
*/
|
|
15508
|
+
const useIsFullscreen = () => {
|
|
15509
|
+
const [isFullScreen, setIsFullScreen] = useState(false);
|
|
15510
|
+
document.addEventListener("fullscreenchange", () => {
|
|
15511
|
+
if (document.fullscreenElement) {
|
|
15512
|
+
setIsFullScreen(true);
|
|
15513
|
+
}
|
|
15514
|
+
else {
|
|
15515
|
+
setIsFullScreen(false);
|
|
15516
|
+
}
|
|
15517
|
+
});
|
|
15518
|
+
return isFullScreen;
|
|
15519
|
+
};
|
|
15520
|
+
|
|
15521
|
+
/**
|
|
15522
|
+
* Helpers for showing keyboard shortcuts outside `useKeyboardShortcut`, such as keycaps on a list of actions.
|
|
15523
|
+
* The returned object is stable, so it can be passed to plain functions or used in effect dependencies.
|
|
15524
|
+
*
|
|
15525
|
+
* @example
|
|
15526
|
+
* const { formatShortcutKeys } = useShortcutHelpers();
|
|
15527
|
+
* const keys = formatShortcutKeys({ key: "k", modifiers: "mod" });
|
|
15528
|
+
*/
|
|
15529
|
+
const useShortcutHelpers = () => useMemo(() => ({ formatShortcutKeys, getPlatform }), []);
|
|
15530
|
+
|
|
14581
15531
|
/**
|
|
14582
15532
|
* Hook that returns true if any modifier key (Ctrl, Alt, Shift, Meta/Cmd) is pressed
|
|
14583
15533
|
*
|
|
@@ -15030,4 +15980,4 @@ const useWindowActivity = ({ onFocus, onBlur, skip = false } = { onBlur: undefin
|
|
|
15030
15980
|
*/
|
|
15031
15981
|
setupLibraryTranslations();
|
|
15032
15982
|
|
|
15033
|
-
export { Alert, Badge, Button, Card, CardBody, CardFooter, CardHeader, Collapse, CompletionStatusIndicator, CopyButton, CopyableValue, DEFAULT_SKELETON_PREFERENCE_CARD_PROPS, DetailsList, EmptyState, EmptyValue, ExternalLink, GridAreas, Heading, Highlight, HorizontalOverflowScroller, Icon, IconButton, IdentityCard, IdentityCardSkeleton, Indicator, KPI, KPICard, KPICardSkeleton, KPISkeleton, LabeledValue, LabeledValueList, List, ListItem, MenuContent, MenuDivider, MenuItem, MenuTree, MoreMenu, Notice, PackageNameStoryComponent, Page, PageContent, PageHeader, PageHeaderKpiMetrics, PageHeaderSecondaryActions, PageHeaderTitle, Pagination, Polygon, Popover, PopoverContent, PopoverTitle, PopoverTrigger, PreferenceCard, PreferenceCardSkeleton, Prompt, ROLE_CARD, SHEET_TRANSITION_DURATION, SHEET_TRANSITION_DURATION_MS, SHEET_TRANSITION_EASING, SectionHeader, SegmentedValueBar, Sheet, Sidebar, SidebarContentLayout, SkeletonBlock, SkeletonLabel, SkeletonLines, Spacer, Spinner, StarButton, Tab, TabContent, TabList, Tabs, Tag, Text, ToggleGroup, Tooltip, TrendIndicator, TrendIndicators, ValueBar, ZStack, createGrid, cvaButton, cvaButtonPrefixSuffix, cvaButtonSpinner, cvaButtonSpinnerContainer, cvaClickable, cvaContainerStyles, cvaContentContainer, cvaContentWrapper, cvaDescriptionCard, cvaIconBackground, cvaIconButton, cvaImgStyles, cvaIndicator, cvaIndicatorIcon, cvaIndicatorIconBackground, cvaIndicatorLabel, cvaIndicatorPing, cvaInputContainer, cvaInteractableItem, cvaList, cvaListContainer, cvaListItem$1 as cvaListItem, cvaMenu, cvaMenuItem, cvaMenuItemLabel, cvaMenuItemPrefix, cvaMenuItemStyle, cvaMenuItemSuffix, cvaMenuList, cvaMenuListDivider, cvaMenuListItem, cvaMenuListMultiSelect, cvaPageHeader, cvaPageHeaderContainer, cvaPageHeaderHeading, cvaPreferenceCard, cvaTitleCard, cvaToggleGroup, cvaToggleGroupWithSlidingBackground, cvaToggleItem, cvaToggleItemContent, cvaToggleItemText, cvaZStackContainer, cvaZStackItem, defaultPageSize, docs, getDevicePixelRatio, getValueBarColorByValue, iconColorNames, iconPalette, noPagination, preferenceCardGrid, useBidirectionalScroll, useClickOutside, useContainerBreakpoints, useCopyToClipboard, useCustomEncoding, useDebounce, useDevicePixelRatio, useElevatedReducer, useElevatedState, useGridAreas, useHold, useHover, useInfiniteScroll, useIsFirstRender, useIsFullscreen, useIsTextTruncated, useKeyboardShortcut, useList, useListItemHeight, useLocalStorage, useLocalStorageReducer, useMeasure, useMenuSearchField, useMenuTree, useMergeRefs, useModifierKey, useOptionalPopoverContext, useOverflowBorder, useOverflowItems, usePopoverContext, usePrevious, usePrompt, useRandomCSSLengths, useRelayPagination, useResize, useScrollBlock, useScrollDetection, useSessionStorage, useSessionStorageReducer, useSheet, useSheetSnap, useStorageKey, useStripForeignIdentityHash, useTextSearch, useTimeout, useViewportBreakpoints, useWatch, useWindowActivity };
|
|
15983
|
+
export { ACTIONS_CHANGED_EVENT, Alert, Badge, Button, Card, CardBody, CardFooter, CardHeader, Collapse, CompletionStatusIndicator, CopyButton, CopyableValue, DEFAULT_SKELETON_PREFERENCE_CARD_PROPS, DetailsList, EmptyState, EmptyValue, ExternalLink, GridAreas, Heading, Highlight, HorizontalOverflowScroller, INVOKE_ACTION_EVENT, Icon, IconButton, IdentityCard, IdentityCardSkeleton, Indicator, KPI, KPICard, KPICardSkeleton, KPISkeleton, LabeledValue, LabeledValueList, List, ListItem, MenuContent, MenuDivider, MenuItem, MenuTree, MoreMenu, Notice, PackageNameStoryComponent, Page, PageContent, PageHeader, PageHeaderKpiMetrics, PageHeaderSecondaryActions, PageHeaderTitle, Pagination, Polygon, Popover, PopoverContent, PopoverTitle, PopoverTrigger, PreferenceCard, PreferenceCardSkeleton, Prompt, ROLE_CARD, SHEET_TRANSITION_DURATION, SHEET_TRANSITION_DURATION_MS, SHEET_TRANSITION_EASING, SectionHeader, SegmentedValueBar, Sheet, ShortcutKeys, Sidebar, SidebarContentLayout, SkeletonBlock, SkeletonLabel, SkeletonLines, Spacer, Spinner, StarButton, Tab, TabContent, TabList, Tabs, Tag, Text, ToggleGroup, Tooltip, TrendIndicator, TrendIndicators, ValueBar, ZStack, createGrid, cvaButton, cvaButtonPrefixSuffix, cvaButtonSpinner, cvaButtonSpinnerContainer, cvaClickable, cvaContainerStyles, cvaContentContainer, cvaContentWrapper, cvaDescriptionCard, cvaIconBackground, cvaIconButton, cvaImgStyles, cvaIndicator, cvaIndicatorIcon, cvaIndicatorIconBackground, cvaIndicatorLabel, cvaIndicatorPing, cvaInputContainer, cvaInteractableItem, cvaList, cvaListContainer, cvaListItem$1 as cvaListItem, cvaMenu, cvaMenuItem, cvaMenuItemLabel, cvaMenuItemPrefix, cvaMenuItemStyle, cvaMenuItemSuffix, cvaMenuList, cvaMenuListDivider, cvaMenuListItem, cvaMenuListMultiSelect, cvaPageHeader, cvaPageHeaderContainer, cvaPageHeaderHeading, cvaPreferenceCard, cvaTitleCard, cvaToggleGroup, cvaToggleGroupWithSlidingBackground, cvaToggleItem, cvaToggleItemContent, cvaToggleItemText, cvaZStackContainer, cvaZStackItem, defaultPageSize, docs, getDevicePixelRatio, getValueBarColorByValue, iconColorNames, iconPalette, noPagination, preferenceCardGrid, useAction, useActionIssueReporter, useActionRelay, useActions, useBidirectionalScroll, useClickOutside, useContainerBreakpoints, useCopyToClipboard, useCustomEncoding, useDebounce, useDevicePixelRatio, useElevatedReducer, useElevatedState, useGridAreas, useHold, useHover, useInfiniteScroll, useIsFirstRender, useIsFullscreen, useIsTextTruncated, useKeyboardShortcut, useList, useListItemHeight, useLocalStorage, useLocalStorageReducer, useMeasure, useMenuSearchField, useMenuTree, useMergeRefs, useModifierKey, useOptionalPopoverContext, useOverflowBorder, useOverflowItems, usePopoverContext, usePrevious, usePrompt, useRandomCSSLengths, useRegisteredActions, useRelayPagination, useResize, useScrollBlock, useScrollDetection, useSessionStorage, useSessionStorageReducer, useSheet, useSheetSnap, useShortcutHelpers, useStorageKey, useStripForeignIdentityHash, useTextSearch, useTimeout, useViewportBreakpoints, useWatch, useWindowActivity };
|