Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Add DOM fixture page for Fragment Ref #32527

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions fixtures/dom/src/components/Header.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ class Header extends React.Component {
<option value="/selection-events">Selection Events</option>
<option value="/suspense">Suspense</option>
<option value="/form-state">Form State</option>
<option value="/fragment-refs">Fragment Refs</option>
</select>
</label>
<label htmlFor="global_version">
Expand Down
103 changes: 103 additions & 0 deletions fixtures/dom/src/components/fixtures/fragment-refs/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import Fixture from '../../Fixture';
import FixtureSet from '../../FixtureSet';
import TestCase from '../../TestCase';

const React = window.React;
const {Fragment, useEffect, useRef, useState} = React;

function WrapperComponent(props) {
return props.children;
}

function handler(e) {
const text = e.currentTarget.innerText;
alert('You clicked: ' + text);
}

export default function FragmentRefsPage() {
const fragmentRef = useRef(null);
const [extraChildCount, setExtraChildCount] = useState(0);

React.useEffect(() => {
fragmentRef.current.addEventListener('click', handler);

return () => {
fragmentRef.current.removeEventListener('click', handler);
};
});

return (
<FixtureSet title="Fragment Refs">
<TestCase title="Event registration">
<TestCase.Steps>
<li>Click one of the children, observe the alert</li>
<li>Add a new child, click it, observe the alert</li>
<li>Remove the event listeners, click a child, observe no alert</li>
<li>
Add the event listeners back, click a child, observe the alert
</li>
</TestCase.Steps>

<TestCase.ExpectedResult>
<p>
Fragment refs can manage event listeners on the first level of host
children. This page loads with an effect that sets up click event
hanndlers on each child card. Clicking on a card will show an alert
with the card's text.
</p>
<p>
New child nodes will also have event listeners applied. Removed
nodes will have their listeners cleaned up.
</p>
</TestCase.ExpectedResult>

<Fixture>
<div className="control-box" id="control-box">
<div>Target count: {extraChildCount + 3}</div>
<button
onClick={() => {
setExtraChildCount(prev => prev + 1);
}}>
Add Child
</button>
<button
onClick={() => {
fragmentRef.current.addEventListener('click', handler);
}}>
Add click event listeners
</button>
<button
onClick={() => {
fragmentRef.current.removeEventListener('click', handler);
}}>
Remove click event listeners
</button>
<div class="card-container">
<Fragment ref={fragmentRef}>
<div className="card" id="child-a">
Child A
</div>
<div className="card" id="child-b">
Child B
</div>
<WrapperComponent>
<div className="card" id="child-c">
Child C
</div>
{Array.from({length: extraChildCount}).map((_, index) => (
<div
className="card"
id={'extra-child-' + index}
key={index}>
Extra Child {index}
</div>
))}
</WrapperComponent>
</Fragment>
</div>
</div>
</Fixture>
</TestCase>
</FixtureSet>
);
}
13 changes: 13 additions & 0 deletions fixtures/dom/src/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -309,3 +309,16 @@ th {
tbody tr:nth-child(even) {
background: #f0f0f0;
}

.card-container {
display: flex;
flex-wrap: wrap;
}

.card {
background: white;
border-radius: 2px;
border: 1px solid rgba(0, 0, 0, 0.24);
margin: 10px;
padding: 10px;
}
20 changes: 20 additions & 0 deletions packages/react-art/src/ReactFiberConfigART.js
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,26 @@ export function createTextInstance(
return text;
}

export type FragmentInstance = null | {
_fragmentFiber: Object,
...
};

export function createFragmentInstance(parentInstance): null {
return null;
}

export function commitNewChildToFragmentInstance(
child,
fragmentInstance,
): void {
// Noop
}

export function deleteChildFromFragmentInstance(child, fragmentInstance): void {
// Noop
}

export function finalizeInitialChildren(domElement, type, props) {
return false;
}
Expand Down
210 changes: 210 additions & 0 deletions packages/react-dom-bindings/src/client/ReactFiberConfigDOM.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import {getCurrentRootHostContainer} from 'react-reconciler/src/ReactFiberHostCo
import hasOwnProperty from 'shared/hasOwnProperty';
import {checkAttributeStringCoercion} from 'shared/CheckStringCoercion';
import {REACT_CONTEXT_TYPE} from 'shared/ReactSymbols';
import {OffscreenComponent} from 'react-reconciler/src/ReactWorkTags';

export {
setCurrentUpdatePriority,
Expand Down Expand Up @@ -1534,6 +1535,215 @@ export function subscribeToGestureDirection(
}
}

type EventListenerOptionsOrUseCapture =
| boolean
| {
capture?: boolean,
once?: boolean,
passive?: boolean,
signal?: AbortSignal,
...
};

type StoredEventListener = {
type: string,
listener: EventListener,
optionsOrUseCapture: void | EventListenerOptionsOrUseCapture,
};

export type FragmentInstance = {
_fragmentFiber: Fiber,
_eventListeners: void | Array<StoredEventListener>,
addEventListener(
type: string,
listener: EventListener,
optionsOrUseCapture?: EventListenerOptionsOrUseCapture,
): void,
removeEventListener(
type: string,
listener: EventListener,
optionsOrUseCapture?: EventListenerOptionsOrUseCapture,
): void,
focus(): void,
};

function FragmentInstancePseudoElement(
this: FragmentInstance,
fragmentFiber: Fiber,
) {
this._fragmentFiber = fragmentFiber;
}
// $FlowFixMe[prop-missing]
FragmentInstancePseudoElement.prototype.addEventListener = function (
this: FragmentInstance,
type: string,
listener: EventListener,
optionsOrUseCapture?: EventListenerOptionsOrUseCapture,
): void {
if (!this._eventListeners) {
this._eventListeners = [];
}

const listeners = this._eventListeners;
// Element.addEventListener will only apply uniquely new event listeners by default. Since we
// need to collect the listeners to apply to appended children, we track them ourselves and use
// custom equality check for the options.
const isNewEventListener =
indexOfEventListener(listeners, {
type,
listener,
optionsOrUseCapture,
}) === -1;
if (isNewEventListener) {
listeners.push({type, listener, optionsOrUseCapture});
traverseFragmentInstanceChildren(
this,
this._fragmentFiber.child,
addEventListenerToChild.bind(null, type, listener, optionsOrUseCapture),
);
}
this._eventListeners = listeners;
};
function addEventListenerToChild(
type: string,
listener: EventListener,
optionsOrUseCapture?: EventListenerOptionsOrUseCapture,
child: Element,
): void {
child.addEventListener(type, listener, optionsOrUseCapture);
}
// $FlowFixMe[prop-missing]
FragmentInstancePseudoElement.prototype.removeEventListener = function (
this: FragmentInstance,
type: string,
listener: EventListener,
optionsOrUseCapture?: EventListenerOptionsOrUseCapture,
): void {
const listeners = this._eventListeners;
if (typeof listeners !== 'undefined' && listeners.length > 0) {
traverseFragmentInstanceChildren(
this,
this._fragmentFiber.child,
removeEventListenerFromChild.bind(
null,
type,
listener,
optionsOrUseCapture,
),
);
const index = indexOfEventListener(listeners, {
type,
listener,
optionsOrUseCapture,
});
if (this._eventListeners !== undefined) {
this._eventListeners.splice(index, 1);
}
}
};
function removeEventListenerFromChild(
type: string,
listener: EventListener,
optionsOrUseCapture?: EventListenerOptionsOrUseCapture,
child: Element,
): void {
child.removeEventListener(type, listener, optionsOrUseCapture);
}
// $FlowFixMe[prop-missing]
FragmentInstancePseudoElement.prototype.focus = function (
this: FragmentInstance,
) {
traverseFragmentInstanceChildren(
this,
this._fragmentFiber.child,
setFocusIfFocusable,
);
};

function traverseFragmentInstanceChildren(
fragmentInstance: FragmentInstance,
child: Fiber | null,
fn: (child: Element) => boolean | void,
): void {
while (child !== null) {
if (child.tag === HostComponent) {
if (fn(child.stateNode)) {
return;
}
} else if (
child.tag === OffscreenComponent &&
child.memoizedState !== null
) {
// Skip hidden subtrees
} else {
traverseFragmentInstanceChildren(fragmentInstance, child.child, fn);
}
child = child.sibling;
}
}

function normalizeListenerOptions(
opts: ?EventListenerOptionsOrUseCapture,
): string {
if (opts == null) {
return '0';
}

if (typeof opts === 'boolean') {
return `c=${opts ? '1' : '0'}`;
}

return `c=${opts.capture ? '1' : '0'}&o=${opts.once ? '1' : '0'}&p=${opts.passive ? '1' : '0'}`;
}

function indexOfEventListener(
eventListeners: Array<StoredEventListener>,
eventListenerToFind: StoredEventListener,
): number {
for (let i = 0; i < eventListeners.length; i++) {
const item = eventListeners[i];
if (
item.type === eventListenerToFind.type &&
item.listener === eventListenerToFind.listener &&
normalizeListenerOptions(item.optionsOrUseCapture) ===
normalizeListenerOptions(eventListenerToFind.optionsOrUseCapture)
) {
return i;
}
}
return -1;
}

export function createFragmentInstance(fragmentFiber: Fiber): FragmentInstance {
return new (FragmentInstancePseudoElement: any)(fragmentFiber);
}

export function commitNewChildToFragmentInstance(
childElement: Element,
fragmentInstance: FragmentInstance,
): void {
const eventListeners = fragmentInstance._eventListeners;
if (eventListeners !== undefined) {
for (let i = 0; i < eventListeners.length; i++) {
const {type, listener, optionsOrUseCapture} = eventListeners[i];
childElement.addEventListener(type, listener, optionsOrUseCapture);
}
}
}

export function deleteChildFromFragmentInstance(
childElement: Element,
fragmentInstance: FragmentInstance,
): void {
const eventListeners = fragmentInstance._eventListeners;
if (eventListeners !== undefined) {
for (let i = 0; i < eventListeners.length; i++) {
const {type, listener, optionsOrUseCapture} = eventListeners[i];
childElement.removeEventListener(type, listener, optionsOrUseCapture);
}
}
}

export function clearContainer(container: Container): void {
const nodeType = container.nodeType;
if (nodeType === DOCUMENT_NODE) {
Expand Down
Loading