@trackunit/react-components 1.15.21 → 1.15.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.cjs.js CHANGED
@@ -7573,6 +7573,406 @@ const useIsFullscreen = () => {
7573
7573
  return isFullScreen;
7574
7574
  };
7575
7575
 
7576
+ /**
7577
+ * Detects the current platform based on the user agent.
7578
+ *
7579
+ * @returns {Platform} The detected platform: "mac", "windows", or "linux"
7580
+ */
7581
+ const getPlatform = () => {
7582
+ if (typeof navigator === "undefined") {
7583
+ // SSR default - most users are on Windows
7584
+ return "windows";
7585
+ }
7586
+ const ua = navigator.userAgent.toLowerCase();
7587
+ if (ua.includes("mac")) {
7588
+ return "mac";
7589
+ }
7590
+ if (ua.includes("linux")) {
7591
+ return "linux";
7592
+ }
7593
+ return "windows";
7594
+ };
7595
+
7596
+ /** Display order for modifiers: mod first, then alt, then shift */
7597
+ const MODIFIER_DISPLAY_ORDER = ["mod", "alt", "shift"];
7598
+ /** Labels for each modifier, mapped per platform */
7599
+ const MODIFIER_LABELS = {
7600
+ mod: { mac: "Cmd", other: "Ctrl" },
7601
+ alt: { mac: "Option", other: "Alt" },
7602
+ shift: { mac: "Shift", other: "Shift" },
7603
+ };
7604
+ /**
7605
+ * Maps a semantic modifier to a display label based on the current platform.
7606
+ */
7607
+ const getModifierLabel = (mod) => {
7608
+ const labels = MODIFIER_LABELS[mod];
7609
+ return getPlatform() === "mac" ? labels.mac : labels.other;
7610
+ };
7611
+ /**
7612
+ * Maps a key to a more readable display label.
7613
+ */
7614
+ const getKeyLabel = (key) => {
7615
+ const keyLabels = {
7616
+ arrowup: "↑",
7617
+ arrowdown: "↓",
7618
+ arrowleft: "←",
7619
+ arrowright: "→",
7620
+ enter: "Enter",
7621
+ escape: "Esc",
7622
+ tab: "Tab",
7623
+ space: "Space",
7624
+ backspace: "Backspace",
7625
+ delete: "Delete",
7626
+ };
7627
+ const lowerKey = key.toLowerCase();
7628
+ return keyLabels[lowerKey] ?? key.toUpperCase();
7629
+ };
7630
+ /**
7631
+ * Formats a shortcut definition into a human-readable label.
7632
+ *
7633
+ * The label is platform-aware:
7634
+ * - Mac: "Cmd + K", "Option + Shift + L"
7635
+ * - Windows/Linux: "Ctrl + K", "Alt + Shift + L"
7636
+ *
7637
+ * @param shortcut - The shortcut definition to format
7638
+ * @param separator - The separator between parts (default: " + ")
7639
+ * @returns {string} A formatted string like "Cmd + K" or "Ctrl + Shift + L"
7640
+ * @example
7641
+ * formatShortcutLabel({ key: "k", modifiers: "mod" })
7642
+ * // Mac: "Cmd + K"
7643
+ * // Windows: "Ctrl + K"
7644
+ * @example
7645
+ * formatShortcutLabel({ key: "l", modifiers: "mod+shift" })
7646
+ * // Mac: "Cmd + Shift + L"
7647
+ * // Windows: "Ctrl + Shift + L"
7648
+ * @example
7649
+ * formatShortcutLabel({ key: "Escape" })
7650
+ * // "Esc"
7651
+ */
7652
+ const formatShortcutLabel = (shortcut, separator = " + ") => {
7653
+ // Parse modifier string and sort in display order (mod, alt, shift)
7654
+ const modifierSet = new Set(shortcut.modifiers?.split("+") ?? []);
7655
+ const sortedModifiers = MODIFIER_DISPLAY_ORDER.filter(mod => modifierSet.has(mod));
7656
+ const modLabels = sortedModifiers.map(getModifierLabel);
7657
+ const keyLabel = getKeyLabel(shortcut.key);
7658
+ return [...modLabels, keyLabel].join(separator);
7659
+ };
7660
+
7661
+ /**
7662
+ * Parses a modifier string into a Set for easy lookup.
7663
+ *
7664
+ * @param modifiers - The modifier string (e.g., "mod+shift")
7665
+ * @returns {Set<string>} A Set containing the individual modifiers
7666
+ */
7667
+ const parseModifiers = (modifiers) => {
7668
+ if (!modifiers) {
7669
+ return new Set();
7670
+ }
7671
+ return new Set(modifiers.split("+"));
7672
+ };
7673
+ /**
7674
+ * Checks if a keyboard event matches the shortcut definition.
7675
+ *
7676
+ * This is a pure function that handles:
7677
+ * - Case-insensitive key matching
7678
+ * - Platform-aware modifier key checking (Cmd on Mac, Ctrl on Windows/Linux)
7679
+ * - Space key normalization
7680
+ * - Extra modifier rejection (ensures only expected modifiers are pressed)
7681
+ *
7682
+ * @param event - The keyboard event to check
7683
+ * @param shortcut - The shortcut definition to match against
7684
+ * @returns {boolean} true if the event matches the shortcut, false otherwise
7685
+ * @example
7686
+ * // Check if Cmd+K (Mac) or Ctrl+K (Windows) was pressed
7687
+ * const isMatch = matchesShortcut(event, { key: "k", modifiers: "mod" });
7688
+ */
7689
+ const matchesShortcut = (event, shortcut) => {
7690
+ // Check the primary key (case-insensitive)
7691
+ const eventKey = event.key.toLowerCase();
7692
+ const shortcutKey = shortcut.key.toLowerCase();
7693
+ // Handle special keys that might have different representations
7694
+ // Normalize both to the same representation for comparison
7695
+ const normalizedEventKey = eventKey === " " ? "space" : eventKey;
7696
+ const normalizedShortcutKey = shortcutKey === " " ? "space" : shortcutKey;
7697
+ if (normalizedEventKey !== normalizedShortcutKey) {
7698
+ return false;
7699
+ }
7700
+ const modifiers = parseModifiers(shortcut.modifiers);
7701
+ // Check "mod" modifier (Cmd on Mac, Ctrl on Windows/Linux)
7702
+ const expectMod = modifiers.has("mod");
7703
+ const hasMod = getPlatform() === "mac" ? event.metaKey : event.ctrlKey;
7704
+ if (expectMod !== hasMod) {
7705
+ return false;
7706
+ }
7707
+ // Check "alt" modifier (Option on Mac, Alt on Windows/Linux)
7708
+ const expectAlt = modifiers.has("alt");
7709
+ if (expectAlt !== event.altKey) {
7710
+ return false;
7711
+ }
7712
+ // Check "shift" modifier
7713
+ const expectShift = modifiers.has("shift");
7714
+ if (expectShift !== event.shiftKey) {
7715
+ return false;
7716
+ }
7717
+ // Make sure no extra modifiers are pressed
7718
+ // If mod is expected, we've already checked the right key (meta or ctrl)
7719
+ // But we need to ensure the OTHER mod key isn't also pressed
7720
+ if (!expectMod) {
7721
+ // If we don't expect mod, neither metaKey nor ctrlKey should be pressed
7722
+ if (event.metaKey || event.ctrlKey) {
7723
+ return false;
7724
+ }
7725
+ }
7726
+ else {
7727
+ // If we expect mod, the opposite mod key shouldn't be pressed
7728
+ const oppositeModPressed = getPlatform() === "mac" ? event.ctrlKey : event.metaKey;
7729
+ if (oppositeModPressed) {
7730
+ return false;
7731
+ }
7732
+ }
7733
+ return true;
7734
+ };
7735
+
7736
+ /**
7737
+ * Reserved application shortcuts.
7738
+ * These are host-level shortcuts that are blocked at the type level.
7739
+ * See reservedShortcutTypes.ts for the type-level enforcement.
7740
+ *
7741
+ * IMPORTANT: When adding a new reserved shortcut here, you must also
7742
+ * update the type definitions in reservedShortcutTypes.ts and the
7743
+ * isGlobalShortcut() function in apps/iris-app-loader/src/forward-events-to-host.ts.
7744
+ */
7745
+ const RESERVED_SHORTCUTS = {
7746
+ "mod+k": {
7747
+ name: "Global Search",
7748
+ owner: "host-navigation",
7749
+ },
7750
+ "mod+shift+l": {
7751
+ name: "Local Dev Mode Toggle",
7752
+ owner: "host-navigation",
7753
+ },
7754
+ };
7755
+ /**
7756
+ * Common browser shortcuts that cannot be reliably overridden.
7757
+ * Using these shortcuts will trigger a development warning since
7758
+ * the browser typically intercepts them before JavaScript can handle them.
7759
+ *
7760
+ * Note: Some of these can be overridden with preventDefault(), but it's
7761
+ * generally a bad UX to override expected browser behavior.
7762
+ */
7763
+ const BROWSER_SHORTCUTS = {
7764
+ // Tab management
7765
+ "mod+t": "New tab",
7766
+ "mod+w": "Close tab",
7767
+ "mod+shift+t": "Reopen closed tab",
7768
+ "mod+n": "New window",
7769
+ "mod+shift+n": "New incognito window",
7770
+ // Navigation
7771
+ "mod+l": "Focus address bar",
7772
+ "mod+r": "Reload page",
7773
+ "mod+shift+r": "Hard reload",
7774
+ // Page actions
7775
+ "mod+s": "Save page",
7776
+ "mod+p": "Print",
7777
+ "mod+f": "Find in page",
7778
+ "mod+g": "Find next",
7779
+ "mod+shift+g": "Find previous",
7780
+ "mod+o": "Open file",
7781
+ // Browser features
7782
+ "mod+h": "History (Chrome) / Hide window (Mac)",
7783
+ "mod+j": "Downloads",
7784
+ "mod+d": "Bookmark page",
7785
+ "mod+shift+b": "Toggle bookmarks bar",
7786
+ // Developer tools
7787
+ "mod+shift+i": "Developer tools",
7788
+ "mod+shift+j": "JavaScript console",
7789
+ "mod+shift+c": "Inspect element",
7790
+ // Function keys
7791
+ f1: "Help",
7792
+ f3: "Find next",
7793
+ f5: "Reload",
7794
+ f11: "Fullscreen",
7795
+ f12: "Developer tools",
7796
+ // Zoom
7797
+ "mod+0": "Reset zoom",
7798
+ "mod+-": "Zoom out",
7799
+ "mod+=": "Zoom in",
7800
+ };
7801
+
7802
+ /**
7803
+ * Converts a ShortcutDefinition to a normalized string key for lookup.
7804
+ * Format: "mod+shift+k" (modifiers sorted alphabetically, then key)
7805
+ */
7806
+ const shortcutToString = (shortcut) => {
7807
+ if (!shortcut.modifiers) {
7808
+ return shortcut.key.toLowerCase();
7809
+ }
7810
+ // Modifiers are already in alphabetical order (enforced by type)
7811
+ return `${shortcut.modifiers}+${shortcut.key.toLowerCase()}`;
7812
+ };
7813
+
7814
+ /**
7815
+ * Hook for checking keyboard shortcut conflicts.
7816
+ *
7817
+ * This hook checks if a shortcut conflicts with:
7818
+ * - Reserved application shortcuts (host-level features)
7819
+ * - Browser shortcuts (that cannot be reliably overridden)
7820
+ *
7821
+ * In development mode, it logs a warning if the shortcut conflicts with
7822
+ * browser shortcuts. Reserved shortcuts are blocked at the type level.
7823
+ *
7824
+ * @param shortcut - The shortcut definition to check
7825
+ * @param options - Optional configuration
7826
+ * @returns {ShortcutConflictInfo} Conflict information for the shortcut
7827
+ * @example
7828
+ * const conflicts = useShortcutConflicts({ key: "k", modifiers: "mod" });
7829
+ * if (conflicts.isReserved) {
7830
+ * console.log(`Reserved by: ${conflicts.reservedInfo?.owner}`);
7831
+ * }
7832
+ */
7833
+ const useShortcutConflicts = (shortcut, options) => {
7834
+ const disabled = options?.disabled ?? false;
7835
+ const conflictInfo = react.useMemo(() => {
7836
+ if (disabled) {
7837
+ return {
7838
+ isReserved: false,
7839
+ reservedInfo: undefined,
7840
+ browserConflict: undefined,
7841
+ };
7842
+ }
7843
+ const key = shortcutToString(shortcut);
7844
+ const reservedInfo = RESERVED_SHORTCUTS[key];
7845
+ const browserConflict = BROWSER_SHORTCUTS[key];
7846
+ return {
7847
+ isReserved: reservedInfo !== undefined,
7848
+ reservedInfo,
7849
+ browserConflict,
7850
+ };
7851
+ }, [shortcut, disabled]);
7852
+ // Log development warning for browser conflicts
7853
+ react.useEffect(() => {
7854
+ if (disabled || process.env.NODE_ENV === "production") {
7855
+ return;
7856
+ }
7857
+ if (conflictInfo.browserConflict) {
7858
+ const shortcutStr = shortcutToString(shortcut);
7859
+ // eslint-disable-next-line no-console -- Development warning for browser shortcut conflicts
7860
+ console.warn(`[useKeyboardShortcut] Shortcut "${shortcutStr}" conflicts with browser shortcut: "${conflictInfo.browserConflict}". ` +
7861
+ `This shortcut may not work reliably as the browser may intercept it.`);
7862
+ }
7863
+ // Only run on mount
7864
+ // eslint-disable-next-line react-hooks/exhaustive-deps
7865
+ }, []);
7866
+ return conflictInfo;
7867
+ };
7868
+
7869
+ /** Time window in ms for the browser fallback escape hatch. */
7870
+ const REPEAT_WINDOW_MS = 400;
7871
+ /**
7872
+ * Hook for handling keyboard shortcuts with platform-aware modifiers.
7873
+ *
7874
+ * Reserved shortcuts are blocked at the type level and will show specific error messages.
7875
+ * There are two categories:
7876
+ *
7877
+ * **App-reserved** (host-level features):
7878
+ * - mod+k: Global Search
7879
+ * - mod+shift+l: Local Dev Mode Toggle
7880
+ *
7881
+ * **Browser-reserved** (native browser shortcuts):
7882
+ * - Clipboard: mod+c (Copy), mod+v (Paste), mod+x (Cut), mod+a (Select All)
7883
+ * - Undo/Redo: mod+z (Undo), mod+shift+z (Redo Mac), mod+y (Redo Win/Linux)
7884
+ * - Find: mod+f (Find), mod+g (Find next), mod+shift+g (Find previous)
7885
+ * - Navigation: mod+r (Reload), mod+shift+r (Hard reload), mod+t (New tab),
7886
+ * mod+w (Close tab), mod+shift+t (Reopen tab), mod+n (New window),
7887
+ * mod+shift+n (Incognito), mod+l (Address bar), mod+d (Bookmark)
7888
+ * - Zoom: mod+= (Zoom in), mod+- (Zoom out), mod+0 (Reset zoom)
7889
+ * - Other: mod+p (Print), mod+s (Save), mod+o (Open), mod+h (History/Hide),
7890
+ * mod+j (Downloads), mod+q (Quit Mac)
7891
+ *
7892
+ * See reservedShortcutTypes.ts for the full list with error messages.
7893
+ *
7894
+ * @param shortcut - The shortcut definition with key and optional modifiers
7895
+ * @param options - Configuration options for the shortcut handler
7896
+ * @param options.onTrigger - Callback invoked when the shortcut is triggered
7897
+ * @param options.disabled - Disable the shortcut conditionally (default: false)
7898
+ * @param options.preventDefault - Controls browser default behavior:
7899
+ * - `"never"` (default) - Browser handles the event normally
7900
+ * - `"once"` - Prevent default, but rapid repeat (within 400ms) passes to browser
7901
+ * - `"always"` - Always prevent default, no browser escape hatch
7902
+ * @param options.target - Target element for the listener (default: "window")
7903
+ * @returns {{ label: string }} Object containing the formatted shortcut label (e.g., "Cmd + K" on Mac)
7904
+ * @example
7905
+ * // Simple Escape key handler (no preventDefault)
7906
+ * const { label } = useKeyboardShortcut(
7907
+ * { key: "Escape" },
7908
+ * { onTrigger: () => closeModal() }
7909
+ * );
7910
+ * // label = "Esc"
7911
+ * @example
7912
+ * // Always prevent default, allow rapid re-triggering
7913
+ * const { label } = useKeyboardShortcut(
7914
+ * { key: "m", modifiers: "mod" },
7915
+ * {
7916
+ * onTrigger: () => createNewItem(),
7917
+ * preventDefault: "always",
7918
+ * }
7919
+ * );
7920
+ * // label = "Cmd + M" (Mac) or "Ctrl + M" (Windows/Linux)
7921
+ */
7922
+ const useKeyboardShortcut = (shortcut, { onTrigger, disabled = false, preventDefault = "never", target = "window" }) => {
7923
+ // Use refs to avoid recreating the handler on every render
7924
+ const onTriggerRef = react.useRef(onTrigger);
7925
+ const preventDefaultRef = react.useRef(preventDefault);
7926
+ // Track when the shortcut was last triggered for browser fallback
7927
+ const lastTriggerRef = react.useRef(0);
7928
+ // Keep refs up to date
7929
+ react.useEffect(() => {
7930
+ onTriggerRef.current = onTrigger;
7931
+ preventDefaultRef.current = preventDefault;
7932
+ }, [onTrigger, preventDefault]);
7933
+ // Check for conflicts and warn in development (handled internally by the hook)
7934
+ useShortcutConflicts(shortcut, { disabled });
7935
+ const handleKeyDown = react.useCallback((event) => {
7936
+ if (matchesShortcut(event, shortcut)) {
7937
+ const now = Date.now();
7938
+ const timeSinceLastTrigger = now - lastTriggerRef.current;
7939
+ const mode = preventDefaultRef.current;
7940
+ // Browser fallback: "once" mode skips handling if pressed within the repeat window
7941
+ if (mode === "once" && timeSinceLastTrigger < REPEAT_WINDOW_MS) {
7942
+ return;
7943
+ }
7944
+ if (mode !== "never") {
7945
+ event.preventDefault();
7946
+ }
7947
+ lastTriggerRef.current = now;
7948
+ onTriggerRef.current();
7949
+ }
7950
+ }, [shortcut]);
7951
+ react.useEffect(() => {
7952
+ if (disabled) {
7953
+ return;
7954
+ }
7955
+ const targetElement = target === "window" ? window : target.current;
7956
+ if (!targetElement) {
7957
+ return;
7958
+ }
7959
+ // Use a wrapper that properly handles the event type for both Window and HTMLElement
7960
+ const keydownHandler = (e) => {
7961
+ if (e instanceof KeyboardEvent) {
7962
+ handleKeyDown(e);
7963
+ }
7964
+ };
7965
+ targetElement.addEventListener("keydown", keydownHandler);
7966
+ return () => {
7967
+ targetElement.removeEventListener("keydown", keydownHandler);
7968
+ };
7969
+ }, [disabled, target, handleKeyDown]);
7970
+ // Compute the human-readable label for the shortcut
7971
+ const label = react.useMemo(() => formatShortcutLabel(shortcut), [shortcut]);
7972
+ // Memoize the return object for referential stability
7973
+ return react.useMemo(() => ({ label }), [label]);
7974
+ };
7975
+
7576
7976
  /**
7577
7977
  * Hook that returns true if any modifier key (Ctrl, Alt, Shift, Meta/Cmd) is pressed
7578
7978
  *
@@ -8084,6 +8484,7 @@ exports.useInfiniteScroll = useInfiniteScroll;
8084
8484
  exports.useIsFirstRender = useIsFirstRender;
8085
8485
  exports.useIsFullscreen = useIsFullscreen;
8086
8486
  exports.useIsTextTruncated = useIsTextTruncated;
8487
+ exports.useKeyboardShortcut = useKeyboardShortcut;
8087
8488
  exports.useList = useList;
8088
8489
  exports.useListItemHeight = useListItemHeight;
8089
8490
  exports.useLocalStorage = useLocalStorage;