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