Skip to content

fix(menu): portal content inside Theme scope (#1100)#2013

Closed
kotAPI wants to merge 1 commit into
mainfrom
fix/issue-1100-menu-portal-theme
Closed

fix(menu): portal content inside Theme scope (#1100)#2013
kotAPI wants to merge 1 commit into
mainfrom
fix/issue-1100-menu-portal-theme

Conversation

@kotAPI

@kotAPI kotAPI commented Jun 19, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • Menu portal targets ThemeContext refs with theme container fallbacks
  • Keeps optional container prop support

Fixes #1100

Test plan

  • npm test -- --testPathPatterns=MenuPrimitive.test
  • npm test -- --testPathPatterns=DropdownMenu.test

Summary by CodeRabbit

  • Improvements
    • Enhanced menu portal rendering with improved theme context integration and support for flexible container control, ensuring more reliable menu positioning and display.

Use ThemeContext portalRootRef and containerRef with theme container
fallbacks instead of querySelector-only resolution.

Fixes #1100
@changeset-bot

changeset-bot Bot commented Jun 19, 2026

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: ffb4de5

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@coderabbitai

coderabbitai Bot commented Jun 19, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

MenuPrimitivePortal is updated to accept an optional container prop and integrates ThemeContext to resolve the portal mount root via a useLayoutEffect. The previous module-level root query is replaced with a ref-based resolution chain, and rendering is deferred until after mount via an isMounted state flag.

Changes

MenuPrimitivePortal – container prop and ThemeContext root resolution

Layer / File(s) Summary
Portal root resolution, container prop, and render gating
src/core/primitives/Menu/fragments/MenuPrimitivePortal.tsx
MenuPrimitivePortalProps gains an optional container prop. useLayoutEffect replaces the previous useEffect-based logic; it stores the portal root in rootElementRef using container, themeContext.portalRootRef.current, themeContext.containerRef.current, or DOM fallbacks (#rad-ui-theme-container, document.body), then sets isMounted. The render path returns null until isMounted is true and uses rootElementRef.current as the Floater.Portal root.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

  • rad-ui/ui#1276: Directly modifies MenuPrimitivePortal and its portal-root resolution behavior, including document.querySelector mocking in tests — the same component and resolution path being changed here.
  • rad-ui/ui#1433: Also modifies MenuPrimitivePortal by extending its API (ref forwarding and portal props exposure), making it a direct predecessor to this PR's further extension with a container prop.

Suggested reviewers

  • mrkazmi333

Poem

🐇 Hop, hop, where shall the portal land?
No more guessing at module-scan time grand,
A container prop, a layout effect neat,
ThemeContext refs make the root complete —
isMounted says "now render, little door!"
The menu blooms where it's supposed to, once more. 🌸

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: fixing menu portal content to resolve correctly within Theme scope by using ThemeContext refs instead of DOM queries.
Linked Issues check ✅ Passed The PR directly addresses issue #1100 by implementing ThemeContext-aware portal root resolution, ensuring portals render as children of the Theme element using portalRootRef and containerRef with proper fallbacks.
Out of Scope Changes check ✅ Passed All changes are scoped to MenuPrimitivePortal component and directly address the portal root resolution issue. The optional container prop and ThemeContext integration are necessary to fix the reported problem.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/issue-1100-menu-portal-theme

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions

Copy link
Copy Markdown
Contributor

Coverage

This report compares the PR with the base branch. "Δ" shows how the PR affects each metric.

Metric PR Δ
Statements 75.73% +0.00%
Branches 59.2% +0.03%
Functions 61.75% +0.00%
Lines 77.26% +0.00%

Coverage improved or stayed the same. Great job!

Run npm run coverage:ci locally for detailed reports and target untested areas to raise these numbers.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/core/primitives/Menu/fragments/MenuPrimitivePortal.tsx`:
- Around line 24-27: The fallback order in the rootElementRef assignment within
MenuPrimitivePortal.tsx is incorrect for multi-theme documents. Reorder the
checks so that theme-scoped fallbacks (themeContext?.containerRef.current) are
evaluated before global portal queries
(document.querySelector('[data-rad-ui-portal-root]')). Move the
themeContext?.containerRef.current check to execute before the global
data-rad-ui-portal-root selector lookup to ensure theme-scoped containers take
precedence over global portal roots.
- Around line 17-31: The rootElementRef in MenuPrimitivePortal stores the
computed portal root in a ref, which doesn't trigger re-renders when updated.
When container or themeContext dependencies change, the component re-renders and
reads the stale rootElementRef.current value before useLayoutEffect updates it,
causing the portal to render with an outdated root. Instead of using useRef and
useLayoutEffect to compute and store the root element, replace this with useMemo
that depends on container and themeContext, so the computed portal root is
recalculated and available during render whenever dependencies change. Remove
the rootElementRef entirely and compute the portal root value directly inside a
useMemo hook.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 1c588d9e-17e6-45a3-8e05-c719c73dba21

📥 Commits

Reviewing files that changed from the base of the PR and between fe87b36 and ffb4de5.

📒 Files selected for processing (1)
  • src/core/primitives/Menu/fragments/MenuPrimitivePortal.tsx

Comment on lines +17 to +31
const rootElementRef = useRef<HTMLElement | null>(null);
const [isMounted, setIsMounted] = useState(false);

useEffect(() => {
if (rootElement) {
setRootElementFound(true);
useLayoutEffect(() => {
if (container) {
rootElementRef.current = container as HTMLElement;
} else {
rootElementRef.current = themeContext?.portalRootRef.current
|| document.querySelector('[data-rad-ui-portal-root]') as HTMLElement | null
|| themeContext?.containerRef.current
|| document.querySelector('#rad-ui-theme-container') as HTMLElement | null
|| document.body;
}
}, [rootElement]);
setIsMounted(true);
}, [container, themeContext]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

cat -n src/core/primitives/Menu/fragments/MenuPrimitivePortal.tsx | head -60

Repository: rad-ui/ui

Length of output: 2315


🏁 Script executed:

fd -t f Floater || rg -l "Floater" src/ | head -5

Repository: rad-ui/ui

Length of output: 35


🏁 Script executed:

find src -name "*loater*" -o -name "*Floater*" 2>/dev/null | head -10

Repository: rad-ui/ui

Length of output: 81


🏁 Script executed:

ls -la src/core/primitives/Floater/

Repository: rad-ui/ui

Length of output: 226


🏁 Script executed:

cat -n src/core/primitives/Floater/index.tsx

Repository: rad-ui/ui

Length of output: 1470


🏁 Script executed:

rg -B5 -A5 "MenuPrimitivePortal" src/ --type tsx | head -40

Repository: rad-ui/ui

Length of output: 81


🏁 Script executed:

rg -B5 -A5 "MenuPrimitivePortal" src/ | head -60

Repository: rad-ui/ui

Length of output: 4702


🏁 Script executed:

cat -n src/core/primitives/Menu/contexts/MenuPrimitiveRootContext.tsx

Repository: rad-ui/ui

Length of output: 1515


🏁 Script executed:

cat -n src/core/primitives/Menu/fragments/MenuPrimitiveRoot.tsx | head -80

Repository: rad-ui/ui

Length of output: 3522


🏁 Script executed:

rg -B3 -A3 "MenuPrimitive.Portal\|MenuPrimitivePortal" src/ | head -80

Repository: rad-ui/ui

Length of output: 35


🏁 Script executed:

find src -type f -name "*.tsx" -o -name "*.ts" | xargs grep -l "MenuPrimitive.Portal\|MenuPrimitivePortal" 2>/dev/null

Repository: rad-ui/ui

Length of output: 448


🏁 Script executed:

cat -n src/core/primitives/Menu/tests/MenuPrimitive.test.tsx | head -100

Repository: rad-ui/ui

Length of output: 4096


🏁 Script executed:

rg -A10 -B2 "container\|Portal" src/core/primitives/Menu/tests/MenuPrimitive.test.tsx | head -60

Repository: rad-ui/ui

Length of output: 35


🏁 Script executed:

cat -n src/components/ui/DropdownMenu/fragments/DropdownMenuPortal.tsx

Repository: rad-ui/ui

Length of output: 1232


🏁 Script executed:

cat -n src/core/primitives/Menu/fragments/MenuPrimitiveContent.tsx | head -80

Repository: rad-ui/ui

Length of output: 2297


🏁 Script executed:

python3 << 'PY'
# Let me analyze the timing issue more carefully
print("=== Ref Write vs State Update Timing ===")
print()
print("Current code (using ref):")
print("1. container/themeContext changes")
print("2. Component re-renders")
print("3. During render: rootElementRef.current = OLD value (effect hasn't run yet)")
print("4. Floater.Portal gets OLD root")
print("5. useLayoutEffect runs and updates rootElementRef.current")
print("6. Portal already rendered, won't update (ref changes don't trigger re-renders)")
print()
print("Proposed code (using state):")
print("1. container/themeContext changes") 
print("2. Component re-renders")
print("3. During render: rootElement = OLD value (effect hasn't run yet)")
print("4. useLayoutEffect runs and calls setRootElement(nextRoot)")
print("5. setRootElement triggers another re-render")
print("6. Second render uses NEW rootElement value")
print()
print("Conclusion: The ref approach has a 1-render delay in applying root changes.")
print("The state approach ensures correct value is used by triggering re-render.")
PY

Repository: rad-ui/ui

Length of output: 880


🏁 Script executed:

# Check if there are any usages showing the actual impact
rg -B5 -A5 "container\s*=" src/core/primitives/Menu/ | head -40

Repository: rad-ui/ui

Length of output: 35


Root element can become stale because ref writes don't trigger re-renders.

Lines 17-31 write the computed portal root into a ref, but line 38 reads it during render. When container or themeContext changes after initial mount, the component re-renders but reads the old ref value before useLayoutEffect updates it. The portal then renders with the stale root and never updates since ref mutations don't cause re-renders.

Suggested fix
-        const rootElementRef = useRef<HTMLElement | null>(null);
+        const [rootElement, setRootElement] = useState<HTMLElement | null>(null);
         const [isMounted, setIsMounted] = useState(false);

         useLayoutEffect(() => {
+            const nextRoot = container
+                ? (container as HTMLElement)
+                : (themeContext?.portalRootRef.current
+                    || themeContext?.containerRef.current
+                    || (document.querySelector('[data-rad-ui-portal-root]') as HTMLElement | null)
+                    || (document.querySelector('`#rad-ui-theme-container`') as HTMLElement | null)
+                    || document.body);
-            if (container) {
-                rootElementRef.current = container as HTMLElement;
-            } else {
-                rootElementRef.current = themeContext?.portalRootRef.current
-                    || document.querySelector('[data-rad-ui-portal-root]') as HTMLElement | null
-                    || themeContext?.containerRef.current
-                    || document.querySelector('`#rad-ui-theme-container`') as HTMLElement | null
-                    || document.body;
-            }
+            setRootElement(nextRoot);
             setIsMounted(true);
-        }, [container, themeContext]);
+        }, [container, themeContext, context?.isOpen]);

         if (!context) return null;
         const { isOpen } = context;
