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

fix: Disable combobox portal inside dialog #14661

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

TomasEng
Copy link
Contributor

@TomasEng TomasEng commented Feb 13, 2025

Description

The Combobox component from The Design System renders its list box in a portal (on the top level of the DOM) by default, which makes it inaccessible when used in a <dialog> element. Therefore I have added this hack to always set portal to false when it is rendered within a dialog. As the Storybook demo (see image below) shows, this is not an optimal solution, but at least the list box is somewhat available to the users.

We need this because the code list library need to render comboboxes within a dialog. We should switch them out with something like Suggestion when we have upgraded The Design System.

Current solution:
image

This pull request:
image

Related Issue(s)

Verification

  • Your code builds clean without any errors or warnings
  • Manual testing done (required)
  • Relevant automated test added (if you find this hard, leave it and we'll help out)

Summary by CodeRabbit

  • New Features

    • Introduced a new demonstration mode that showcases the combobox within a modal context.
    • Enhanced the component’s adaptability by automatically adjusting its display when used in dialog environments for a seamless experience.
  • Tests

    • Expanded test coverage to validate proper rendering and interaction across different usage scenarios, ensuring robust performance.
    • Added tests to verify the functionality of the new isWithinDialog function, ensuring accurate context detection.

Copy link
Contributor

coderabbitai bot commented Feb 13, 2025

📝 Walkthrough

Walkthrough

This pull request introduces changes to the StudioCombobox component and its supporting files. It adds a new Storybook story, InModal, which demonstrates the component rendered inside a modal. The tests for StudioCombobox are enhanced to cover additional rendering scenarios such as portal mode, wrapper element usage, dialog embedding, and ref forwarding. The component itself is updated to accept a new portal prop that conditionally disables portal behavior when within a dialog, using an internal detection via the isWithinDialog function. Additionally, a new helper function, isWithinDialog, and its tests have been added.

Changes

Files Change Summary
.../StudioCombobox.stories.tsx Added a new Storybook story export InModal that renders StudioCombobox within a modal context using a trigger button and dialog, mirroring options from an existing preview story.
.../StudioCombobox.test.tsx Enhanced test coverage by adding cases for default portal mode, rendering within a wrapper and dialog, and verifying ref forwarding. Modified renderTestCombobox to accept additional parameters for flexibility in tests.
.../StudioCombobox.tsx Updated the component to accept a new optional prop portal (defaulting to true) and implemented internal logic that disables the portal if the component is detected within a dialog via the isWithinDialog function.
.../isWithinDialog.ts
.../isWithinDialog.test.tsx
Introduced the isWithinDialog function that checks if an element is within a <dialog> using the closest method, along with corresponding tests to verify its behavior.

Suggested labels

area/ui-editor

Suggested reviewers

  • Jondyr
  • mlqn

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

frontend/libs/studio-components/src/components/StudioCombobox/StudioCombobox.test.tsx

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-storybook".

(The package "eslint-plugin-storybook" was not found when loaded as a Node module from the directory "/frontend/libs/studio-components".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-storybook@latest --save-dev

The plugin "eslint-plugin-storybook" was referenced from the config file in "frontend/libs/studio-components/.eslintrc.js".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.

frontend/libs/studio-components/src/components/StudioCombobox/StudioCombobox.tsx

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-storybook".

(The package "eslint-plugin-storybook" was not found when loaded as a Node module from the directory "/frontend/libs/studio-components".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-storybook@latest --save-dev

The plugin "eslint-plugin-storybook" was referenced from the config file in "frontend/libs/studio-components/.eslintrc.js".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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.

@github-actions github-actions bot added solution/studio/designer Issues related to the Altinn Studio Designer solution. frontend labels Feb 13, 2025
@TomasEng TomasEng added team/studio-domain1 area/content-library Area: Related to library for shared resources area/studio-components Area: Related to studio-components library skip-releasenotes Issues that do not make sense to list in our release notes skip-documentation Issues where updating documentation is not relevant labels Feb 13, 2025
@TomasEng TomasEng marked this pull request as ready for review February 13, 2025 14:34
Copy link

codecov bot commented Feb 13, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 95.76%. Comparing base (2badc34) to head (e51bdaa).
Report is 5 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14661   +/-   ##
=======================================
  Coverage   95.75%   95.76%           
=======================================
  Files        1913     1914    +1     
  Lines       24925    24936   +11     
  Branches     2848     2849    +1     
=======================================
+ Hits        23868    23879   +11     
  Misses        799      799           
  Partials      258      258           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

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

🧹 Nitpick comments (3)
frontend/libs/studio-components/src/components/StudioCombobox/isWithinDialog.test.tsx (1)

5-21: Consider adding edge case tests.

The current test coverage is good but could be enhanced with additional edge cases:

  • Nested dialogs
  • Closed dialog
  • Null/undefined element

Here's an example of additional test cases:

 describe('isWithinDialog', () => {
   it('Returns true when the element is inside a dialog', () => {
     render(
       <dialog open>
         <button />
       </dialog>,
     );
     const button = screen.getByRole('button');
     expect(isWithinDialog(button)).toBe(true);
   });

   it('Returns false when the element is not inside a dialog', () => {
     render(<button />);
     const button = screen.getByRole('button');
     expect(isWithinDialog(button)).toBe(false);
   });
+
+  it('Returns true for element in nested dialogs', () => {
+    render(
+      <dialog open>
+        <dialog open>
+          <button />
+        </dialog>
+      </dialog>,
+    );
+    const button = screen.getByRole('button');
+    expect(isWithinDialog(button)).toBe(true);
+  });
+
+  it('Returns true for element in closed dialog', () => {
+    render(
+      <dialog>
+        <button />
+      </dialog>,
+    );
+    const button = screen.getByRole('button');
+    expect(isWithinDialog(button)).toBe(true);
+  });
 });
frontend/libs/studio-components/src/components/StudioCombobox/StudioCombobox.tsx (1)

16-22: Consider memoizing the callback with useCallback.

The callback is already memoized with useCallback, but it could be optimized further by moving the dialog check logic outside the callback.

Here's a suggested optimization:

-    const internalRef = useCallback(
-      (node?: HTMLInputElement) => {
-        forwardedRef.current = node;
-        if (node && isWithinDialog(node)) setPortal(false);
-      },
-      [forwardedRef],
-    );
+    const checkDialog = useCallback(
+      (node?: HTMLInputElement) => {
+        if (node && isWithinDialog(node)) setPortal(false);
+      },
+      [],
+    );
+
+    const internalRef = useCallback(
+      (node?: HTMLInputElement) => {
+        forwardedRef.current = node;
+        checkDialog(node);
+      },
+      [forwardedRef, checkDialog],
+    );
frontend/libs/studio-components/src/components/StudioCombobox/StudioCombobox.test.tsx (1)

144-144: Replace empty object type with explicit type.

The empty object type {} is flagged by static analysis as it can lead to type safety issues. Consider using a more explicit type.

Apply this change to all three wrapper implementations:

-const wrapper = ({ children }: PropsWithChildren<{}>) =>
+const wrapper = ({ children }: PropsWithChildren<Record<string, never>>) =>

Or create a reusable type:

type WrapperProps = PropsWithChildren<Record<string, never>>;

Also applies to: 155-155, 166-166

🧰 Tools
🪛 Biome (1.9.4)

[error] 144-144: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9b93ad0 and 167c167.

📒 Files selected for processing (5)
  • frontend/libs/studio-components/src/components/StudioCombobox/StudioCombobox.stories.tsx (2 hunks)
  • frontend/libs/studio-components/src/components/StudioCombobox/StudioCombobox.test.tsx (2 hunks)
  • frontend/libs/studio-components/src/components/StudioCombobox/StudioCombobox.tsx (1 hunks)
  • frontend/libs/studio-components/src/components/StudioCombobox/isWithinDialog.test.tsx (1 hunks)
  • frontend/libs/studio-components/src/components/StudioCombobox/isWithinDialog.ts (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
frontend/libs/studio-components/src/components/StudioCombobox/StudioCombobox.test.tsx

[error] 144-144: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)


[error] 155-155: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)


[error] 166-166: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)

🔇 Additional comments (7)
frontend/libs/studio-components/src/components/StudioCombobox/isWithinDialog.ts (1)

1-3: LGTM! Clean and focused implementation.

The function is well-implemented, using standard DOM APIs and proper null safety checks.

frontend/libs/studio-components/src/components/StudioCombobox/StudioCombobox.tsx (2)

12-14: LGTM! Clean props and state management.

Good implementation of:

  • Default portal behavior
  • Proper state initialization with prop value
  • Clear prop naming convention

24-28: LGTM! Clean component rendering.

The component correctly passes the portal state to the Combobox component.

frontend/libs/studio-components/src/components/StudioCombobox/StudioCombobox.stories.tsx (1)

40-54: LGTM! Well-structured story demonstrating modal context.

The story effectively demonstrates the combobox behavior within a modal context, following Storybook best practices.

frontend/libs/studio-components/src/components/StudioCombobox/StudioCombobox.test.tsx (3)

1-7: LGTM! Type imports enhance type safety.

The new type imports and utility imports are well-organized and necessary for the enhanced test coverage.


142-177: LGTM! Comprehensive test coverage for portal behavior and ref forwarding.

The new test cases effectively validate:

  1. Default portal behavior
  2. Non-portal behavior with wrapper
  3. Dialog-specific behavior
  4. Ref forwarding functionality

These tests align perfectly with the PR's objective of fixing combobox accessibility within dialogs.

🧰 Tools
🪛 Biome (1.9.4)

[error] 144-144: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)


