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