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

Fixing the AlertDialogPortal dark mode #470

Merged
merged 2 commits into from
Oct 26, 2024

Conversation

impirios
Copy link
Contributor

@impirios impirios commented Oct 26, 2024

Closes #468
We're using FloatingPortal from floating-ui/react as a way to add the dialog box children to the dom. by default it uses the document.body element and adds the HTML as a child to it so the dark theme classes didn't work on it

Solution

we will be using the rootClass from the AlertDialogRoot in AlertDialogPortal and get the element and pass it to the FloatingPortal.
Screenshot 2024-10-26 at 4 33 56 PM
Screenshot 2024-10-26 at 4 34 08 PM

Summary by CodeRabbit

  • New Features
    • Introduced a context for the Alert Dialog, enhancing type safety and flexibility.
    • Updated the AlertDialogPortal to dynamically determine the root element based on context.
    • Added default functionality for the onClickOutside prop in the AlertDialogRoot component to prevent runtime errors.
  • Style
    • Revised CSS for the alert dialog to utilize CSS variables for improved theming and readability.

…that we want to add the AlertDialogPortal as a child of.
Copy link
Contributor

coderabbitai bot commented Oct 26, 2024

Walkthrough

The changes in this pull request involve modifications to the AlertDialog component's context and related components. A new type definition for AlertDialogContextType is introduced to enhance type safety, and the AlertDialogContext is created with default values. The AlertDialogPortal component is updated to utilize this context for determining the portal's root element. Additionally, minor formatting changes are made in the AlertDialogRoot component, and the CSS for the alert dialog is updated to use CSS variables instead of fixed colors.

Changes

File Path Change Summary
src/components/ui/AlertDialog/contexts/AlertDialogContext.tsx Added AlertDialogContextType type definition and created AlertDialogContext with default values.
src/components/ui/AlertDialog/shards/AlertDialogPortal.tsx Updated import statements and modified internal logic to use AlertDialogContext for determining the portal's root element.
src/components/ui/AlertDialog/shards/AlertDialogRoot.tsx Minor formatting change (added space before closing angle bracket of a <div> element). Defaulted onClickOutside prop to an empty function.
styles/themes/components/alert-dialog.scss Updated CSS to use CSS variables for background and text colors, improving readability of the CSS formatting.

Possibly related issues

Possibly related PRs

  • AlertDialog Component #448: This PR directly utilizes the AlertDialogContext, which is the primary focus of the changes in this main PR, enhancing the context's type safety and structure.

🐰 In the meadow where dialogs bloom,
A context was crafted to chase away gloom.
With colors that dance like the soft morning light,
Our alerts now shine, oh what a delight!
So hop with joy, let the changes take flight! 🌼


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 193479c and b1a3e1c.

📒 Files selected for processing (3)
  • src/components/ui/AlertDialog/contexts/AlertDialogContext.tsx (1 hunks)
  • src/components/ui/AlertDialog/shards/AlertDialogPortal.tsx (1 hunks)
  • src/components/ui/AlertDialog/shards/AlertDialogRoot.tsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/components/ui/AlertDialog/contexts/AlertDialogContext.tsx
  • src/components/ui/AlertDialog/shards/AlertDialogPortal.tsx
  • src/components/ui/AlertDialog/shards/AlertDialogRoot.tsx

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.

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.

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: 2

🧹 Outside diff range and nitpick comments (2)
src/components/ui/AlertDialog/contexts/AlertDialogContext.tsx (1)

4-10: Consider enhancing type safety with explicit return types and type narrowing.

The type definition is well-structured, but could benefit from some improvements:

 type AlertDialogContextType = {
   isOpen: boolean;
   handleOpenChange: (open: boolean) => void;
-  floaterContext: FloatingContext;
+  floaterContext: Pick<FloatingContext, 'refs' | 'floatingStyles'>;
-  handleOverlayClick: () => void;
+  handleOverlayClick: () => void | undefined;
   rootClass: string;
 };

This change:

  1. Narrows down FloatingContext to only required properties
  2. Makes the return type of handleOverlayClick explicit
src/components/ui/AlertDialog/shards/AlertDialogPortal.tsx (1)

Line range hint 1-21: Architecture suggestion: Consider using data attributes.

While using class names works, consider using data attributes (e.g., data-alert-dialog-root) instead of classes for targeting portal containers. This separates styling concerns from DOM targeting and prevents potential conflicts with CSS classes.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between e0af5db and 193479c.

