Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(ui): add key action support for dialog navigation #674

Merged
merged 4 commits into from
Dec 5, 2024

Conversation

billcookie
Copy link
Contributor

@billcookie billcookie commented Dec 5, 2024

Overview

Allow users to be able to navigate using arrows keys and "double click" with enter.

What I've done

Added key support for navigating the menu with up, down and enter keys.

What I haven't done

How I tested

manually

Screenshot

Which point I want you to review particularly

  • Quality
  • Improvements

Memo

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced ActionItem component to support direct DOM referencing via ref.
    • Improved NodePickerDialog with keyboard navigation for selecting actions and automatic scrolling to the selected item.
  • Bug Fixes

    • Ensured the selected action in NodePickerDialog scrolls into view when the selection changes.
  • Refactor

    • Updated component structures to accommodate new functionality while maintaining existing features.

@billcookie billcookie requested a review from KaWaite as a code owner December 5, 2024 03:42
Copy link
Contributor

coderabbitai bot commented Dec 5, 2024

Walkthrough

The changes involve significant modifications to two components: ActionItem and NodePickerDialog. The ActionItem component is now wrapped with forwardRef, allowing it to accept a ref prop for direct DOM node access. In NodePickerDialog, new state management features are introduced, including tracking the selected action index and managing keyboard navigation for user interactions. Additionally, references for scrolling actions are implemented to enhance the user experience.

Changes

File Path Change Summary
ui/src/components/ActionItem/index.tsx Converted to a forwardRef component, allowing ref prop for direct DOM access. Updated component signature.
ui/src/features/Editor/components/OverlayUI/components/NodePickerDialog/index.tsx Added selectedIndex state for tracking selections, introduced containerRef and itemRefs for scrolling, updated handleKeyDown for keyboard navigation, and modified rendering for action items.

Suggested reviewers

  • KaWaite

Poem

In the garden where actions bloom,
The ActionItem finds more room.
With NodePicker now able to scroll,
Select with ease, and have a ball!
A hop, a skip, a jump so bright,
Navigating actions feels just right! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

netlify bot commented Dec 5, 2024

Deploy Preview for reearth-flow ready!

Name Link
🔨 Latest commit 30343fe
🔍 Latest deploy log https://app.netlify.com/sites/reearth-flow/deploys/675147d971da3600085a6be8
😎 Deploy Preview https://deploy-preview-674--reearth-flow.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Outside diff range and nitpick comments (2)
ui/src/components/ActionItem/index.tsx (1)

18-33: LGTM! Clean forwardRef implementation.

The conversion to forwardRef is well-implemented and necessary for the keyboard navigation feature. Consider adding a display name for better debugging:

const ActionItem = forwardRef<HTMLDivElement, Props>(
  ({ /* props */ }, ref) => {
    /* implementation */
  }
);
+ActionItem.displayName = "ActionItem";
ui/src/features/Editor/components/OverlayUI/components/NodePickerDialog/index.tsx (1)

48-59: Consider optimizing scroll behavior and state management.

A few suggestions to improve the implementation:

  1. Consider using a more sophisticated scroll behavior
  2. Selected state could be derived instead of stored
-const [selected, setSelected] = useState<string | undefined>(undefined);
+const selected = actions?.[selectedIndex]?.name;

 useEffect(() => {
   if (actions?.length) {
-    setSelected(actions[selectedIndex]?.name);
     const selectedItem = itemRefs.current[selectedIndex];
     if (selectedItem && containerRef.current) {
+      const container = containerRef.current;
+      const itemTop = selectedItem.offsetTop;
+      const itemBottom = itemTop + selectedItem.offsetHeight;
+      const containerTop = container.scrollTop;
+      const containerBottom = containerTop + container.offsetHeight;
+
+      if (itemTop < containerTop || itemBottom > containerBottom) {
         selectedItem.scrollIntoView({
           behavior: "smooth",
-          block: "nearest",
+          block: itemTop < containerTop ? "start" : "end",
         });
+      }
     }
   }
 }, [selectedIndex, actions]);
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7c6d1e1 and 42e22a2.