[error] 155-155: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)


[error] 166-166: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)


180-193: LGTM! Enhanced test utility with backward compatibility.

The renderTestCombobox function has been thoughtfully updated to support new test scenarios while maintaining compatibility with existing tests.

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

🧹 Nitpick comments (1)
frontend/libs/studio-components/src/components/StudioCombobox/StudioCombobox.tsx (1)

16-26: Consider memoizing the ref callback dependencies.

The implementation correctly detects dialog context and updates portal state. However, the dependencies of the callbacks could be memoized to prevent unnecessary re-renders.

 export const StudioCombobox = forwardRef<HTMLInputElement, StudioComboboxProps>(
   ({ children, size = 'sm', portal: givenPortal = true, ...rest }, ref): JSX.Element => {
     const forwardedRef = useForwardedRef<HTMLInputElement>(ref);
     const [portal, setPortal] = useState<boolean>(givenPortal);
+    const setPortalFalse = useCallback(() => setPortal(false), []);
 
     const removePortalIfInDialog = useCallback((node: HTMLInputElement | null): void => {
-      if (node && isWithinDialog(node)) setPortal(false);
+      if (node && isWithinDialog(node)) setPortalFalse();
-    }, []);
+    }, [setPortalFalse]);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 167c167 and e51bdaa.

