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