📒 Files selected for processing (2)
  • ui/src/components/ActionItem/index.tsx (2 hunks)
  • ui/src/features/Editor/components/OverlayUI/components/NodePickerDialog/index.tsx (6 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
ui/src/features/Editor/components/OverlayUI/components/NodePickerDialog/index.tsx

[error] 159-159: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)

Comment on lines +159 to +160
ref={(el) => (itemRefs.current[idx] = el)}
className={"m-1"}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Refactor ref assignment to follow best practices.

The current ref assignment in the expression could be confusing and harder to maintain.

-ref={(el) => (itemRefs.current[idx] = el)}
+ref={el => {
+  if (el) {
+    itemRefs.current[idx] = el;
+  }
+}}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
ref={(el) => (itemRefs.current[idx] = el)}
className={"m-1"}
ref={el => {
if (el) {
itemRefs.current[idx] = el;
}
}}
className={"m-1"}
🧰 Tools
🪛 Biome (1.9.4)

[error] 159-159: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)

Comment on lines +37 to +39
const [selectedIndex, setSelectedIndex] = useState(0);
const containerRef = useRef<HTMLDivElement>(null);
const itemRefs = useRef<(HTMLDivElement | null)[]>([]);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider cleaning up itemRefs when actions change.

The itemRefs array should be reset when actions change to prevent stale references.

useEffect(() => {
  if (rawActions && openedActionType?.nodeType) {
+   itemRefs.current = [];
    setActions(rawActions?.byType[openedActionType.nodeType]);
  }
}, [rawActions, openedActionType.nodeType]);

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines 121 to 143
const handleKeyDown = useCallback(
(e: KeyboardEvent) => {
if (e.key === "Enter") {
handleDoubleClick(selected);
} else if (e.key === "ArrowUp") {
setSelectedIndex((prevIndex) =>
prevIndex === 0 ? prevIndex : prevIndex - 1,
);
} else if (e.key === "ArrowDown") {
setSelectedIndex((prevIndex) =>
prevIndex === (actions?.length || 1) - 1 ? prevIndex : prevIndex + 1,
);
}
},
[handleDoubleClick, selected, actions],
);

useEffect(() => {
window.addEventListener("keydown", handleKeyDown);
return () => {
window.removeEventListener("keydown", handleKeyDown);
};
}, [actions, selected, handleKeyDown]);
Copy link
Contributor

@coderabbitai coderabbitai bot Dec 5, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Improve keyboard event handling.

Current implementation has several potential issues:

  1. Global keyboard events could interfere with other inputs
  2. Missing edge case handling
  3. Arrow keys might scroll the page
 const handleKeyDown = useCallback(
   (e: KeyboardEvent) => {
+    // Only handle events when dialog is open
+    if (!openedActionType) return;
+
+    // Ignore events from input fields
+    if (e.target instanceof HTMLInputElement) return;
+
     if (e.key === "Enter") {
+      e.preventDefault();
       handleDoubleClick(selected);
     } else if (e.key === "ArrowUp") {
+      e.preventDefault();
       setSelectedIndex((prevIndex) =>
         prevIndex === 0 ? prevIndex : prevIndex - 1,
       );
     } else if (e.key === "ArrowDown") {
+      e.preventDefault();
       setSelectedIndex((prevIndex) =>
         prevIndex === (actions?.length || 1) - 1 ? prevIndex : prevIndex + 1,
       );
     }
   },
-  [handleDoubleClick, selected, actions],
+  [handleDoubleClick, selected, actions, openedActionType],
 );
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const handleKeyDown = useCallback(
(e: KeyboardEvent) => {
if (e.key === "Enter") {
handleDoubleClick(selected);
} else if (e.key === "ArrowUp") {
setSelectedIndex((prevIndex) =>
prevIndex === 0 ? prevIndex : prevIndex - 1,
);
} else if (e.key === "ArrowDown") {
setSelectedIndex((prevIndex) =>
prevIndex === (actions?.length || 1) - 1 ? prevIndex : prevIndex + 1,
);
}
},
[handleDoubleClick, selected, actions],
);
useEffect(() => {
window.addEventListener("keydown", handleKeyDown);
return () => {
window.removeEventListener("keydown", handleKeyDown);
};
}, [actions, selected, handleKeyDown]);
const handleKeyDown = useCallback(
(e: KeyboardEvent) => {
// Only handle events when dialog is open
if (!openedActionType) return;
// Ignore events from input fields
if (e.target instanceof HTMLInputElement) return;
if (e.key === "Enter") {
e.preventDefault();
handleDoubleClick(selected);
} else if (e.key === "ArrowUp") {
e.preventDefault();
setSelectedIndex((prevIndex) =>
prevIndex === 0 ? prevIndex : prevIndex - 1,
);
} else if (e.key === "ArrowDown") {
e.preventDefault();
setSelectedIndex((prevIndex) =>
prevIndex === (actions?.length || 1) - 1 ? prevIndex : prevIndex + 1,
);
}
},
[handleDoubleClick, selected, actions, openedActionType],
);
useEffect(() => {
window.addEventListener("keydown", handleKeyDown);
return () => {
window.removeEventListener("keydown", handleKeyDown);
};
}, [actions, selected, handleKeyDown]);

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@billcookie This looks like a good addition

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