📒 Files selected for processing (2)
  • frontend/libs/studio-components/src/components/StudioCombobox/StudioCombobox.test.tsx (2 hunks)
  • frontend/libs/studio-components/src/components/StudioCombobox/StudioCombobox.tsx (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Build environment and run e2e test
  • GitHub Check: Typechecking and linting
  • GitHub Check: Testing
  • GitHub Check: CodeQL
🔇 Additional comments (7)
frontend/libs/studio-components/src/components/StudioCombobox/StudioCombobox.tsx (3)

1-1: LGTM! Good choice of hooks and utilities.

The added imports enhance the component's functionality:

  • useForwardedRef for proper ref forwarding
  • isWithinDialog for dialog detection

Also applies to: 6-7


12-14: LGTM! Well-structured prop handling and ref management.

Good practices observed:

  • Default portal behavior preserved with givenPortal = true
  • Proper ref forwarding using the useForwardedRef hook

29-31: LGTM! Clean component rendering.

The component correctly applies the portal state and forwards all other props.

frontend/libs/studio-components/src/components/StudioCombobox/StudioCombobox.test.tsx (4)

1-1: LGTM! Good test setup with proper types.

The added imports enhance test type safety and provide necessary testing utilities.

Also applies to: 3-3, 7-7


142-170: LGTM! Comprehensive portal behavior testing.

The tests effectively cover:

  • Default portal behavior
  • Explicit portal disable
  • Automatic portal disable in dialog context

172-184: LGTM! Thorough ref forwarding tests.

The tests properly verify:

  • Ref forwarding to the input element
  • Ref cleanup on unmount

187-200: LGTM! Well-structured test helper.

The renderTestCombobox helper is properly enhanced to support:

  • Custom render options
  • Ref forwarding
  • Consistent test data

@ErlingHauan ErlingHauan self-assigned this Feb 14, 2025
Copy link
Contributor

@ErlingHauan ErlingHauan left a comment

Choose a reason for hiding this comment

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

Brilliant!

@ErlingHauan ErlingHauan removed their assignment Feb 14, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area/content-library Area: Related to library for shared resources area/studio-components Area: Related to studio-components library frontend skip-documentation Issues where updating documentation is not relevant skip-releasenotes Issues that do not make sense to list in our release notes solution/studio/designer Issues related to the Altinn Studio Designer solution. team/studio-domain1
Projects
Status: 🧪 Test
Development

Successfully merging this pull request may close these issues.

2 participants