📒 Files selected for processing (4)
  • src/components/ui/AlertDialog/contexts/AlertDialogContext.tsx (1 hunks)
  • src/components/ui/AlertDialog/shards/AlertDialogPortal.tsx (1 hunks)
  • src/components/ui/AlertDialog/shards/AlertDialogRoot.tsx (1 hunks)
  • styles/themes/components/alert-dialog.scss (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • src/components/ui/AlertDialog/shards/AlertDialogRoot.tsx
  • styles/themes/components/alert-dialog.scss
🔇 Additional comments (3)
src/components/ui/AlertDialog/contexts/AlertDialogContext.tsx (1)

8-8: Verify dark mode class propagation.

The rootClass implementation aligns with the PR objective of fixing dark mode styling. Let's verify its usage:

Also applies to: 16-16

✅ Verification successful

Dark mode class propagation implementation is correct

The verification shows the rootClass implementation is working as intended:

  • AlertDialogRoot generates the root class using customClassSwitcher
  • The class is properly distributed through context to all child components (Portal, Overlay, Content)
  • The component uses the RAD UI class naming convention (rad-ui-alert-dialog) which supports theme inheritance
  • Dark mode classes can be applied either through the default class or a custom root class
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check how rootClass is being used in AlertDialogPortal and related components
ast-grep --pattern 'rootClass = useContext(AlertDialogContext)'

# Verify if there are any direct dark mode class references
rg -l 'dark|theme' src/components/ui/AlertDialog/

Length of output: 117


Script:

#!/bin/bash
# Let's try a broader search for AlertDialogContext usage
ast-grep --pattern 'useContext(AlertDialogContext)'

# Search for rootClass usage in AlertDialog components
rg 'rootClass' src/components/ui/AlertDialog/ -A 2

# Check AlertDialogPortal implementation
fd AlertDialogPortal.tsx -t f -x cat {}

# Look for dark mode related classes in the component
rg -i 'className.*dark' src/components/ui/AlertDialog/

Length of output: 4560


Script:

#!/bin/bash
# Let's check how customClassSwitcher is used for dark mode
rg -l "customClassSwitcher" src/core/
cat $(fd "customClassSwitcher" src/core/)

# Check the actual class name generation
rg "COMPONENT_NAME.*AlertDialog" src/components/ui/AlertDialog/ -A 2

Length of output: 1162

src/components/ui/AlertDialog/shards/AlertDialogPortal.tsx (2)

1-1: LGTM: Import statements are appropriate.

The added imports for useContext and AlertDialogContext are necessary for the dark mode fix implementation.

Also applies to: 3-3


11-12: Verify error handling for missing root element.

While the implementation correctly retrieves the root element using the class name, we should consider the case where no element with the specified class exists.

Let's verify the usage of this class across the codebase:

Comment on lines 12 to 18
export const AlertDialogContext = createContext<AlertDialogContextType>({
isOpen: false,
handleOpenChange: () => {},
floaterContext: {} as FloatingContext,
rootClass: '',
handleOverlayClick: () => {},
});
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid unsafe type casting for FloatingContext default value.

The current implementation uses an unsafe type cast for the floaterContext default value. Consider providing a safer default implementation:

 export const AlertDialogContext = createContext<AlertDialogContextType>({
   isOpen: false,
   handleOpenChange: () => {},
-  floaterContext: {} as FloatingContext,
+  floaterContext: {
+    refs: { reference: null, floating: null, domReference: null },
+    floatingStyles: { position: 'fixed', top: '0', left: '0' }
+  },
   rootClass: '',
   handleOverlayClick: () => {},
 });

This provides a proper default structure that matches the expected FloatingContext shape, making it safer and more predictable.

Committable suggestion was skipped due to low confidence.

return (
<Floater.Portal>
<Floater.Portal root={rootElement || document.body}>
Copy link
Contributor

@coderabbitai coderabbitai bot Oct 26, 2024

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider adding a warning for fallback to document.body.

The fallback to document.body is correct, but it might be worth logging a warning in development when this happens as it indicates the dark mode won't work as expected.

- <Floater.Portal root={rootElement || document.body}>
+ <Floater.Portal 
+   root={rootElement || (() => {
+     if (process.env.NODE_ENV === 'development') {
+       console.warn(
+         `AlertDialog: No element found with class "${rootClass}". ` +
+         'Falling back to document.body. Dark mode styling may not work correctly.'
+       );
+     }
+     return document.body;
+   })()}>
📝 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
<Floater.Portal root={rootElement || document.body}>
<Floater.Portal
root={rootElement || (() => {
if (process.env.NODE_ENV === 'development') {
console.warn(
`AlertDialog: No element found with class "${rootClass}". ` +
'Falling back to document.body. Dark mode styling may not work correctly.'
);
}
return document.body;
})()}>

Copy link
Collaborator

Choose a reason for hiding this comment

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

should we accept this suggestion? @impirios

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!

@@ -1,5 +1,18 @@
import { createContext } from 'react';
import { FloatingContext } from '@floating-ui/react';
Copy link
Collaborator

Choose a reason for hiding this comment

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

we can use the Floater component, you can add the items you need from the floating UI library that way, instead of directly importing - this makes sure we use only the API we strictly declare to use from the library

z-index: 50;
background-color: rgba(0, 0, 0, 0.8);
.rad-ui-alert-dialog-overlay {
z-index: 50;
Copy link
Collaborator

Choose a reason for hiding this comment

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

we should probably have a lint commit hook for CSS files no? 😁

Copy link
Contributor Author

Choose a reason for hiding this comment

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

can keep it as a separate issue

Copy link
Collaborator

Choose a reason for hiding this comment

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

yess

@impirios impirios requested a review from kotAPI October 26, 2024 13:09
@kotAPI kotAPI merged commit 7052848 into rad-ui:main Oct 26, 2024
2 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Dec 1, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Preserve Dark Mode details when using React Portals
2 participants