-        if (!isOpen || !isMounted) return null;
+        if (!isOpen || !isMounted || !rootElement) return null;

         return (
-            <Floater.Portal root={rootElementRef.current} {...props}>
+            <Floater.Portal root={rootElement} {...props}>
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/core/primitives/Menu/fragments/MenuPrimitivePortal.tsx` around lines 17 -
31, The rootElementRef in MenuPrimitivePortal stores the computed portal root in
a ref, which doesn't trigger re-renders when updated. When container or
themeContext dependencies change, the component re-renders and reads the stale
rootElementRef.current value before useLayoutEffect updates it, causing the
portal to render with an outdated root. Instead of using useRef and
useLayoutEffect to compute and store the root element, replace this with useMemo
that depends on container and themeContext, so the computed portal root is
recalculated and available during render whenever dependencies change. Remove
the rootElementRef entirely and compute the portal root value directly inside a
useMemo hook.

Comment on lines +24 to +27
rootElementRef.current = themeContext?.portalRootRef.current
|| document.querySelector('[data-rad-ui-portal-root]') as HTMLElement | null
|| themeContext?.containerRef.current
|| document.querySelector('#rad-ui-theme-container') as HTMLElement | null

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Prefer Theme-scoped fallback before global portal query.

On Line 25, the global [data-rad-ui-portal-root] lookup runs before Line 26 (themeContext?.containerRef.current), so in multi-theme documents this can mount into the wrong Theme subtree.

Suggested fix
-                rootElementRef.current = themeContext?.portalRootRef.current
-                    || document.querySelector('[data-rad-ui-portal-root]') as HTMLElement | null
-                    || themeContext?.containerRef.current
+                rootElementRef.current = themeContext?.portalRootRef.current
+                    || themeContext?.containerRef.current
+                    || document.querySelector('[data-rad-ui-portal-root]') as HTMLElement | null
                     || document.querySelector('`#rad-ui-theme-container`') as HTMLElement | null
                     || 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
rootElementRef.current = themeContext?.portalRootRef.current
|| document.querySelector('[data-rad-ui-portal-root]') as HTMLElement | null
|| themeContext?.containerRef.current
|| document.querySelector('#rad-ui-theme-container') as HTMLElement | null
rootElementRef.current = themeContext?.portalRootRef.current
|| themeContext?.containerRef.current
|| document.querySelector('[data-rad-ui-portal-root]') as HTMLElement | null
|| document.querySelector('`#rad-ui-theme-container`') as HTMLElement | null
|| document.body;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/core/primitives/Menu/fragments/MenuPrimitivePortal.tsx` around lines 24 -
27, The fallback order in the rootElementRef assignment within
MenuPrimitivePortal.tsx is incorrect for multi-theme documents. Reorder the
checks so that theme-scoped fallbacks (themeContext?.containerRef.current) are
evaluated before global portal queries
(document.querySelector('[data-rad-ui-portal-root]')). Move the
themeContext?.containerRef.current check to execute before the global
data-rad-ui-portal-root selector lookup to ensure theme-scoped containers take
precedence over global portal roots.

@kotAPI

kotAPI commented Jun 24, 2026

Copy link
Copy Markdown
Collaborator Author

Closing as duplicate of #2020

@kotAPI kotAPI closed this Jun 24, 2026
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.

BUG: Alert Dialog not spawning as a child to the provided root element

1 participant