Skip to content

Commit

Permalink
[Float][Fiber] implement a faster hydration match for hoistable eleme…
Browse files Browse the repository at this point in the history
…nts (#26154)

This PR is now based on #26256 

The original matching function for `hydrateHoistable` some challenging
time complexity since we built up the list of matchable nodes for each
link of that type and then had to check to exclusion. This new
implementation aims to improve the complexity

For hoisted title tags we match the first title if it is valid (not in
SVG context and does not have `itemprop`, the two ways you opt out of
hoisting when rendering titles). This path is much faster than others
and we use it because valid Documents only have 1 title anyway and if we
did have a mismatch the rendered title still ends up as the
Document.title so there is no functional degradation for misses.

For hoisted link and meta tags we track all potentially hydratable
Elements of this type in a cache per Document. The cache is refreshed
once each commit if and only if there is a title or meta hoistable
hydrating. The caches are partitioned by a natural key for each type
(href for link and content for meta). Then secondary attributes are
checked to see if the potential match is matchable.

For link we check `rel`, `title`, and `crossorigin`. These should
provide enough entropy that we never have collisions except is contrived
cases and even then it should not affect functionality of the page. This
should also be tolerant of links being injected in arbitrary places in
the Document by 3rd party scripts and browser extensions

For meta we check `name`, `property`, `http-equiv`, and `charset`. These
should provide enough entropy that we don't have meaningful collisions.
It is concievable with og tags that there may be true duplciates `<meta
property="og:image:size:height" content="100" />` but even if we did
bind to the wrong instance meta tags are typically only read from SSR by
bots and rarely inserted by 3rd parties so an adverse functional outcome
is not expected.
  • Loading branch information
gnoff authored Mar 7, 2023
1 parent 8a9f82e commit 978fae4
Show file tree
Hide file tree
Showing 10 changed files with 427 additions and 296 deletions.
140 changes: 75 additions & 65 deletions packages/react-dom-bindings/src/client/ReactDOMComponent.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,7 @@ import {
setValueForStyles,
validateShorthandPropertyCollisionInDev,
} from './CSSPropertyOperations';
import {
HTML_NAMESPACE,
MATH_NAMESPACE,
SVG_NAMESPACE,
getIntrinsicNamespace,
} from '../shared/DOMNamespaces';
import {HTML_NAMESPACE, getIntrinsicNamespace} from '../shared/DOMNamespaces';
import {
getPropertyInfo,
shouldIgnoreAttribute,
Expand Down Expand Up @@ -380,15 +375,83 @@ function updateDOMProperties(
}
}

// creates a script element that won't execute
export function createPotentiallyInlineScriptElement(
ownerDocument: Document,
): Element {
// Create the script via .innerHTML so its "parser-inserted" flag is
// set to true and it does not execute
const div = ownerDocument.createElement('div');
if (__DEV__) {
if (enableTrustedTypesIntegration && !didWarnScriptTags) {
console.error(
'Encountered a script tag while rendering React component. ' +
'Scripts inside React components are never executed when rendering ' +
'on the client. Consider using template tag instead ' +
'(https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template).',
);
didWarnScriptTags = true;
}
}
div.innerHTML = '<script><' + '/script>'; // eslint-disable-line
// This is guaranteed to yield a script element.
const firstChild = ((div.firstChild: any): HTMLScriptElement);
const element = div.removeChild(firstChild);
return element;
}

export function createSelectElement(
props: Object,
ownerDocument: Document,
): Element {
let element;
if (typeof props.is === 'string') {
element = ownerDocument.createElement('select', {is: props.is});
} else {
// Separate else branch instead of using `props.is || undefined` above because of a Firefox bug.
// See discussion in https://github.com/facebook/react/pull/6896
// and discussion in https://bugzilla.mozilla.org/show_bug.cgi?id=1276240
element = ownerDocument.createElement('select');
}
if (props.multiple) {
element.multiple = true;
} else if (props.size) {
// Setting a size greater than 1 causes a select to behave like `multiple=true`, where
// it is possible that no option is selected.
//
// This is only necessary when a select in "single selection mode".
element.size = props.size;
}
return element;
}

// Creates elements in the HTML namesapce
export function createHTMLElement(
type: string,
props: Object,
ownerDocument: Document,
): Element {
if (__DEV__) {
switch (type) {
case 'script':
case 'select':
console.error(
'createHTMLElement was called with a "%s" type. This type has special creation logic in React and should use the create function implemented specifically for it. This is a bug in React.',
type,
);
break;
case 'svg':
case 'math':
console.error(
'createHTMLElement was called with a "%s" type. This type must be created with Document.createElementNS which this method does not implement. This is a bug in React.',
type,
);
}
}

let isCustomComponentTag;

let domElement: Element;
let element: Element;
if (__DEV__) {
isCustomComponentTag = isCustomComponent(type, props);
// Should this check be gated by parent namespace? Not sure we want to
Expand All @@ -403,59 +466,20 @@ export function createHTMLElement(
}
}

if (type === 'script') {
// Create the script via .innerHTML so its "parser-inserted" flag is
// set to true and it does not execute
const div = ownerDocument.createElement('div');
if (__DEV__) {
if (enableTrustedTypesIntegration && !didWarnScriptTags) {
console.error(
'Encountered a script tag while rendering React component. ' +
'Scripts inside React components are never executed when rendering ' +
'on the client. Consider using template tag instead ' +
'(https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template).',
);
didWarnScriptTags = true;
}
}
div.innerHTML = '<script><' + '/script>'; // eslint-disable-line
// This is guaranteed to yield a script element.
const firstChild = ((div.firstChild: any): HTMLScriptElement);
domElement = div.removeChild(firstChild);
} else if (typeof props.is === 'string') {
domElement = ownerDocument.createElement(type, {is: props.is});
if (typeof props.is === 'string') {
element = ownerDocument.createElement(type, {is: props.is});
} else {
// Separate else branch instead of using `props.is || undefined` above because of a Firefox bug.
// See discussion in https://github.com/facebook/react/pull/6896
// and discussion in https://bugzilla.mozilla.org/show_bug.cgi?id=1276240
domElement = ownerDocument.createElement(type);
// Normally attributes are assigned in `setInitialDOMProperties`, however the `multiple` and `size`
// attributes on `select`s needs to be added before `option`s are inserted.
// This prevents:
// - a bug where the `select` does not scroll to the correct option because singular
// `select` elements automatically pick the first item #13222
// - a bug where the `select` set the first item as selected despite the `size` attribute #14239
// See https://github.com/facebook/react/issues/13222
// and https://github.com/facebook/react/issues/14239
if (type === 'select') {
const node = ((domElement: any): HTMLSelectElement);
if (props.multiple) {
node.multiple = true;
} else if (props.size) {
// Setting a size greater than 1 causes a select to behave like `multiple=true`, where
// it is possible that no option is selected.
//
// This is only necessary when a select in "single selection mode".
node.size = props.size;
}
}
element = ownerDocument.createElement(type);
}

if (__DEV__) {
if (
!isCustomComponentTag &&
// $FlowFixMe[method-unbinding]
Object.prototype.toString.call(domElement) ===
Object.prototype.toString.call(element) ===
'[object HTMLUnknownElement]' &&
!hasOwnProperty.call(warnedUnknownTags, type)
) {
Expand All @@ -469,21 +493,7 @@ export function createHTMLElement(
}
}

return domElement;
}

export function createSVGElement(
type: string,
ownerDocument: Document,
): Element {
return ownerDocument.createElementNS(SVG_NAMESPACE, type);
}

export function createMathElement(
type: string,
ownerDocument: Document,
): Element {
return ownerDocument.createElementNS(MATH_NAMESPACE, type);
return element;
}

export function createTextNode(
Expand Down
16 changes: 11 additions & 5 deletions packages/react-dom-bindings/src/client/ReactDOMComponentTree.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ const internalEventHandlersKey = '__reactEvents$' + randomKey;
const internalEventHandlerListenersKey = '__reactListeners$' + randomKey;
const internalEventHandlesSetKey = '__reactHandles$' + randomKey;
const internalRootNodeResourcesKey = '__reactResources$' + randomKey;
const internalResourceMarker = '__reactMarker$' + randomKey;
const internalHoistableMarker = '__reactMarker$' + randomKey;

export function detachDeletedInstance(node: Instance): void {
// TODO: This function is only called on host components. I don't think all of
Expand Down Expand Up @@ -288,10 +288,16 @@ export function getResourcesFromRoot(root: HoistableRoot): RootResources {
return resources;
}

export function isMarkedResource(node: Node): boolean {
return !!(node: any)[internalResourceMarker];
export function isMarkedHoistable(node: Node): boolean {
return !!(node: any)[internalHoistableMarker];
}

export function markNodeAsResource(node: Node) {
(node: any)[internalResourceMarker] = true;
export function markNodeAsHoistable(node: Node) {
(node: any)[internalHoistableMarker] = true;
}

export function isOwnedInstance(node: Node): boolean {
return !!(
(node: any)[internalHoistableMarker] || (node: any)[internalInstanceKey]
);
}
Loading

0 comments on commit 978fae4

Please sign in to comment.