@billcookie billcookie changed the title improve(ui): add key action support for dialog navigation refactor(ui): add key action support for dialog navigation Dec 5, 2024
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (2)
ui/src/features/Editor/components/OverlayUI/components/NodePickerDialog/index.tsx (2)

48-59: Optimize the scroll effect implementation.

Consider these improvements for better robustness:

  1. Add null check for actions[selectedIndex]
  2. Use optional chaining
 useEffect(() => {
-  if (actions?.length) {
+  if (actions?.length && actions[selectedIndex]?.name) {
     setSelected(actions[selectedIndex]?.name);
     const selectedItem = itemRefs.current[selectedIndex];
     if (selectedItem && containerRef.current) {
       selectedItem.scrollIntoView({
         behavior: "smooth",
         block: "nearest",
       });
     }
   }
 }, [selectedIndex, actions]);

Line range hint 158-170: Enhance accessibility support.

Consider adding these accessibility improvements:

  1. Add role="listbox" to the container
  2. Add role="option" and aria-selected to each ActionItem
  3. Add aria-activedescendant to indicate the currently selected option
-<div ref={containerRef} className="max-h-[50vh] overflow-scroll">
+<div 
+  ref={containerRef} 
+  className="max-h-[50vh] overflow-scroll"
+  role="listbox"
+  aria-activedescendant={selected ? `action-${selected}` : undefined}
+>
   {actions?.map((action, idx) => (
     <Fragment key={action.name}>
       <ActionItem
         ref={(el) => (itemRefs.current[idx] = el)}
         className={"m-1"}
+        id={`action-${action.name}`}
+        role="option"
+        aria-selected={selected === action.name}
         action={action}
         selected={selected === action.name}
         onSingleClick={handleSingleClick}
         onDoubleClick={handleDoubleClick}
       />
🧰 Tools
🪛 Biome (1.9.4)

[error] 162-162: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 42e22a2 and 78665e6.

📒 Files selected for processing (1)
  • ui/src/features/Editor/components/OverlayUI/components/NodePickerDialog/index.tsx (6 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
ui/src/features/Editor/components/OverlayUI/components/NodePickerDialog/index.tsx

[error] 162-162: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)

🔇 Additional comments (3)
ui/src/features/Editor/components/OverlayUI/components/NodePickerDialog/index.tsx (3)

37-39: Consider cleaning up itemRefs when actions change.

The itemRefs array should be reset when actions change to prevent stale references.


121-146: Improve keyboard event handling.

Current implementation has several potential issues:

  1. Global keyboard events could interfere with other inputs
  2. Missing edge case handling
  3. Arrow keys might scroll the page

162-163: Refactor ref assignment to follow best practices.

The current ref assignment in the expression could be confusing and harder to maintain.

🧰 Tools
🪛 Biome (1.9.4)

[error] 162-162: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)

…kerDialog/index.tsx


Will commit the suggestion as it removes redundant calls for e.preventDefault

Co-authored-by: KaWaite <34051327+KaWaite@users.noreply.github.com>
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (1)
ui/src/features/Editor/components/OverlayUI/components/NodePickerDialog/index.tsx (1)

Based on the results, I can now generate the final response since we've found that:

  1. Testing utilities are available in the project (from earlier results showing testing-library in package.json)
  2. There are no existing tests for the NodePickerDialog component
  3. The project has keyboard interaction implementations in other components (useShortcuts.ts)

Add tests for NodePickerDialog keyboard navigation and accessibility

The NodePickerDialog component lacks test coverage for its keyboard navigation implementation. Create a new test file with the following coverage:

  • Keyboard navigation (Arrow Up/Down) for action selection
  • Enter key handling for action confirmation
  • Focus management between search input and action items
  • Screen reader accessibility for the dialog content
  • Proper cleanup of keyboard event listeners
🔗 Analysis chain

Line range hint 121-161: Add comprehensive testing for keyboard navigation.

Please ensure thorough testing of the keyboard navigation implementation:

  1. Test keyboard navigation with screen readers
  2. Verify focus management
  3. Test interaction with search input
  4. Validate scroll behavior

Let me gather more specific information about the testing setup and existing keyboard navigation tests.


Let me try one more search with corrected path patterns to find test files and testing utilities.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for existing test files
fd -e test.tsx -e spec.tsx NodePickerDialog

# Check for accessibility testing utilities
rg -l "testing-library/jest-dom|@testing-library/react"

# Look for similar keyboard navigation implementations
ast-grep --pattern 'useEffect($_) {
  window.addEventListener("keydown", $_);
  return () => {
    window.removeEventListener("keydown", $_);
  };
}'

Length of output: 585


Script:

#!/bin/bash
# Check for existing keyboard navigation tests
rg -l "keyboard|keydown|keypress" "ui/src/**/*.test.tsx" "ui/src/**/*.spec.tsx"

# Look for testing utilities specifically in the Editor feature
fd . ui/src/features/Editor -t f -e test.tsx -e spec.tsx

# Check testing setup and utilities
rg "@testing-library/user-event|fireEvent" "ui/src/**/*.test.tsx" "ui/src/**/*.spec.tsx"

# Search for accessibility-related testing patterns
rg "role=|aria-|screen.getBy" "ui/src/**/*.test.tsx" "ui/src/**/*.spec.tsx"

Length of output: 675


Script:

#!/bin/bash
# Look for test files in the entire ui directory
fd -e test.tsx -e spec.tsx . ui/src

# Check for keyboard event testing patterns in all test files
rg -l "keyboard|keydown|keypress" $(fd -e test.tsx -e spec.tsx . ui/src)

# Check for testing-library usage patterns
rg "fireEvent|userEvent|screen\." $(fd -e test.tsx -e spec.tsx . ui/src)

# Look specifically for Dialog component tests
rg -l "Dialog.*test" ui/src

Length of output: 716

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 78665e6 and 7b69e11.

📒 Files selected for processing (1)
  • ui/src/features/Editor/components/OverlayUI/components/NodePickerDialog/index.tsx (6 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
ui/src/features/Editor/components/OverlayUI/components/NodePickerDialog/index.tsx

[error] 160-160: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)

🔇 Additional comments (3)
ui/src/features/Editor/components/OverlayUI/components/NodePickerDialog/index.tsx (3)

37-39: Consider cleaning up itemRefs when actions change.

The itemRefs array should be reset when actions change to prevent stale references.


160-161: Refactor ref assignment to follow best practices.

The current ref assignment in the expression could be confusing and harder to maintain.

🧰 Tools
🪛 Biome (1.9.4)

[error] 160-160: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


121-144: ⚠️ Potential issue

Improve keyboard event handling and accessibility.

The current keyboard event handling has several issues:

  1. Global event listener could interfere with other inputs
  2. Missing focus management
  3. Lacks proper accessibility support
+const [isFocused, setIsFocused] = useState(false);
+const lastInteractionWasKeyboard = useRef(false);

 const handleKeyDown = useCallback(
   (e: KeyboardEvent) => {
+    // Only handle events when dialog is focused
+    if (!isFocused) return;
+
+    // Ignore events from input fields
+    if (e.target instanceof HTMLInputElement) return;
+
+    lastInteractionWasKeyboard.current = true;
     e.preventDefault();
     if (e.key === "Enter") {
       handleDoubleClick(selected);
     } else if (e.key === "ArrowUp") {
       setSelectedIndex((prevIndex) =>
         prevIndex === 0 ? prevIndex : prevIndex - 1,
       );
     } else if (e.key === "ArrowDown") {
       setSelectedIndex((prevIndex) =>
         prevIndex === (actions?.length || 1) - 1 ? prevIndex : prevIndex + 1,
       );
     }
   },
-  [handleDoubleClick, selected, actions],
+  [handleDoubleClick, selected, actions, isFocused],
 );

-useEffect(() => {
-  window.addEventListener("keydown", handleKeyDown);
-  return () => {
-    window.removeEventListener("keydown", handleKeyDown);
-  };
-}, [actions, selected, handleKeyDown]);
+// Add role and aria attributes to the container
+<div
+  ref={containerRef}
+  className="max-h-[50vh] overflow-scroll"
+  role="listbox"
+  tabIndex={0}
+  aria-activedescendant={selected}
+  onFocus={() => setIsFocused(true)}
+  onBlur={() => setIsFocused(false)}
+  onKeyDown={handleKeyDown}
+>

Likely invalid or redundant comment.

Comment on lines +48 to +59
useEffect(() => {
if (actions?.length) {
setSelected(actions[selectedIndex]?.name);
const selectedItem = itemRefs.current[selectedIndex];
if (selectedItem && containerRef.current) {
selectedItem.scrollIntoView({
behavior: "smooth",
block: "nearest",
});
}
}
}, [selectedIndex, actions]);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add safety checks and optimize scroll behavior.

The current implementation could be improved for better reliability and user experience:

  1. Add null/empty checks before accessing array index
  2. Prevent unnecessary scrolling on initial render
 useEffect(() => {
-  if (actions?.length) {
+  if (actions?.length && actions[selectedIndex]) {
     setSelected(actions[selectedIndex]?.name);
     const selectedItem = itemRefs.current[selectedIndex];
-    if (selectedItem && containerRef.current) {
+    // Only scroll if selection changed by keyboard navigation
+    if (selectedItem && containerRef.current && lastInteractionWasKeyboard.current) {
       selectedItem.scrollIntoView({
         behavior: "smooth",
         block: "nearest",
       });
     }
   }
 }, [selectedIndex, actions]);

Committable suggestion skipped: line range outside the PR's diff.

@billcookie billcookie merged commit d439d0b into main Dec 5, 2024
16 checks passed
@billcookie billcookie deleted the ui/key-support-action-dialog branch December 5, 2024 06:29
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (1)
ui/src/features/Editor/components/OverlayUI/components/NodePickerDialog/index.tsx (1)

Line range hint 1-177: Consider extracting keyboard navigation logic into a custom hook

The component is handling multiple responsibilities. Consider extracting the keyboard navigation logic into a reusable custom hook for better maintainability and reusability:

function useKeyboardNavigation<T>({
  items,
  onSelect,
  onConfirm,
  isActive,
}: {
  items: T[];
  onSelect: (index: number) => void;
  onConfirm: () => void;
  isActive: boolean;
}) {
  const [selectedIndex, setSelectedIndex] = useState(0);

  const handleKeyDown = useCallback(
    (e: KeyboardEvent) => {
      if (!isActive) return;

      if (e.key === "Enter") {
        e.preventDefault();
        onConfirm();
      } else if (e.key === "ArrowUp") {
        e.preventDefault();
        setSelectedIndex((prev) => (prev === 0 ? prev : prev - 1));
      } else if (e.key === "ArrowDown") {
        e.preventDefault();
        setSelectedIndex((prev) =>
          prev === items.length - 1 ? prev : prev + 1
        );
      }
    },
    [items, isActive, onConfirm]
  );

  useEffect(() => {
    onSelect(selectedIndex);
  }, [selectedIndex, onSelect]);

  useEffect(() => {
    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [handleKeyDown]);

  return selectedIndex;
}

Would you like me to help create this custom hook in a separate file?

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7b69e11 and 30343fe.

📒 Files selected for processing (1)
  • ui/src/features/Editor/components/OverlayUI/components/NodePickerDialog/index.tsx (6 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
ui/src/features/Editor/components/OverlayUI/components/NodePickerDialog/index.tsx

[error] 162-162: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)

🔇 Additional comments (3)
ui/src/features/Editor/components/OverlayUI/components/NodePickerDialog/index.tsx (3)

37-39: Clean up itemRefs when actions change

The itemRefs array should be reset when actions change to prevent stale references.


48-59: Add safety checks and optimize scroll behavior

The current implementation could be improved for better reliability and user experience.


162-163: Refactor ref assignment to follow best practices

The current ref assignment in the expression could be confusing and harder to maintain.

🧰 Tools
🪛 Biome (1.9.4)

[error] 162-162: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)

Comment on lines +121 to +146
const handleKeyDown = useCallback(
(e: KeyboardEvent) => {
if (e.key === "Enter") {
e.preventDefault();
handleDoubleClick(selected);
} else if (e.key === "ArrowUp") {
e.preventDefault();
setSelectedIndex((prevIndex) =>
prevIndex === 0 ? prevIndex : prevIndex - 1,
);
} else if (e.key === "ArrowDown") {
e.preventDefault();
setSelectedIndex((prevIndex) =>
prevIndex === (actions?.length || 1) - 1 ? prevIndex : prevIndex + 1,
);
}
},
[handleDoubleClick, selected, actions],
);

useEffect(() => {
window.addEventListener("keydown", handleKeyDown);
return () => {
window.removeEventListener("keydown", handleKeyDown);
};
}, [actions, selected, handleKeyDown]);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Implement focus management for better accessibility

The keyboard navigation implementation needs focus management to ensure proper accessibility:

  1. The dialog should trap focus within its bounds
  2. Selected items should receive focus for screen readers
  3. ESC key handling is missing for dialog dismissal
+ const [hasFocus, setHasFocus] = useState(false);

  const handleKeyDown = useCallback(
    (e: KeyboardEvent) => {
+     // Only handle events when dialog has focus
+     if (!hasFocus) return;
+
      if (e.key === "Enter") {
        e.preventDefault();
        handleDoubleClick(selected);
+     } else if (e.key === "Escape") {
+       e.preventDefault();
+       onClose();
      } else if (e.key === "ArrowUp") {
        e.preventDefault();
        setSelectedIndex((prevIndex) =>
          prevIndex === 0 ? prevIndex : prevIndex - 1,
        );
      } else if (e.key === "ArrowDown") {
        e.preventDefault();
        setSelectedIndex((prevIndex) =>
          prevIndex === (actions?.length || 1) - 1 ? prevIndex : prevIndex + 1,
        );
      }
    },
-   [handleDoubleClick, selected, actions],
+   [handleDoubleClick, selected, actions, hasFocus, onClose],
  );

  useEffect(() => {
    window.addEventListener("keydown", handleKeyDown);
    return () => {
      window.removeEventListener("keydown", handleKeyDown);
    };
-  }, [actions, selected, handleKeyDown]);
+  }, [handleKeyDown]);

Committable suggestion skipped: line range outside the PR's diff.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants