Skip to content

Commit 142cfde

Browse files
authored
Fix FragmentInstance listener leak: normalize boolean vs object capture options per DOM spec (#36047)
## Summary `FragmentInstance.addEventListener` and `removeEventListener` fail to cross-match listeners when the `capture` option is passed as a **boolean** in one call and an **options object** in the other. This violates the [DOM Living Standard](https://dom.spec.whatwg.org/#dom-eventtarget-removeeventlistener), which states that `addEventListener(type, fn, true)` and `addEventListener(type, fn, {capture: true})` are identical. ### Root Cause In `ReactFiberConfigDOM.js`, the `normalizeListenerOptions` function generates a listener key string for deduplication. The boolean branch generates a **different format** than the object branch: ```js // Boolean branch (old) — produces "c=1" return `c=${opts ? '1' : '0'}`; // Object branch — produces "c=1&o=0&p=0" return `c=${opts.capture ? '1' : '0'}&o=${opts.once ? '1' : '0'}&p=${opts.passive ? '1' : '0'}`; ``` Because the keys differ, `indexOfEventListener` cannot match them — so `removeEventListener('click', fn, {capture: true})` silently fails to remove a listener registered with `addEventListener('click', fn, true)`, and vice versa. This causes a **memory leak and event listener accumulation** on all Fragment child DOM nodes. ### Fix Normalize the boolean branch to produce the same full key format: ```js // Boolean branch (fixed) — now produces "c=1&o=0&p=0" (matches object branch) return `c=${opts ? '1' : '0'}&o=0&p=0`; ``` This makes both forms produce an identical key, matching the DOM spec behavior. ### When Was This Introduced This bug has been present since `FragmentInstance` event listener tracking was first added. It became reachable in production as of [#36026](#36026) which enabled `enableFragmentRefs` + `enableFragmentRefsInstanceHandles` across all builds (merged 3 days ago). ### Tests Added two new regression tests to `ReactDOMFragmentRefs-test.js`: 1. `removes a capture listener registered with boolean when removed with options object` 2. `removes a capture listener registered with options object when removed with boolean` Both tests were failing before this fix and pass after. ## How did you test this change? Added two new automated tests covering both cross-form removal directions. Existing tests continue to pass. ## Changelog ### React DOM - **Fixed** `FragmentInstance.removeEventListener()` not removing capture-phase listeners when the `capture` option form (boolean vs options object) differs between `add` and `remove` calls.
1 parent 94643c3 commit 142cfde

2 files changed

Lines changed: 165 additions & 1 deletion

File tree

‎packages/react-dom-bindings/src/client/ReactFiberConfigDOM.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3093,7 +3093,7 @@ function normalizeListenerOptions(
30933093
return`c=${opts ? '1' : '0'}`;
30943094
}
30953095

3096-
return`c=${opts.capture ? '1' : '0'}&o=${opts.once ? '1' : '0'}&p=${opts.passive ? '1' : '0'}`;
3096+
return`c=${opts.capture ? '1' : '0'}`;
30973097
}
30983098
functionindexOfEventListener(
30993099
eventListeners: Array<StoredEventListener>,

‎packages/react-dom/src/__tests__/ReactDOMFragmentRefs-test.js‎

Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -814,6 +814,86 @@ describe('FragmentRefs', () => {
814814
expect(logs).toEqual([]);
815815
});
816816

817+
// @gate enableFragmentRefs
818+
it(
819+
'removes a capture listener registered with boolean when removed with options object',
820+
async()=>{
821+
constfragmentRef=React.createRef(null);
822+
functionTest(){
823+
return(
824+
<Fragmentref={fragmentRef}>
825+
<divid="child-a"/>
826+
</Fragment>
827+
);
828+
}
829+
constroot=ReactDOMClient.createRoot(container);
830+
awaitact(()=>{
831+
root.render(<Test/>);
832+
});
833+
834+
constlogs=[];
835+
functionlogCapture(){
836+
logs.push('capture');
837+
}
838+
839+
// Register with boolean `true` (capture phase)
840+
fragmentRef.current.addEventListener('click',logCapture,true);
841+
document.querySelector('#child-a').click();
842+
expect(logs).toEqual(['capture']);
843+
844+
logs.length=0;
845+
846+
// Remove with equivalent options object {capture: true}
847+
// Per DOM spec, these are identical - the listener MUST be removed
848+
fragmentRef.current.removeEventListener('click',logCapture,{
849+
capture: true,
850+
});
851+
document.querySelector('#child-a').click();
852+
// Listener should have been removed - logs must remain empty
853+
expect(logs).toEqual([]);
854+
},
855+
);
856+
857+
// @gate enableFragmentRefs
858+
it(
859+
'removes a capture listener registered with options object when removed with boolean',
860+
async()=>{
861+
constfragmentRef=React.createRef(null);
862+
functionTest(){
863+
return(
864+
<Fragmentref={fragmentRef}>
865+
<divid="child-b"/>
866+
</Fragment>
867+
);
868+
}
869+
constroot=ReactDOMClient.createRoot(container);
870+
awaitact(()=>{
871+
root.render(<Test/>);
872+
});
873+
874+
constlogs=[];
875+
functionlogCapture(){
876+
logs.push('capture');
877+
}
878+
879+
// Register with options object {capture: true}
880+
fragmentRef.current.addEventListener('click',logCapture,{
881+
capture: true,
882+
});
883+
document.querySelector('#child-b').click();
884+
expect(logs).toEqual(['capture']);
885+
886+
logs.length=0;
887+
888+
// Remove with boolean `true`
889+
// Per DOM spec, these are identical - the listener MUST be removed
890+
fragmentRef.current.removeEventListener('click',logCapture,true);
891+
document.querySelector('#child-b').click();
892+
// Listener should have been removed - logs must remain empty
893+
expect(logs).toEqual([]);
894+
},
895+
);
896+
817897
// @gate enableFragmentRefs
818898
it('applies event listeners to portaled children',async()=>{
819899
constfragmentRef=React.createRef();
@@ -2680,5 +2760,89 @@ describe('FragmentRefs', () => {
26802760
window.scrollTo=originalScrollTo;
26812761
restoreRange();
26822762
});
2763+
2764+
// @gate enableFragmentRefs
2765+
it(
2766+
'treats passive:true and passive:false as same listener per DOM spec',
2767+
async()=>{
2768+
constfragmentRef=React.createRef();
2769+
constroot=ReactDOMClient.createRoot(container);
2770+
2771+
awaitact(()=>{
2772+
root.render(
2773+
<Fragmentref={fragmentRef}>
2774+
<divid="child"/>
2775+
</Fragment>,
2776+
);
2777+
});
2778+
2779+
constlogs=[];
2780+
consthandler=()=>logs.push('fired');
2781+
2782+
constchild=document.querySelector('#child');
2783+
constspy=jest.spyOn(child,'addEventListener');
2784+
// Per DOM spec, listener identity is (type, callback, capture).
2785+
// passive is NOT part of the key, so these are the SAME listener.
2786+
fragmentRef.current.addEventListener('click',handler,{passive: false});
2787+
// Second add is a no-op: same (type, callback, capture) identity.
2788+
fragmentRef.current.addEventListener('click',handler,{passive: true});
2789+
expect(spy).toHaveBeenCalledTimes(1);
2790+
expect(spy).toHaveBeenCalledWith('click',handler,{passive: false});
2791+
2792+
document.querySelector('#child').click();
2793+
// First handler fires once (second add was a no-op).
2794+
expect(logs).toEqual(['fired']);
2795+
2796+
// removeEventListener also ignores passive when matching
2797+
fragmentRef.current.removeEventListener('click',handler,{
2798+
passive: true,
2799+
});
2800+
2801+
logs.length=0;
2802+
document.querySelector('#child').click();
2803+
expect(logs).toEqual([]);
2804+
},
2805+
);
2806+
// @gate enableFragmentRefs
2807+
it(
2808+
'removes a listener registered with passive:false when removed with passive:true',
2809+
async()=>{
2810+
constfragmentRef=React.createRef(null);
2811+
functionTest(){
2812+
return(
2813+
<>
2814+
<divid="child-x"/>
2815+
</>
2816+
);
2817+
}
2818+
constroot=ReactDOMClient.createRoot(container);
2819+
awaitact(()=>{
2820+
root.render(
2821+
<Fragmentref={fragmentRef}>
2822+
<Test/>
2823+
</Fragment>,
2824+
);
2825+
});
2826+
constlogs=[];
2827+
functionhandler(){
2828+
logs.push('fired');
2829+
}
2830+
// Register with passive: false
2831+
fragmentRef.current.addEventListener('click',handler,{
2832+
passive: false,
2833+
});
2834+
document.querySelector('#child-x').click();
2835+
expect(logs).toEqual(['fired']);
2836+
logs.length=0;
2837+
// Remove with passive: true - per DOM spec, passive is NOT part of identity
2838+
// so this MUST remove the listener regardless of passive mismatch.
2839+
fragmentRef.current.removeEventListener('click',handler,{
2840+
passive: true,
2841+
});
2842+
document.querySelector('#child-x').click();
2843+
// Listener removed - no more invocations
2844+
expect(logs).toEqual([]);
2845+
},
2846+
);
26832847
});
26842848
});

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Fix FragmentInstance listener leak: normalize boolean vs object captu… · react/react@142cfde · GitHub
Skip to content

Commit 142cfde

Browse files
authored
Fix FragmentInstance listener leak: normalize boolean vs object capture options per DOM spec (#36047)
## Summary `FragmentInstance.addEventListener` and `removeEventListener` fail to cross-match listeners when the `capture` option is passed as a **boolean** in one call and an **options object** in the other. This violates the [DOM Living Standard](https://dom.spec.whatwg.org/#dom-eventtarget-removeeventlistener), which states that `addEventListener(type, fn, true)` and `addEventListener(type, fn, {capture: true})` are identical. ### Root Cause In `ReactFiberConfigDOM.js`, the `normalizeListenerOptions` function generates a listener key string for deduplication. The boolean branch generates a **different format** than the object branch: ```js // Boolean branch (old) — produces "c=1" return `c=${opts ? '1' : '0'}`; // Object branch — produces "c=1&o=0&p=0" return `c=${opts.capture ? '1' : '0'}&o=${opts.once ? '1' : '0'}&p=${opts.passive ? '1' : '0'}`; ``` Because the keys differ, `indexOfEventListener` cannot match them — so `removeEventListener('click', fn, {capture: true})` silently fails to remove a listener registered with `addEventListener('click', fn, true)`, and vice versa. This causes a **memory leak and event listener accumulation** on all Fragment child DOM nodes. ### Fix Normalize the boolean branch to produce the same full key format: ```js // Boolean branch (fixed) — now produces "c=1&o=0&p=0" (matches object branch) return `c=${opts ? '1' : '0'}&o=0&p=0`; ``` This makes both forms produce an identical key, matching the DOM spec behavior. ### When Was This Introduced This bug has been present since `FragmentInstance` event listener tracking was first added. It became reachable in production as of [#36026](#36026) which enabled `enableFragmentRefs` + `enableFragmentRefsInstanceHandles` across all builds (merged 3 days ago). ### Tests Added two new regression tests to `ReactDOMFragmentRefs-test.js`: 1. `removes a capture listener registered with boolean when removed with options object` 2. `removes a capture listener registered with options object when removed with boolean` Both tests were failing before this fix and pass after. ## How did you test this change? Added two new automated tests covering both cross-form removal directions. Existing tests continue to pass. ## Changelog ### React DOM - **Fixed** `FragmentInstance.removeEventListener()` not removing capture-phase listeners when the `capture` option form (boolean vs options object) differs between `add` and `remove` calls.
1 parent 94643c3 commit 142cfde

2 files changed

Lines changed: 165 additions & 1 deletion

File tree

‎packages/react-dom-bindings/src/client/ReactFiberConfigDOM.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3093,7 +3093,7 @@ function normalizeListenerOptions(
30933093
return`c=${opts ? '1' : '0'}`;
30943094
}
30953095

3096-
return`c=${opts.capture ? '1' : '0'}&o=${opts.once ? '1' : '0'}&p=${opts.passive ? '1' : '0'}`;
3096+
return`c=${opts.capture ? '1' : '0'}`;
30973097
}
30983098
functionindexOfEventListener(
30993099
eventListeners: Array<StoredEventListener>,

‎packages/react-dom/src/__tests__/ReactDOMFragmentRefs-test.js‎

Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -814,6 +814,86 @@ describe('FragmentRefs', () => {
814814
expect(logs).toEqual([]);
815815
});
816816

817+
// @gate enableFragmentRefs
818+
it(
819+
'removes a capture listener registered with boolean when removed with options object',
820+
async()=>{
821+
constfragmentRef=React.createRef(null);
822+
functionTest(){
823+
return(
824+
<Fragmentref={fragmentRef}>
825+
<divid="child-a"/>
826+
</Fragment>
827+
);
828+
}
829+
constroot=ReactDOMClient.createRoot(container);
830+
awaitact(()=>{
831+
root.render(<Test/>);
832+
});
833+
834+
constlogs=[];
835+
functionlogCapture(){
836+
logs.push('capture');
837+
}
838+
839+
// Register with boolean `true` (capture phase)
840+
fragmentRef.current.addEventListener('click',logCapture,true);
841+
document.querySelector('#child-a').click();
842+
expect(logs).toEqual(['capture']);
843+
844+
logs.length=0;
845+
846+
// Remove with equivalent options object {capture: true}
847+
// Per DOM spec, these are identical - the listener MUST be removed
848+
fragmentRef.current.removeEventListener('click',logCapture,{
849+
capture: true,
850+
});
851+
document.querySelector('#child-a').click();
852+
// Listener should have been removed - logs must remain empty
853+
expect(logs).toEqual([]);
854+
},
855+
);
856+
857+
// @gate enableFragmentRefs
858+
it(
859+
'removes a capture listener registered with options object when removed with boolean',
860+
async()=>{
861+
constfragmentRef=React.createRef(null);
862+
functionTest(){
863+
return(
864+
<Fragmentref={fragmentRef}>
865+
<divid="child-b"/>
866+
</Fragment>
867+
);
868+
}
869+
constroot=ReactDOMClient.createRoot(container);
870+
awaitact(()=>{
871+
root.render(<Test/>);
872+
});
873+
874+
constlogs=[];
875+
functionlogCapture(){
876+
logs.push('capture');
877+
}
878+
879+
// Register with options object {capture: true}
880+
fragmentRef.current.addEventListener('click',logCapture,{
881+
capture: true,
882+
});
883+
document.querySelector('#child-b').click();
884+
expect(logs).toEqual(['capture']);
885+
886+
logs.length=0;
887+
888+
// Remove with boolean `true`
889+
// Per DOM spec, these are identical - the listener MUST be removed
890+
fragmentRef.current.removeEventListener('click',logCapture,true);
891+
document.querySelector('#child-b').click();
892+
// Listener should have been removed - logs must remain empty
893+
expect(logs).toEqual([]);
894+
},
895+
);
896+
817897
// @gate enableFragmentRefs
818898
it('applies event listeners to portaled children',async()=>{
819899
constfragmentRef=React.createRef();
@@ -2680,5 +2760,89 @@ describe('FragmentRefs', () => {
26802760
window.scrollTo=originalScrollTo;
26812761
restoreRange();
26822762
});
2763+
2764+
// @gate enableFragmentRefs
2765+
it(
2766+
'treats passive:true and passive:false as same listener per DOM spec',
2767+
async()=>{
2768+
constfragmentRef=React.createRef();
2769+
constroot=ReactDOMClient.createRoot(container);
2770+
2771+
awaitact(()=>{
2772+
root.render(
2773+
<Fragmentref={fragmentRef}>
2774+
<divid="child"/>
2775+
</Fragment>,
2776+
);
2777+
});
2778+
2779+
constlogs=[];
2780+
consthandler=()=>logs.push('fired');
2781+
2782+
constchild=document.querySelector('#child');
2783+
constspy=jest.spyOn(child,'addEventListener');
2784+
// Per DOM spec, listener identity is (type, callback, capture).
2785+
// passive is NOT part of the key, so these are the SAME listener.
2786+
fragmentRef.current.addEventListener('click',handler,{passive: false});
2787+
// Second add is a no-op: same (type, callback, capture) identity.
2788+
fragmentRef.current.addEventListener('click',handler,{passive: true});
2789+
expect(spy).toHaveBeenCalledTimes(1);
2790+
expect(spy).toHaveBeenCalledWith('click',handler,{passive: false});
2791+
2792+
document.querySelector('#child').click();
2793+
// First handler fires once (second add was a no-op).
2794+
expect(logs).toEqual(['fired']);
2795+
2796+
// removeEventListener also ignores passive when matching
2797+
fragmentRef.current.removeEventListener('click',handler,{
2798+
passive: true,
2799+
});
2800+
2801+
logs.length=0;
2802+
document.querySelector('#child').click();
2803+
expect(logs).toEqual([]);
2804+
},
2805+
);
2806+
// @gate enableFragmentRefs
2807+
it(
2808+
'removes a listener registered with passive:false when removed with passive:true',
2809+
async()=>{
2810+
constfragmentRef=React.createRef(null);
2811+
functionTest(){
2812+
return(
2813+
<>
2814+
<divid="child-x"/>
2815+
</>
2816+
);
2817+
}
2818+
constroot=ReactDOMClient.createRoot(container);
2819+
awaitact(()=>{
2820+
root.render(
2821+
<Fragmentref={fragmentRef}>
2822+
<Test/>
2823+
</Fragment>,
2824+
);
2825+
});
2826+
constlogs=[];
2827+
functionhandler(){
2828+
logs.push('fired');
2829+
}
2830+
// Register with passive: false
2831+
fragmentRef.current.addEventListener('click',handler,{
2832+
passive: false,
2833+
});
2834+
document.querySelector('#child-x').click();
2835+
expect(logs).toEqual(['fired']);
2836+
logs.length=0;
2837+
// Remove with passive: true - per DOM spec, passive is NOT part of identity
2838+
// so this MUST remove the listener regardless of passive mismatch.
2839+
fragmentRef.current.removeEventListener('click',handler,{
2840+
passive: true,
2841+
});
2842+
document.querySelector('#child-x').click();
2843+
// Listener removed - no more invocations
2844+
expect(logs).toEqual([]);
2845+
},
2846+
);
26832847
});
26842848
});

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Fix FragmentInstance listener leak: normalize boolean vs object captu… · react/react@142cfde · GitHub
Skip to content

Commit 142cfde

Browse files
authored
Fix FragmentInstance listener leak: normalize boolean vs object capture options per DOM spec (#36047)
## Summary `FragmentInstance.addEventListener` and `removeEventListener` fail to cross-match listeners when the `capture` option is passed as a **boolean** in one call and an **options object** in the other. This violates the [DOM Living Standard](https://dom.spec.whatwg.org/#dom-eventtarget-removeeventlistener), which states that `addEventListener(type, fn, true)` and `addEventListener(type, fn, {capture: true})` are identical. ### Root Cause In `ReactFiberConfigDOM.js`, the `normalizeListenerOptions` function generates a listener key string for deduplication. The boolean branch generates a **different format** than the object branch: ```js // Boolean branch (old) — produces "c=1" return `c=${opts ? '1' : '0'}`; // Object branch — produces "c=1&o=0&p=0" return `c=${opts.capture ? '1' : '0'}&o=${opts.once ? '1' : '0'}&p=${opts.passive ? '1' : '0'}`; ``` Because the keys differ, `indexOfEventListener` cannot match them — so `removeEventListener('click', fn, {capture: true})` silently fails to remove a listener registered with `addEventListener('click', fn, true)`, and vice versa. This causes a **memory leak and event listener accumulation** on all Fragment child DOM nodes. ### Fix Normalize the boolean branch to produce the same full key format: ```js // Boolean branch (fixed) — now produces "c=1&o=0&p=0" (matches object branch) return `c=${opts ? '1' : '0'}&o=0&p=0`; ``` This makes both forms produce an identical key, matching the DOM spec behavior. ### When Was This Introduced This bug has been present since `FragmentInstance` event listener tracking was first added. It became reachable in production as of [#36026](#36026) which enabled `enableFragmentRefs` + `enableFragmentRefsInstanceHandles` across all builds (merged 3 days ago). ### Tests Added two new regression tests to `ReactDOMFragmentRefs-test.js`: 1. `removes a capture listener registered with boolean when removed with options object` 2. `removes a capture listener registered with options object when removed with boolean` Both tests were failing before this fix and pass after. ## How did you test this change? Added two new automated tests covering both cross-form removal directions. Existing tests continue to pass. ## Changelog ### React DOM - **Fixed** `FragmentInstance.removeEventListener()` not removing capture-phase listeners when the `capture` option form (boolean vs options object) differs between `add` and `remove` calls.
1 parent 94643c3 commit 142cfde

2 files changed

Lines changed: 165 additions & 1 deletion

File tree

‎packages/react-dom-bindings/src/client/ReactFiberConfigDOM.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3093,7 +3093,7 @@ function normalizeListenerOptions(
30933093
return`c=${opts ? '1' : '0'}`;
30943094
}
30953095

3096-
return`c=${opts.capture ? '1' : '0'}&o=${opts.once ? '1' : '0'}&p=${opts.passive ? '1' : '0'}`;
3096+
return`c=${opts.capture ? '1' : '0'}`;
30973097
}
30983098
functionindexOfEventListener(
30993099
eventListeners: Array<StoredEventListener>,

‎packages/react-dom/src/__tests__/ReactDOMFragmentRefs-test.js‎

Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -814,6 +814,86 @@ describe('FragmentRefs', () => {
814814
expect(logs).toEqual([]);
815815
});
816816

817+
// @gate enableFragmentRefs
818+
it(
819+
'removes a capture listener registered with boolean when removed with options object',
820+
async()=>{
821+
constfragmentRef=React.createRef(null);
822+
functionTest(){
823+
return(
824+
<Fragmentref={fragmentRef}>
825+
<divid="child-a"/>
826+
</Fragment>
827+
);
828+
}
829+
constroot=ReactDOMClient.createRoot(container);
830+
awaitact(()=>{
831+
root.render(<Test/>);
832+
});
833+
834+
constlogs=[];
835+
functionlogCapture(){
836+
logs.push('capture');
837+
}
838+
839+
// Register with boolean `true` (capture phase)
840+
fragmentRef.current.addEventListener('click',logCapture,true);
841+
document.querySelector('#child-a').click();
842+
expect(logs).toEqual(['capture']);
843+
844+
logs.length=0;
845+
846+
// Remove with equivalent options object {capture: true}
847+
// Per DOM spec, these are identical - the listener MUST be removed
848+
fragmentRef.current.removeEventListener('click',logCapture,{
849+
capture: true,
850+
});
851+
document.querySelector('#child-a').click();
852+
// Listener should have been removed - logs must remain empty
853+
expect(logs).toEqual([]);
854+
},
855+
);
856+
857+
// @gate enableFragmentRefs
858+
it(
859+
'removes a capture listener registered with options object when removed with boolean',
860+
async()=>{
861+
constfragmentRef=React.createRef(null);
862+
functionTest(){
863+
return(
864+
<Fragmentref={fragmentRef}>
865+
<divid="child-b"/>
866+
</Fragment>
867+
);
868+
}
869+
constroot=ReactDOMClient.createRoot(container);
870+
awaitact(()=>{
871+
root.render(<Test/>);
872+
});
873+
874+
constlogs=[];
875+
functionlogCapture(){
876+
logs.push('capture');
877+
}
878+
879+
// Register with options object {capture: true}
880+
fragmentRef.current.addEventListener('click',logCapture,{
881+
capture: true,
882+
});
883+
document.querySelector('#child-b').click();
884+
expect(logs).toEqual(['capture']);
885+
886+
logs.length=0;
887+
888+
// Remove with boolean `true`
889+
// Per DOM spec, these are identical - the listener MUST be removed
890+
fragmentRef.current.removeEventListener('click',logCapture,true);
891+
document.querySelector('#child-b').click();
892+
// Listener should have been removed - logs must remain empty
893+
expect(logs).toEqual([]);
894+
},
895+
);
896+
817897
// @gate enableFragmentRefs
818898
it('applies event listeners to portaled children',async()=>{
819899
constfragmentRef=React.createRef();
@@ -2680,5 +2760,89 @@ describe('FragmentRefs', () => {
26802760
window.scrollTo=originalScrollTo;
26812761
restoreRange();
26822762
});
2763+
2764+
// @gate enableFragmentRefs
2765+
it(
2766+
'treats passive:true and passive:false as same listener per DOM spec',
2767+
async()=>{
2768+
constfragmentRef=React.createRef();
2769+
constroot=ReactDOMClient.createRoot(container);
2770+
2771+
awaitact(()=>{
2772+
root.render(
2773+
<Fragmentref={fragmentRef}>
2774+
<divid="child"/>
2775+
</Fragment>,
2776+
);
2777+
});
2778+
2779+
constlogs=[];
2780+
consthandler=()=>logs.push('fired');
2781+
2782+
constchild=document.querySelector('#child');
2783+
constspy=jest.spyOn(child,'addEventListener');
2784+
// Per DOM spec, listener identity is (type, callback, capture).
2785+
// passive is NOT part of the key, so these are the SAME listener.
2786+
fragmentRef.current.addEventListener('click',handler,{passive: false});
2787+
// Second add is a no-op: same (type, callback, capture) identity.
2788+
fragmentRef.current.addEventListener('click',handler,{passive: true});
2789+
expect(spy).toHaveBeenCalledTimes(1);
2790+
expect(spy).toHaveBeenCalledWith('click',handler,{passive: false});
2791+
2792+
document.querySelector('#child').click();
2793+
// First handler fires once (second add was a no-op).
2794+
expect(logs).toEqual(['fired']);
2795+
2796+
// removeEventListener also ignores passive when matching
2797+
fragmentRef.current.removeEventListener('click',handler,{
2798+
passive: true,
2799+
});
2800+
2801+
logs.length=0;
2802+
document.querySelector('#child').click();
2803+
expect(logs).toEqual([]);
2804+
},
2805+
);
2806+
// @gate enableFragmentRefs
2807+
it(
2808+
'removes a listener registered with passive:false when removed with passive:true',
2809+
async()=>{
2810+
constfragmentRef=React.createRef(null);
2811+
functionTest(){
2812+
return(
2813+
<>
2814+
<divid="child-x"/>
2815+
</>
2816+
);
2817+
}
2818+
constroot=ReactDOMClient.createRoot(container);
2819+
awaitact(()=>{
2820+
root.render(
2821+
<Fragmentref={fragmentRef}>
2822+
<Test/>
2823+
</Fragment>,
2824+
);
2825+
});
2826+
constlogs=[];
2827+
functionhandler(){
2828+
logs.push('fired');
2829+
}
2830+
// Register with passive: false
2831+
fragmentRef.current.addEventListener('click',handler,{
2832+
passive: false,
2833+
});
2834+
document.querySelector('#child-x').click();
2835+
expect(logs).toEqual(['fired']);
2836+
logs.length=0;
2837+
// Remove with passive: true - per DOM spec, passive is NOT part of identity
2838+
// so this MUST remove the listener regardless of passive mismatch.
2839+
fragmentRef.current.removeEventListener('click',handler,{
2840+
passive: true,
2841+
});
2842+
document.querySelector('#child-x').click();
2843+
// Listener removed - no more invocations
2844+
expect(logs).toEqual([]);
2845+
},
2846+
);
26832847
});
26842848
});

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Fix FragmentInstance listener leak: normalize boolean vs object captu… · react/react@142cfde · GitHub
Skip to content

Commit 142cfde

Browse files
authored
Fix FragmentInstance listener leak: normalize boolean vs object capture options per DOM spec (#36047)
## Summary `FragmentInstance.addEventListener` and `removeEventListener` fail to cross-match listeners when the `capture` option is passed as a **boolean** in one call and an **options object** in the other. This violates the [DOM Living Standard](https://dom.spec.whatwg.org/#dom-eventtarget-removeeventlistener), which states that `addEventListener(type, fn, true)` and `addEventListener(type, fn, {capture: true})` are identical. ### Root Cause In `ReactFiberConfigDOM.js`, the `normalizeListenerOptions` function generates a listener key string for deduplication. The boolean branch generates a **different format** than the object branch: ```js // Boolean branch (old) — produces "c=1" return `c=${opts ? '1' : '0'}`; // Object branch — produces "c=1&o=0&p=0" return `c=${opts.capture ? '1' : '0'}&o=${opts.once ? '1' : '0'}&p=${opts.passive ? '1' : '0'}`; ``` Because the keys differ, `indexOfEventListener` cannot match them — so `removeEventListener('click', fn, {capture: true})` silently fails to remove a listener registered with `addEventListener('click', fn, true)`, and vice versa. This causes a **memory leak and event listener accumulation** on all Fragment child DOM nodes. ### Fix Normalize the boolean branch to produce the same full key format: ```js // Boolean branch (fixed) — now produces "c=1&o=0&p=0" (matches object branch) return `c=${opts ? '1' : '0'}&o=0&p=0`; ``` This makes both forms produce an identical key, matching the DOM spec behavior. ### When Was This Introduced This bug has been present since `FragmentInstance` event listener tracking was first added. It became reachable in production as of [#36026](#36026) which enabled `enableFragmentRefs` + `enableFragmentRefsInstanceHandles` across all builds (merged 3 days ago). ### Tests Added two new regression tests to `ReactDOMFragmentRefs-test.js`: 1. `removes a capture listener registered with boolean when removed with options object` 2. `removes a capture listener registered with options object when removed with boolean` Both tests were failing before this fix and pass after. ## How did you test this change? Added two new automated tests covering both cross-form removal directions. Existing tests continue to pass. ## Changelog ### React DOM - **Fixed** `FragmentInstance.removeEventListener()` not removing capture-phase listeners when the `capture` option form (boolean vs options object) differs between `add` and `remove` calls.
1 parent 94643c3 commit 142cfde

2 files changed

Lines changed: 165 additions & 1 deletion

File tree

‎packages/react-dom-bindings/src/client/ReactFiberConfigDOM.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3093,7 +3093,7 @@ function normalizeListenerOptions(
30933093
return`c=${opts ? '1' : '0'}`;
30943094
}
30953095

3096-
return`c=${opts.capture ? '1' : '0'}&o=${opts.once ? '1' : '0'}&p=${opts.passive ? '1' : '0'}`;
3096+
return`c=${opts.capture ? '1' : '0'}`;
30973097
}
30983098
functionindexOfEventListener(
30993099
eventListeners: Array<StoredEventListener>,

‎packages/react-dom/src/__tests__/ReactDOMFragmentRefs-test.js‎

Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -814,6 +814,86 @@ describe('FragmentRefs', () => {
814814
expect(logs).toEqual([]);
815815
});
816816

817+
// @gate enableFragmentRefs
818+
it(
819+
'removes a capture listener registered with boolean when removed with options object',
820+
async()=>{
821+
constfragmentRef=React.createRef(null);
822+
functionTest(){
823+
return(
824+
<Fragmentref={fragmentRef}>
825+
<divid="child-a"/>
826+
</Fragment>
827+
);
828+
}
829+
constroot=ReactDOMClient.createRoot(container);
830+
awaitact(()=>{
831+
root.render(<Test/>);
832+
});
833+
834+
constlogs=[];
835+
functionlogCapture(){
836+
logs.push('capture');
837+
}
838+
839+
// Register with boolean `true` (capture phase)
840+
fragmentRef.current.addEventListener('click',logCapture,true);
841+
document.querySelector('#child-a').click();
842+
expect(logs).toEqual(['capture']);
843+
844+
logs.length=0;
845+
846+
// Remove with equivalent options object {capture: true}
847+
// Per DOM spec, these are identical - the listener MUST be removed
848+
fragmentRef.current.removeEventListener('click',logCapture,{
849+
capture: true,
850+
});
851+
document.querySelector('#child-a').click();
852+
// Listener should have been removed - logs must remain empty
853+
expect(logs).toEqual([]);
854+
},
855+
);
856+
857+
// @gate enableFragmentRefs
858+
it(
859+
'removes a capture listener registered with options object when removed with boolean',
860+
async()=>{
861+
constfragmentRef=React.createRef(null);
862+
functionTest(){
863+
return(
864+
<Fragmentref={fragmentRef}>
865+
<divid="child-b"/>
866+
</Fragment>
867+
);
868+
}
869+
constroot=ReactDOMClient.createRoot(container);
870+
awaitact(()=>{
871+
root.render(<Test/>);
872+
});
873+
874+
constlogs=[];
875+
functionlogCapture(){
876+
logs.push('capture');
877+
}
878+
879+
// Register with options object {capture: true}
880+
fragmentRef.current.addEventListener('click',logCapture,{
881+
capture: true,
882+
});
883+
document.querySelector('#child-b').click();
884+
expect(logs).toEqual(['capture']);
885+
886+
logs.length=0;
887+
888+
// Remove with boolean `true`
889+
// Per DOM spec, these are identical - the listener MUST be removed
890+
fragmentRef.current.removeEventListener('click',logCapture,true);
891+
document.querySelector('#child-b').click();
892+
// Listener should have been removed - logs must remain empty
893+
expect(logs).toEqual([]);
894+
},
895+
);
896+
817897
// @gate enableFragmentRefs
818898
it('applies event listeners to portaled children',async()=>{
819899
constfragmentRef=React.createRef();
@@ -2680,5 +2760,89 @@ describe('FragmentRefs', () => {
26802760
window.scrollTo=originalScrollTo;
26812761
restoreRange();
26822762
});
2763+
2764+
// @gate enableFragmentRefs
2765+
it(
2766+
'treats passive:true and passive:false as same listener per DOM spec',
2767+
async()=>{
2768+
constfragmentRef=React.createRef();
2769+
constroot=ReactDOMClient.createRoot(container);
2770+
2771+
awaitact(()=>{
2772+
root.render(
2773+
<Fragmentref={fragmentRef}>
2774+
<divid="child"/>
2775+
</Fragment>,
2776+
);
2777+
});
2778+
2779+
constlogs=[];
2780+
consthandler=()=>logs.push('fired');
2781+
2782+
constchild=document.querySelector('#child');
2783+
constspy=jest.spyOn(child,'addEventListener');
2784+
// Per DOM spec, listener identity is (type, callback, capture).
2785+
// passive is NOT part of the key, so these are the SAME listener.
2786+
fragmentRef.current.addEventListener('click',handler,{passive: false});
2787+
// Second add is a no-op: same (type, callback, capture) identity.
2788+
fragmentRef.current.addEventListener('click',handler,{passive: true});
2789+
expect(spy).toHaveBeenCalledTimes(1);
2790+
expect(spy).toHaveBeenCalledWith('click',handler,{passive: false});
2791+
2792+
document.querySelector('#child').click();
2793+
// First handler fires once (second add was a no-op).
2794+
expect(logs).toEqual(['fired']);
2795+
2796+
// removeEventListener also ignores passive when matching
2797+
fragmentRef.current.removeEventListener('click',handler,{
2798+
passive: true,
2799+
});
2800+
2801+
logs.length=0;
2802+
document.querySelector('#child').click();
2803+
expect(logs).toEqual([]);
2804+
},
2805+
);
2806+
// @gate enableFragmentRefs
2807+
it(
2808+
'removes a listener registered with passive:false when removed with passive:true',
2809+
async()=>{
2810+
constfragmentRef=React.createRef(null);
2811+
functionTest(){
2812+
return(
2813+
<>
2814+
<divid="child-x"/>
2815+
</>
2816+
);
2817+
}
2818+
constroot=ReactDOMClient.createRoot(container);
2819+
awaitact(()=>{
2820+
root.render(
2821+
<Fragmentref={fragmentRef}>
2822+
<Test/>
2823+
</Fragment>,
2824+
);
2825+
});
2826+
constlogs=[];
2827+
functionhandler(){
2828+
logs.push('fired');
2829+
}
2830+
// Register with passive: false
2831+
fragmentRef.current.addEventListener('click',handler,{
2832+
passive: false,
2833+
});
2834+
document.querySelector('#child-x').click();
2835+
expect(logs).toEqual(['fired']);
2836+
logs.length=0;
2837+
// Remove with passive: true - per DOM spec, passive is NOT part of identity
2838+
// so this MUST remove the listener regardless of passive mismatch.
2839+
fragmentRef.current.removeEventListener('click',handler,{
2840+
passive: true,
2841+
});
2842+
document.querySelector('#child-x').click();
2843+
// Listener removed - no more invocations
2844+
expect(logs).toEqual([]);
2845+
},
2846+
);
26832847
});
26842848
});

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' Fix FragmentInstance listener leak: normalize boolean vs object captu… · react/react@142cfde · GitHub
Skip to content

Commit 142cfde

Browse files
authored
Fix FragmentInstance listener leak: normalize boolean vs object capture options per DOM spec (#36047)
## Summary `FragmentInstance.addEventListener` and `removeEventListener` fail to cross-match listeners when the `capture` option is passed as a **boolean** in one call and an **options object** in the other. This violates the [DOM Living Standard](https://dom.spec.whatwg.org/#dom-eventtarget-removeeventlistener), which states that `addEventListener(type, fn, true)` and `addEventListener(type, fn, {capture: true})` are identical. ### Root Cause In `ReactFiberConfigDOM.js`, the `normalizeListenerOptions` function generates a listener key string for deduplication. The boolean branch generates a **different format** than the object branch: ```js // Boolean branch (old) — produces "c=1" return `c=${opts ? '1' : '0'}`; // Object branch — produces "c=1&o=0&p=0" return `c=${opts.capture ? '1' : '0'}&o=${opts.once ? '1' : '0'}&p=${opts.passive ? '1' : '0'}`; ``` Because the keys differ, `indexOfEventListener` cannot match them — so `removeEventListener('click', fn, {capture: true})` silently fails to remove a listener registered with `addEventListener('click', fn, true)`, and vice versa. This causes a **memory leak and event listener accumulation** on all Fragment child DOM nodes. ### Fix Normalize the boolean branch to produce the same full key format: ```js // Boolean branch (fixed) — now produces "c=1&o=0&p=0" (matches object branch) return `c=${opts ? '1' : '0'}&o=0&p=0`; ``` This makes both forms produce an identical key, matching the DOM spec behavior. ### When Was This Introduced This bug has been present since `FragmentInstance` event listener tracking was first added. It became reachable in production as of [#36026](#36026) which enabled `enableFragmentRefs` + `enableFragmentRefsInstanceHandles` across all builds (merged 3 days ago). ### Tests Added two new regression tests to `ReactDOMFragmentRefs-test.js`: 1. `removes a capture listener registered with boolean when removed with options object` 2. `removes a capture listener registered with options object when removed with boolean` Both tests were failing before this fix and pass after. ## How did you test this change? Added two new automated tests covering both cross-form removal directions. Existing tests continue to pass. ## Changelog ### React DOM - **Fixed** `FragmentInstance.removeEventListener()` not removing capture-phase listeners when the `capture` option form (boolean vs options object) differs between `add` and `remove` calls.
1 parent 94643c3 commit 142cfde

2 files changed

Lines changed: 165 additions & 1 deletion

File tree

‎packages/react-dom-bindings/src/client/ReactFiberConfigDOM.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3093,7 +3093,7 @@ function normalizeListenerOptions(
30933093
return`c=${opts ? '1' : '0'}`;
30943094
}
30953095

3096-
return`c=${opts.capture ? '1' : '0'}&o=${opts.once ? '1' : '0'}&p=${opts.passive ? '1' : '0'}`;
3096+
return`c=${opts.capture ? '1' : '0'}`;
30973097
}
30983098
functionindexOfEventListener(
30993099
eventListeners: Array<StoredEventListener>,

‎packages/react-dom/src/__tests__/ReactDOMFragmentRefs-test.js‎

Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -814,6 +814,86 @@ describe('FragmentRefs', () => {
814814
expect(logs).toEqual([]);
815815
});
816816

817+
// @gate enableFragmentRefs
818+
it(
819+
'removes a capture listener registered with boolean when removed with options object',
820+
async()=>{
821+
constfragmentRef=React.createRef(null);
822+
functionTest(){
823+
return(
824+
<Fragmentref={fragmentRef}>
825+
<divid="child-a"/>
826+
</Fragment>
827+
);
828+
}
829+
constroot=ReactDOMClient.createRoot(container);
830+
awaitact(()=>{
831+
root.render(<Test/>);
832+
});
833+
834+
constlogs=[];
835+
functionlogCapture(){
836+
logs.push('capture');
837+
}
838+
839+
// Register with boolean `true` (capture phase)
840+
fragmentRef.current.addEventListener('click',logCapture,true);
841+
document.querySelector('#child-a').click();
842+
expect(logs).toEqual(['capture']);
843+
844+
logs.length=0;
845+
846+
// Remove with equivalent options object {capture: true}
847+
// Per DOM spec, these are identical - the listener MUST be removed
848+
fragmentRef.current.removeEventListener('click',logCapture,{
849+
capture: true,
850+
});
851+
document.querySelector('#child-a').click();
852+
// Listener should have been removed - logs must remain empty
853+
expect(logs).toEqual([]);
854+
},
855+
);
856+
857+
// @gate enableFragmentRefs
858+
it(
859+
'removes a capture listener registered with options object when removed with boolean',
860+
async()=>{
861+
constfragmentRef=React.createRef(null);
862+
functionTest(){
863+
return(
864+
<Fragmentref={fragmentRef}>
865+
<divid="child-b"/>
866+
</Fragment>
867+
);
868+
}
869+
constroot=ReactDOMClient.createRoot(container);
870+
awaitact(()=>{
871+
root.render(<Test/>);
872+
});
873+
874+
constlogs=[];
875+
functionlogCapture(){
876+
logs.push('capture');
877+
}
878+
879+
// Register with options object {capture: true}
880+
fragmentRef.current.addEventListener('click',logCapture,{
881+
capture: true,
882+
});
883+
document.querySelector('#child-b').click();
884+
expect(logs).toEqual(['capture']);
885+
886+
logs.length=0;
887+
888+
// Remove with boolean `true`
889+
// Per DOM spec, these are identical - the listener MUST be removed
890+
fragmentRef.current.removeEventListener('click',logCapture,true);
891+
document.querySelector('#child-b').click();
892+
// Listener should have been removed - logs must remain empty
893+
expect(logs).toEqual([]);
894+
},
895+
);
896+
817897
// @gate enableFragmentRefs
818898
it('applies event listeners to portaled children',async()=>{
819899
constfragmentRef=React.createRef();
@@ -2680,5 +2760,89 @@ describe('FragmentRefs', () => {
26802760
window.scrollTo=originalScrollTo;
26812761
restoreRange();
26822762
});
2763+
2764+
// @gate enableFragmentRefs
2765+
it(
2766+
'treats passive:true and passive:false as same listener per DOM spec',
2767+
async()=>{
2768+
constfragmentRef=React.createRef();
2769+
constroot=ReactDOMClient.createRoot(container);
2770+
2771+
awaitact(()=>{
2772+
root.render(
2773+
<Fragmentref={fragmentRef}>
2774+
<divid="child"/>
2775+
</Fragment>,
2776+
);
2777+
});
2778+
2779+
constlogs=[];
2780+
consthandler=()=>logs.push('fired');
2781+
2782+
constchild=document.querySelector('#child');
2783+
constspy=jest.spyOn(child,'addEventListener');
2784+
// Per DOM spec, listener identity is (type, callback, capture).
2785+
// passive is NOT part of the key, so these are the SAME listener.
2786+
fragmentRef.current.addEventListener('click',handler,{passive: false});
2787+
// Second add is a no-op: same (type, callback, capture) identity.
2788+
fragmentRef.current.addEventListener('click',handler,{passive: true});
2789+
expect(spy).toHaveBeenCalledTimes(1);
2790+
expect(spy).toHaveBeenCalledWith('click',handler,{passive: false});
2791+
2792+
document.querySelector('#child').click();
2793+
// First handler fires once (second add was a no-op).
2794+
expect(logs).toEqual(['fired']);
2795+
2796+
// removeEventListener also ignores passive when matching
2797+
fragmentRef.current.removeEventListener('click',handler,{
2798+
passive: true,
2799+
});
2800+
2801+
logs.length=0;
2802+
document.querySelector('#child').click();
2803+
expect(logs).toEqual([]);
2804+
},
2805+
);
2806+
// @gate enableFragmentRefs
2807+
it(
2808+
'removes a listener registered with passive:false when removed with passive:true',
2809+
async()=>{
2810+
constfragmentRef=React.createRef(null);
2811+
functionTest(){
2812+
return(
2813+
<>
2814+
<divid="child-x"/>
2815+
</>
2816+
);
2817+
}
2818+
constroot=ReactDOMClient.createRoot(container);
2819+
awaitact(()=>{
2820+
root.render(
2821+
<Fragmentref={fragmentRef}>
2822+
<Test/>
2823+
</Fragment>,
2824+
);
2825+
});
2826+
constlogs=[];
2827+
functionhandler(){
2828+
logs.push('fired');
2829+
}
2830+
// Register with passive: false
2831+
fragmentRef.current.addEventListener('click',handler,{
2832+
passive: false,
2833+
});
2834+
document.querySelector('#child-x').click();
2835+
expect(logs).toEqual(['fired']);
2836+
logs.length=0;
2837+
// Remove with passive: true - per DOM spec, passive is NOT part of identity
2838+
// so this MUST remove the listener regardless of passive mismatch.
2839+
fragmentRef.current.removeEventListener('click',handler,{
2840+
passive: true,
2841+
});
2842+
document.querySelector('#child-x').click();
2843+
// Listener removed - no more invocations
2844+
expect(logs).toEqual([]);
2845+
},
2846+
);
26832847
});
26842848
});

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Fix FragmentInstance listener leak: normalize boolean vs object captu… · react/react@142cfde · GitHub
Skip to content

Commit 142cfde

Browse files
authored
Fix FragmentInstance listener leak: normalize boolean vs object capture options per DOM spec (#36047)
## Summary `FragmentInstance.addEventListener` and `removeEventListener` fail to cross-match listeners when the `capture` option is passed as a **boolean** in one call and an **options object** in the other. This violates the [DOM Living Standard](https://dom.spec.whatwg.org/#dom-eventtarget-removeeventlistener), which states that `addEventListener(type, fn, true)` and `addEventListener(type, fn, {capture: true})` are identical. ### Root Cause In `ReactFiberConfigDOM.js`, the `normalizeListenerOptions` function generates a listener key string for deduplication. The boolean branch generates a **different format** than the object branch: ```js // Boolean branch (old) — produces "c=1" return `c=${opts ? '1' : '0'}`; // Object branch — produces "c=1&o=0&p=0" return `c=${opts.capture ? '1' : '0'}&o=${opts.once ? '1' : '0'}&p=${opts.passive ? '1' : '0'}`; ``` Because the keys differ, `indexOfEventListener` cannot match them — so `removeEventListener('click', fn, {capture: true})` silently fails to remove a listener registered with `addEventListener('click', fn, true)`, and vice versa. This causes a **memory leak and event listener accumulation** on all Fragment child DOM nodes. ### Fix Normalize the boolean branch to produce the same full key format: ```js // Boolean branch (fixed) — now produces "c=1&o=0&p=0" (matches object branch) return `c=${opts ? '1' : '0'}&o=0&p=0`; ``` This makes both forms produce an identical key, matching the DOM spec behavior. ### When Was This Introduced This bug has been present since `FragmentInstance` event listener tracking was first added. It became reachable in production as of [#36026](#36026) which enabled `enableFragmentRefs` + `enableFragmentRefsInstanceHandles` across all builds (merged 3 days ago). ### Tests Added two new regression tests to `ReactDOMFragmentRefs-test.js`: 1. `removes a capture listener registered with boolean when removed with options object` 2. `removes a capture listener registered with options object when removed with boolean` Both tests were failing before this fix and pass after. ## How did you test this change? Added two new automated tests covering both cross-form removal directions. Existing tests continue to pass. ## Changelog ### React DOM - **Fixed** `FragmentInstance.removeEventListener()` not removing capture-phase listeners when the `capture` option form (boolean vs options object) differs between `add` and `remove` calls.
1 parent 94643c3 commit 142cfde

2 files changed

Lines changed: 165 additions & 1 deletion

File tree

‎packages/react-dom-bindings/src/client/ReactFiberConfigDOM.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3093,7 +3093,7 @@ function normalizeListenerOptions(
30933093
return`c=${opts ? '1' : '0'}`;
30943094
}
30953095

3096-
return`c=${opts.capture ? '1' : '0'}&o=${opts.once ? '1' : '0'}&p=${opts.passive ? '1' : '0'}`;
3096+
return`c=${opts.capture ? '1' : '0'}`;
30973097
}
30983098
functionindexOfEventListener(
30993099
eventListeners: Array<StoredEventListener>,

‎packages/react-dom/src/__tests__/ReactDOMFragmentRefs-test.js‎

Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -814,6 +814,86 @@ describe('FragmentRefs', () => {
814814
expect(logs).toEqual([]);
815815
});
816816

817+
// @gate enableFragmentRefs
818+
it(
819+
'removes a capture listener registered with boolean when removed with options object',
820+
async()=>{
821+
constfragmentRef=React.createRef(null);
822+
functionTest(){
823+
return(
824+
<Fragmentref={fragmentRef}>
825+
<divid="child-a"/>
826+
</Fragment>
827+
);
828+
}
829+
constroot=ReactDOMClient.createRoot(container);
830+
awaitact(()=>{
831+
root.render(<Test/>);
832+
});
833+
834+
constlogs=[];
835+
functionlogCapture(){
836+
logs.push('capture');
837+
}
838+
839+
// Register with boolean `true` (capture phase)
840+
fragmentRef.current.addEventListener('click',logCapture,true);
841+
document.querySelector('#child-a').click();
842+
expect(logs).toEqual(['capture']);
843+
844+
logs.length=0;
845+
846+
// Remove with equivalent options object {capture: true}
847+
// Per DOM spec, these are identical - the listener MUST be removed
848+
fragmentRef.current.removeEventListener('click',logCapture,{
849+
capture: true,
850+
});
851+
document.querySelector('#child-a').click();
852+
// Listener should have been removed - logs must remain empty
853+
expect(logs).toEqual([]);
854+
},
855+
);
856+
857+
// @gate enableFragmentRefs
858+
it(
859+
'removes a capture listener registered with options object when removed with boolean',
860+
async()=>{
861+
constfragmentRef=React.createRef(null);
862+
functionTest(){
863+
return(
864+
<Fragmentref={fragmentRef}>
865+
<divid="child-b"/>
866+
</Fragment>
867+
);
868+
}
869+
constroot=ReactDOMClient.createRoot(container);
870+
awaitact(()=>{
871+
root.render(<Test/>);
872+
});
873+
874+
constlogs=[];
875+
functionlogCapture(){
876+
logs.push('capture');
877+
}
878+
879+
// Register with options object {capture: true}
880+
fragmentRef.current.addEventListener('click',logCapture,{
881+
capture: true,
882+
});
883+
document.querySelector('#child-b').click();
884+
expect(logs).toEqual(['capture']);
885+
886+
logs.length=0;
887+
888+
// Remove with boolean `true`
889+
// Per DOM spec, these are identical - the listener MUST be removed
890+
fragmentRef.current.removeEventListener('click',logCapture,true);
891+
document.querySelector('#child-b').click();
892+
// Listener should have been removed - logs must remain empty
893+
expect(logs).toEqual([]);
894+
},
895+
);
896+
817897
// @gate enableFragmentRefs
818898
it('applies event listeners to portaled children',async()=>{
819899
constfragmentRef=React.createRef();
@@ -2680,5 +2760,89 @@ describe('FragmentRefs', () => {
26802760
window.scrollTo=originalScrollTo;
26812761
restoreRange();
26822762
});
2763+
2764+
// @gate enableFragmentRefs
2765+
it(
2766+
'treats passive:true and passive:false as same listener per DOM spec',
2767+
async()=>{
2768+
constfragmentRef=React.createRef();
2769+
constroot=ReactDOMClient.createRoot(container);
2770+
2771+
awaitact(()=>{
2772+
root.render(
2773+
<Fragmentref={fragmentRef}>
2774+
<divid="child"/>
2775+
</Fragment>,
2776+
);
2777+
});
2778+
2779+
constlogs=[];
2780+
consthandler=()=>logs.push('fired');
2781+
2782+
constchild=document.querySelector('#child');
2783+
constspy=jest.spyOn(child,'addEventListener');
2784+
// Per DOM spec, listener identity is (type, callback, capture).
2785+
// passive is NOT part of the key, so these are the SAME listener.
2786+
fragmentRef.current.addEventListener('click',handler,{passive: false});
2787+
// Second add is a no-op: same (type, callback, capture) identity.
2788+
fragmentRef.current.addEventListener('click',handler,{passive: true});
2789+
expect(spy).toHaveBeenCalledTimes(1);
2790+
expect(spy).toHaveBeenCalledWith('click',handler,{passive: false});
2791+
2792+
document.querySelector('#child').click();
2793+
// First handler fires once (second add was a no-op).
2794+
expect(logs).toEqual(['fired']);
2795+
2796+
// removeEventListener also ignores passive when matching
2797+
fragmentRef.current.removeEventListener('click',handler,{
2798+
passive: true,
2799+
});
2800+
2801+
logs.length=0;
2802+
document.querySelector('#child').click();
2803+
expect(logs).toEqual([]);
2804+
},
2805+
);
2806+
// @gate enableFragmentRefs
2807+
it(
2808+
'removes a listener registered with passive:false when removed with passive:true',
2809+
async()=>{
2810+
constfragmentRef=React.createRef(null);
2811+
functionTest(){
2812+
return(
2813+
<>
2814+
<divid="child-x"/>
2815+
</>
2816+
);
2817+
}
2818+
constroot=ReactDOMClient.createRoot(container);
2819+
awaitact(()=>{
2820+
root.render(
2821+
<Fragmentref={fragmentRef}>
2822+
<Test/>
2823+
</Fragment>,
2824+
);
2825+
});
2826+
constlogs=[];
2827+
functionhandler(){
2828+
logs.push('fired');
2829+
}
2830+
// Register with passive: false
2831+
fragmentRef.current.addEventListener('click',handler,{
2832+
passive: false,
2833+
});
2834+
document.querySelector('#child-x').click();
2835+
expect(logs).toEqual(['fired']);
2836+
logs.length=0;
2837+
// Remove with passive: true - per DOM spec, passive is NOT part of identity
2838+
// so this MUST remove the listener regardless of passive mismatch.
2839+
fragmentRef.current.removeEventListener('click',handler,{
2840+
passive: true,
2841+
});
2842+
document.querySelector('#child-x').click();
2843+
// Listener removed - no more invocations
2844+
expect(logs).toEqual([]);
2845+
},
2846+
);
26832847
});
26842848
});

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Fix FragmentInstance listener leak: normalize boolean vs object captu… · react/react@142cfde · GitHub
Skip to content

Commit 142cfde

Browse files
authored
Fix FragmentInstance listener leak: normalize boolean vs object capture options per DOM spec (#36047)
## Summary `FragmentInstance.addEventListener` and `removeEventListener` fail to cross-match listeners when the `capture` option is passed as a **boolean** in one call and an **options object** in the other. This violates the [DOM Living Standard](https://dom.spec.whatwg.org/#dom-eventtarget-removeeventlistener), which states that `addEventListener(type, fn, true)` and `addEventListener(type, fn, {capture: true})` are identical. ### Root Cause In `ReactFiberConfigDOM.js`, the `normalizeListenerOptions` function generates a listener key string for deduplication. The boolean branch generates a **different format** than the object branch: ```js // Boolean branch (old) — produces "c=1" return `c=${opts ? '1' : '0'}`; // Object branch — produces "c=1&o=0&p=0" return `c=${opts.capture ? '1' : '0'}&o=${opts.once ? '1' : '0'}&p=${opts.passive ? '1' : '0'}`; ``` Because the keys differ, `indexOfEventListener` cannot match them — so `removeEventListener('click', fn, {capture: true})` silently fails to remove a listener registered with `addEventListener('click', fn, true)`, and vice versa. This causes a **memory leak and event listener accumulation** on all Fragment child DOM nodes. ### Fix Normalize the boolean branch to produce the same full key format: ```js // Boolean branch (fixed) — now produces "c=1&o=0&p=0" (matches object branch) return `c=${opts ? '1' : '0'}&o=0&p=0`; ``` This makes both forms produce an identical key, matching the DOM spec behavior. ### When Was This Introduced This bug has been present since `FragmentInstance` event listener tracking was first added. It became reachable in production as of [#36026](#36026) which enabled `enableFragmentRefs` + `enableFragmentRefsInstanceHandles` across all builds (merged 3 days ago). ### Tests Added two new regression tests to `ReactDOMFragmentRefs-test.js`: 1. `removes a capture listener registered with boolean when removed with options object` 2. `removes a capture listener registered with options object when removed with boolean` Both tests were failing before this fix and pass after. ## How did you test this change? Added two new automated tests covering both cross-form removal directions. Existing tests continue to pass. ## Changelog ### React DOM - **Fixed** `FragmentInstance.removeEventListener()` not removing capture-phase listeners when the `capture` option form (boolean vs options object) differs between `add` and `remove` calls.
1 parent 94643c3 commit 142cfde

2 files changed

Lines changed: 165 additions & 1 deletion

File tree

‎packages/react-dom-bindings/src/client/ReactFiberConfigDOM.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3093,7 +3093,7 @@ function normalizeListenerOptions(
30933093
return`c=${opts ? '1' : '0'}`;
30943094
}
30953095

3096-
return`c=${opts.capture ? '1' : '0'}&o=${opts.once ? '1' : '0'}&p=${opts.passive ? '1' : '0'}`;
3096+
return`c=${opts.capture ? '1' : '0'}`;
30973097
}
30983098
functionindexOfEventListener(
30993099
eventListeners: Array<StoredEventListener>,

‎packages/react-dom/src/__tests__/ReactDOMFragmentRefs-test.js‎

Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -814,6 +814,86 @@ describe('FragmentRefs', () => {
814814
expect(logs).toEqual([]);
815815
});
816816

817+
// @gate enableFragmentRefs
818+
it(
819+
'removes a capture listener registered with boolean when removed with options object',
820+
async()=>{
821+
constfragmentRef=React.createRef(null);
822+
functionTest(){
823+
return(
824+
<Fragmentref={fragmentRef}>
825+
<divid="child-a"/>
826+
</Fragment>
827+
);
828+
}
829+
constroot=ReactDOMClient.createRoot(container);
830+
awaitact(()=>{
831+
root.render(<Test/>);
832+
});
833+
834+
constlogs=[];
835+
functionlogCapture(){
836+
logs.push('capture');
837+
}
838+
839+
// Register with boolean `true` (capture phase)
840+
fragmentRef.current.addEventListener('click',logCapture,true);
841+
document.querySelector('#child-a').click();
842+
expect(logs).toEqual(['capture']);
843+
844+
logs.length=0;
845+
846+
// Remove with equivalent options object {capture: true}
847+
// Per DOM spec, these are identical - the listener MUST be removed
848+
fragmentRef.current.removeEventListener('click',logCapture,{
849+
capture: true,
850+
});
851+
document.querySelector('#child-a').click();
852+
// Listener should have been removed - logs must remain empty
853+
expect(logs).toEqual([]);
854+
},
855+
);
856+
857+
// @gate enableFragmentRefs
858+
it(
859+
'removes a capture listener registered with options object when removed with boolean',
860+
async()=>{
861+
constfragmentRef=React.createRef(null);
862+
functionTest(){
863+
return(
864+
<Fragmentref={fragmentRef}>
865+
<divid="child-b"/>
866+
</Fragment>
867+
);
868+
}
869+
constroot=ReactDOMClient.createRoot(container);
870+
awaitact(()=>{
871+
root.render(<Test/>);
872+
});
873+
874+
constlogs=[];
875+
functionlogCapture(){
876+
logs.push('capture');
877+
}
878+
879+
// Register with options object {capture: true}
880+
fragmentRef.current.addEventListener('click',logCapture,{
881+
capture: true,
882+
});
883+
document.querySelector('#child-b').click();
884+
expect(logs).toEqual(['capture']);
885+
886+
logs.length=0;
887+
888+
// Remove with boolean `true`
889+
// Per DOM spec, these are identical - the listener MUST be removed
890+
fragmentRef.current.removeEventListener('click',logCapture,true);
891+
document.querySelector('#child-b').click();
892+
// Listener should have been removed - logs must remain empty
893+
expect(logs).toEqual([]);
894+
},
895+
);
896+
817897
// @gate enableFragmentRefs
818898
it('applies event listeners to portaled children',async()=>{
819899
constfragmentRef=React.createRef();
@@ -2680,5 +2760,89 @@ describe('FragmentRefs', () => {
26802760
window.scrollTo=originalScrollTo;
26812761
restoreRange();
26822762
});
2763+
2764+
// @gate enableFragmentRefs
2765+
it(
2766+
'treats passive:true and passive:false as same listener per DOM spec',
2767+
async()=>{
2768+
constfragmentRef=React.createRef();
2769+
constroot=ReactDOMClient.createRoot(container);
2770+
2771+
awaitact(()=>{
2772+
root.render(
2773+
<Fragmentref={fragmentRef}>
2774+
<divid="child"/>
2775+
</Fragment>,
2776+
);
2777+
});
2778+
2779+
constlogs=[];
2780+
consthandler=()=>logs.push('fired');
2781+
2782+
constchild=document.querySelector('#child');
2783+
constspy=jest.spyOn(child,'addEventListener');
2784+
// Per DOM spec, listener identity is (type, callback, capture).
2785+
// passive is NOT part of the key, so these are the SAME listener.
2786+
fragmentRef.current.addEventListener('click',handler,{passive: false});
2787+
// Second add is a no-op: same (type, callback, capture) identity.
2788+
fragmentRef.current.addEventListener('click',handler,{passive: true});
2789+
expect(spy).toHaveBeenCalledTimes(1);
2790+
expect(spy).toHaveBeenCalledWith('click',handler,{passive: false});
2791+
2792+
document.querySelector('#child').click();
2793+
// First handler fires once (second add was a no-op).
2794+
expect(logs).toEqual(['fired']);
2795+
2796+
// removeEventListener also ignores passive when matching
2797+
fragmentRef.current.removeEventListener('click',handler,{
2798+
passive: true,
2799+
});
2800+
2801+
logs.length=0;
2802+
document.querySelector('#child').click();
2803+
expect(logs).toEqual([]);
2804+
},
2805+
);
2806+
// @gate enableFragmentRefs
2807+
it(
2808+
'removes a listener registered with passive:false when removed with passive:true',
2809+
async()=>{
2810+
constfragmentRef=React.createRef(null);
2811+
functionTest(){
2812+
return(
2813+
<>
2814+
<divid="child-x"/>
2815+
</>
2816+
);
2817+
}
2818+
constroot=ReactDOMClient.createRoot(container);
2819+
awaitact(()=>{
2820+
root.render(
2821+
<Fragmentref={fragmentRef}>
2822+
<Test/>
2823+
</Fragment>,
2824+
);
2825+
});
2826+
constlogs=[];
2827+
functionhandler(){
2828+
logs.push('fired');
2829+
}
2830+
// Register with passive: false
2831+
fragmentRef.current.addEventListener('click',handler,{
2832+
passive: false,
2833+
});
2834+
document.querySelector('#child-x').click();
2835+
expect(logs).toEqual(['fired']);
2836+
logs.length=0;
2837+
// Remove with passive: true - per DOM spec, passive is NOT part of identity
2838+
// so this MUST remove the listener regardless of passive mismatch.
2839+
fragmentRef.current.removeEventListener('click',handler,{
2840+
passive: true,
2841+
});
2842+
document.querySelector('#child-x').click();
2843+
// Listener removed - no more invocations
2844+
expect(logs).toEqual([]);
2845+
},
2846+
);
26832847
});
26842848
});

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); Fix FragmentInstance listener leak: normalize boolean vs object captu… · react/react@142cfde · GitHub
Skip to content

Commit 142cfde

Browse files
authored
Fix FragmentInstance listener leak: normalize boolean vs object capture options per DOM spec (#36047)
## Summary `FragmentInstance.addEventListener` and `removeEventListener` fail to cross-match listeners when the `capture` option is passed as a **boolean** in one call and an **options object** in the other. This violates the [DOM Living Standard](https://dom.spec.whatwg.org/#dom-eventtarget-removeeventlistener), which states that `addEventListener(type, fn, true)` and `addEventListener(type, fn, {capture: true})` are identical. ### Root Cause In `ReactFiberConfigDOM.js`, the `normalizeListenerOptions` function generates a listener key string for deduplication. The boolean branch generates a **different format** than the object branch: ```js // Boolean branch (old) — produces "c=1" return `c=${opts ? '1' : '0'}`; // Object branch — produces "c=1&o=0&p=0" return `c=${opts.capture ? '1' : '0'}&o=${opts.once ? '1' : '0'}&p=${opts.passive ? '1' : '0'}`; ``` Because the keys differ, `indexOfEventListener` cannot match them — so `removeEventListener('click', fn, {capture: true})` silently fails to remove a listener registered with `addEventListener('click', fn, true)`, and vice versa. This causes a **memory leak and event listener accumulation** on all Fragment child DOM nodes. ### Fix Normalize the boolean branch to produce the same full key format: ```js // Boolean branch (fixed) — now produces "c=1&o=0&p=0" (matches object branch) return `c=${opts ? '1' : '0'}&o=0&p=0`; ``` This makes both forms produce an identical key, matching the DOM spec behavior. ### When Was This Introduced This bug has been present since `FragmentInstance` event listener tracking was first added. It became reachable in production as of [#36026](#36026) which enabled `enableFragmentRefs` + `enableFragmentRefsInstanceHandles` across all builds (merged 3 days ago). ### Tests Added two new regression tests to `ReactDOMFragmentRefs-test.js`: 1. `removes a capture listener registered with boolean when removed with options object` 2. `removes a capture listener registered with options object when removed with boolean` Both tests were failing before this fix and pass after. ## How did you test this change? Added two new automated tests covering both cross-form removal directions. Existing tests continue to pass. ## Changelog ### React DOM - **Fixed** `FragmentInstance.removeEventListener()` not removing capture-phase listeners when the `capture` option form (boolean vs options object) differs between `add` and `remove` calls.
1 parent 94643c3 commit 142cfde

2 files changed

Lines changed: 165 additions & 1 deletion

File tree

‎packages/react-dom-bindings/src/client/ReactFiberConfigDOM.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3093,7 +3093,7 @@ function normalizeListenerOptions(
30933093
return`c=${opts ? '1' : '0'}`;
30943094
}
30953095

3096-
return`c=${opts.capture ? '1' : '0'}&o=${opts.once ? '1' : '0'}&p=${opts.passive ? '1' : '0'}`;
3096+
return`c=${opts.capture ? '1' : '0'}`;
30973097
}
30983098
functionindexOfEventListener(
30993099
eventListeners: Array<StoredEventListener>,

‎packages/react-dom/src/__tests__/ReactDOMFragmentRefs-test.js‎

Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -814,6 +814,86 @@ describe('FragmentRefs', () => {
814814
expect(logs).toEqual([]);
815815
});
816816

817+
// @gate enableFragmentRefs
818+
it(
819+
'removes a capture listener registered with boolean when removed with options object',
820+
async()=>{
821+
constfragmentRef=React.createRef(null);
822+
functionTest(){
823+
return(
824+
<Fragmentref={fragmentRef}>
825+
<divid="child-a"/>
826+
</Fragment>
827+
);
828+
}
829+
constroot=ReactDOMClient.createRoot(container);
830+
awaitact(()=>{
831+
root.render(<Test/>);
832+
});
833+
834+
constlogs=[];
835+
functionlogCapture(){
836+
logs.push('capture');
837+
}
838+
839+
// Register with boolean `true` (capture phase)
840+
fragmentRef.current.addEventListener('click',logCapture,true);
841+
document.querySelector('#child-a').click();
842+
expect(logs).toEqual(['capture']);
843+
844+
logs.length=0;
845+
846+
// Remove with equivalent options object {capture: true}
847+
// Per DOM spec, these are identical - the listener MUST be removed
848+
fragmentRef.current.removeEventListener('click',logCapture,{
849+
capture: true,
850+
});
851+
document.querySelector('#child-a').click();
852+
// Listener should have been removed - logs must remain empty
853+
expect(logs).toEqual([]);
854+
},
855+
);
856+
857+
// @gate enableFragmentRefs
858+
it(
859+
'removes a capture listener registered with options object when removed with boolean',
860+
async()=>{
861+
constfragmentRef=React.createRef(null);
862+
functionTest(){
863+
return(
864+
<Fragmentref={fragmentRef}>
865+
<divid="child-b"/>
866+
</Fragment>
867+
);
868+
}
869+
constroot=ReactDOMClient.createRoot(container);
870+
awaitact(()=>{
871+
root.render(<Test/>);
872+
});
873+
874+
constlogs=[];
875+
functionlogCapture(){
876+
logs.push('capture');
877+
}
878+
879+
// Register with options object {capture: true}
880+
fragmentRef.current.addEventListener('click',logCapture,{
881+
capture: true,
882+
});
883+
document.querySelector('#child-b').click();
884+
expect(logs).toEqual(['capture']);
885+
886+
logs.length=0;
887+
888+
// Remove with boolean `true`
889+
// Per DOM spec, these are identical - the listener MUST be removed
890+
fragmentRef.current.removeEventListener('click',logCapture,true);
891+
document.querySelector('#child-b').click();
892+
// Listener should have been removed - logs must remain empty
893+
expect(logs).toEqual([]);
894+
},
895+
);
896+
817897
// @gate enableFragmentRefs
818898
it('applies event listeners to portaled children',async()=>{
819899
constfragmentRef=React.createRef();
@@ -2680,5 +2760,89 @@ describe('FragmentRefs', () => {
26802760
window.scrollTo=originalScrollTo;
26812761
restoreRange();
26822762
});
2763+
2764+
// @gate enableFragmentRefs
2765+
it(
2766+
'treats passive:true and passive:false as same listener per DOM spec',
2767+
async()=>{
2768+
constfragmentRef=React.createRef();
2769+
constroot=ReactDOMClient.createRoot(container);
2770+
2771+
awaitact(()=>{
2772+
root.render(
2773+
<Fragmentref={fragmentRef}>
2774+
<divid="child"/>
2775+
</Fragment>,
2776+
);
2777+
});
2778+
2779+
constlogs=[];
2780+
consthandler=()=>logs.push('fired');
2781+
2782+
constchild=document.querySelector('#child');
2783+
constspy=jest.spyOn(child,'addEventListener');
2784+
// Per DOM spec, listener identity is (type, callback, capture).
2785+
// passive is NOT part of the key, so these are the SAME listener.
2786+
fragmentRef.current.addEventListener('click',handler,{passive: false});
2787+
// Second add is a no-op: same (type, callback, capture) identity.
2788+
fragmentRef.current.addEventListener('click',handler,{passive: true});
2789+
expect(spy).toHaveBeenCalledTimes(1);
2790+
expect(spy).toHaveBeenCalledWith('click',handler,{passive: false});
2791+
2792+
document.querySelector('#child').click();
2793+
// First handler fires once (second add was a no-op).
2794+
expect(logs).toEqual(['fired']);
2795+
2796+
// removeEventListener also ignores passive when matching
2797+
fragmentRef.current.removeEventListener('click',handler,{
2798+
passive: true,
2799+
});
2800+
2801+
logs.length=0;
2802+
document.querySelector('#child').click();
2803+
expect(logs).toEqual([]);
2804+
},
2805+
);
2806+
// @gate enableFragmentRefs
2807+
it(
2808+
'removes a listener registered with passive:false when removed with passive:true',
2809+
async()=>{
2810+
constfragmentRef=React.createRef(null);
2811+
functionTest(){
2812+
return(
2813+
<>
2814+
<divid="child-x"/>
2815+
</>
2816+
);
2817+
}
2818+
constroot=ReactDOMClient.createRoot(container);
2819+
awaitact(()=>{
2820+
root.render(
2821+
<Fragmentref={fragmentRef}>
2822+
<Test/>
2823+
</Fragment>,
2824+
);
2825+
});
2826+
constlogs=[];
2827+
functionhandler(){
2828+
logs.push('fired');
2829+
}
2830+
// Register with passive: false
2831+
fragmentRef.current.addEventListener('click',handler,{
2832+
passive: false,
2833+
});
2834+
document.querySelector('#child-x').click();
2835+
expect(logs).toEqual(['fired']);
2836+
logs.length=0;
2837+
// Remove with passive: true - per DOM spec, passive is NOT part of identity
2838+
// so this MUST remove the listener regardless of passive mismatch.
2839+
fragmentRef.current.removeEventListener('click',handler,{
2840+
passive: true,
2841+
});
2842+
document.querySelector('#child-x').click();
2843+
// Listener removed - no more invocations
2844+
expect(logs).toEqual([]);
2845+
},
2846+
);
26832847
});
26842848
});

0 commit comments

Comments
 (0)