Skip to content

Validate node nesting structure #735

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

Closed
wants to merge 6 commits into from
Closed
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
10 changes: 10 additions & 0 deletions src/browser/ReactComponentBrowserEnvironment.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@ var ReactReconcileTransaction = require('ReactReconcileTransaction');
var getReactRootElementInContainer = require('getReactRootElementInContainer');
var invariant = require('invariant');

if (__DEV__) {
var getNodeNameFromReactMarkup = require('getNodeNameFromReactMarkup');
var validateNodeNesting = require('validateNodeNesting');
}


var ELEMENT_NODE_TYPE = 1;
var DOC_NODE_TYPE = 9;
Expand Down Expand Up @@ -133,6 +138,11 @@ var ReactComponentBrowserEnvironment = {
'See renderComponentToString() for server rendering.'
);

if (__DEV__) {
var nodeName = getNodeNameFromReactMarkup(markup);
validateNodeNesting(container.nodeName, nodeName);
}

// Asynchronously inject markup by ensuring that the container is not in
// the document when settings its `innerHTML`.
var parent = container.parentNode;
Expand Down
10 changes: 5 additions & 5 deletions src/browser/ReactDOM.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,12 +72,12 @@ var ReactDOM = objMapKeyVal({
a: false,
abbr: false,
address: false,
area: false,
area: true,
article: false,
aside: false,
audio: false,
b: false,
base: false,
base: true,
bdi: false,
bdo: false,
big: false,
Expand Down Expand Up @@ -127,7 +127,7 @@ var ReactDOM = objMapKeyVal({
label: false,
legend: false,
li: false,
link: false,
link: true,
main: false,
map: false,
mark: false,
Expand Down Expand Up @@ -156,7 +156,7 @@ var ReactDOM = objMapKeyVal({
section: false,
select: false,
small: false,
source: false,
source: true,
span: false,
strong: false,
style: false,
Expand All @@ -178,7 +178,7 @@ var ReactDOM = objMapKeyVal({
ul: false,
'var': false,
video: false,
wbr: false,
wbr: true,

// SVG
circle: false,
Expand Down
28 changes: 22 additions & 6 deletions src/browser/ReactDOMComponent.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@ var keyOf = require('keyOf');
var merge = require('merge');
var mixInto = require('mixInto');

if (__DEV__) {
var getNodeNameFromReactMarkup = require('getNodeNameFromReactMarkup');
var validateNodeNesting = require('validateNodeNesting');
}

var deleteListener = ReactEventEmitter.deleteListener;
var listenTo = ReactEventEmitter.listenTo;
var registrationNameModules = ReactEventEmitter.registrationNameModules;
Expand Down Expand Up @@ -114,9 +119,20 @@ ReactDOMComponent.Mixin = {
mountDepth
);
assertValidProps(this.props);
var contentMarkup = this._createContentMarkup(transaction);
if (__DEV__) {
if (contentMarkup) {
var tagName = this.tagName;
for (var i = 0, l = contentMarkup.length; i < l; i++) {
var markup = contentMarkup[i];
var nodeName = getNodeNameFromReactMarkup(markup);
validateNodeNesting(tagName, nodeName);
}
}
}
return (
this._createOpenTagMarkupAndPutListeners(transaction) +
this._createContentMarkup(transaction) +
(contentMarkup ? contentMarkup.join('') : '') +
this._tagClose
);
}
Expand Down Expand Up @@ -172,30 +188,30 @@ ReactDOMComponent.Mixin = {
*
* @private
* @param {ReactReconcileTransaction} transaction
* @return {string} Content markup.
* @return {array<string>} Content markup or list of content markup.
*/
_createContentMarkup: function(transaction) {
// Intentional use of != to avoid catching zero/false.
var innerHTML = this.props.dangerouslySetInnerHTML;
if (innerHTML != null) {
if (innerHTML.__html != null) {
return innerHTML.__html;
return [innerHTML.__html];
}
} else {
var contentToUse =
CONTENT_TYPES[typeof this.props.children] ? this.props.children : null;
var childrenToUse = contentToUse != null ? null : this.props.children;
if (contentToUse != null) {
return escapeTextForBrowser(contentToUse);
return [escapeTextForBrowser(contentToUse)];
} else if (childrenToUse != null) {
var mountImages = this.mountChildren(
childrenToUse,
transaction
);
return mountImages.join('');
return mountImages;
}
}
return '';
return null;
},

receiveComponent: function(nextComponent, transaction) {
Expand Down
12 changes: 12 additions & 0 deletions src/browser/dom/DOMChildrenOperations.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ var ReactMultiChildUpdateTypes = require('ReactMultiChildUpdateTypes');

var getTextContentAccessor = require('getTextContentAccessor');

if (__DEV__) {
var validateNodeNesting = require('validateNodeNesting');
}

/**
* The DOM property to use when setting text content.
*
Expand All @@ -41,6 +45,9 @@ var textContentAccessor = getTextContentAccessor();
* @internal
*/
function insertChildAt(parentNode, childNode, index) {
if (__DEV__) {
validateNodeNesting(parentNode.nodeName, childNode.nodeName);
}
var childNodes = parentNode.childNodes;
if (childNodes[index] === childNode) {
return;
Expand Down Expand Up @@ -121,6 +128,11 @@ var DOMChildrenOperations = {
);
break;
case ReactMultiChildUpdateTypes.TEXT_CONTENT:
if (__DEV__) {
if (update.textContent !== '') {
validateNodeNesting(update.parentNode.nodeName, '#text');
}
}
update.parentNode[textContentAccessor] = update.textContent;
break;
case ReactMultiChildUpdateTypes.REMOVE_NODE:
Expand Down
25 changes: 9 additions & 16 deletions src/browser/dom/Danger.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,26 +26,16 @@ var ExecutionEnvironment = require('ExecutionEnvironment');
var createNodesFromMarkup = require('createNodesFromMarkup');
var emptyFunction = require('emptyFunction');
var getMarkupWrap = require('getMarkupWrap');
var getNodeNameFromReactMarkup = require('getNodeNameFromReactMarkup');
var invariant = require('invariant');

if (__DEV__) {
var validateNodeNesting = require('validateNodeNesting');
}

var OPEN_TAG_NAME_EXP = /^(<[^ \/>]+)/;
var RESULT_INDEX_ATTR = 'data-danger-index';

/**
* Extracts the `nodeName` from a string of markup.
*
* NOTE: Extracting the `nodeName` does not require a regular expression match
* because we make assumptions about React-generated markup (i.e. there are no
* spaces surrounding the opening tag and there is at least one attribute).
*
* @param {string} markup String of markup.
* @return {string} Node name of the supplied markup.
* @see http://jsperf.com/extract-nodename
*/
function getNodeName(markup) {
return markup.substring(1, markup.indexOf(' '));
}

var Danger = {

/**
Expand All @@ -72,7 +62,7 @@ var Danger = {
markupList[i],
'dangerouslyRenderMarkup(...): Missing markup.'
);
nodeName = getNodeName(markupList[i]);
nodeName = getNodeNameFromReactMarkup(markupList[i]);
nodeName = getMarkupWrap(nodeName) ? nodeName : '*';
markupByNodeName[nodeName] = markupByNodeName[nodeName] || [];
markupByNodeName[nodeName][i] = markupList[i];
Expand Down Expand Up @@ -179,6 +169,9 @@ var Danger = {
);

var newChild = createNodesFromMarkup(markup, emptyFunction)[0];
if (__DEV__) {
validateNodeNesting(oldChild.parentNode.nodeName, newChild.nodeName);
}
oldChild.parentNode.replaceChild(newChild, oldChild);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,9 +95,9 @@ describe('ReactCompositeComponentDOMMinimalism', function() {
it('should not render extra nodes for non-interpolated text', function() {
var instance = (
<MyCompositeComponent>
<ul>
This text causes no children in ul, just innerHTML
</ul>
<span>
This text causes no children in span, just innerHTML
</span>
</MyCompositeComponent>
);
ReactTestUtils.renderIntoDocument(instance);
Expand All @@ -108,7 +108,7 @@ describe('ReactCompositeComponentDOMMinimalism', function() {
.toBeDOMComponentWithTag('div')
.toBeDOMComponentWithChildCount(1)
.expectRenderedChildAt(0)
.toBeDOMComponentWithTag('ul')
.toBeDOMComponentWithTag('span')
.toBeDOMComponentWithNoChildren();
});

Expand Down
23 changes: 19 additions & 4 deletions src/core/__tests__/ReactDOMComponent-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,19 @@ describe('ReactDOMComponent', function() {
stub.receiveComponent({props: {}}, transaction);
expect(nodeValueSetter.mock.calls.length).toBe(1);
});

it("should warn on invalid markup nesting", function() {
spyOn(console, 'warn');
expect(console.warn.argsForCall.length).toBe(0);
var stub = ReactTestUtils.renderIntoDocument(
<div><tr /></div>
);

expect(console.warn.argsForCall.length).toBe(1);
expect(console.warn.argsForCall[0][0]).toBe(
'validateNodeNesting(...): <div> cannot contain a <tr> node.'
);
});
});

describe('createOpenTagMarkup', function() {
Expand Down Expand Up @@ -260,10 +273,11 @@ describe('ReactDOMComponent', function() {
beforeEach(function() {
require('mock-modules').dumpCache();

var mixInto = require('mixInto');
var ReactDOMComponent = require('ReactDOMComponent');
var ReactReconcileTransaction = require('ReactReconcileTransaction');

var mixInto = require('mixInto');

var NodeStub = function(initialProps) {
this.props = initialProps || {};
this._rootNodeID = 'test';
Expand All @@ -272,11 +286,12 @@ describe('ReactDOMComponent', function() {

genMarkup = function(props) {
var transaction = new ReactReconcileTransaction();
return (new NodeStub(props))._createContentMarkup(transaction);
var markup = (new NodeStub(props))._createContentMarkup(transaction);
return markup.join('');
};

this.addMatchers({
toHaveInnerhtml: function(html) {
toHaveInnerHTML: function(html) {
var expected = '^' + quoteRegexp(html) + '$';
return this.actual.match(new RegExp(expected));
}
Expand All @@ -287,7 +302,7 @@ describe('ReactDOMComponent', function() {
var innerHTML = {__html: 'testContent'};
expect(
genMarkup({ dangerouslySetInnerHTML: innerHTML })
).toHaveInnerhtml('testContent');
).toHaveInnerHTML('testContent');
});
});

Expand Down
2 changes: 1 addition & 1 deletion src/core/__tests__/refs-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ var ClickCounter = React.createClass({
var i;
for (i=0; i < this.state.count; i++) {
children.push(
<div
<span
className="clickLogDiv"
key={"clickLog" + i}
ref={"clickLog" + i}
Expand Down
42 changes: 42 additions & 0 deletions src/dom/getNodeNameFromReactMarkup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule getNodeNameFromReactMarkup
*/

"use strict";

/**
* Extracts the `nodeName` from a string of markup generated by React.
*
* NOTE: Extracting the `nodeName` does not require a regular expression match
* because we make assumptions about React-generated markup (i.e. there are no
* spaces surrounding the opening tag and there is at least one attribute).
*
* @param {string} markup String of markup.
* @return {string} Node name of the supplied markup.
* @see http://jsperf.com/extract-nodename/2
*/
function getNodeNameFromReactMarkup(markup) {
if (markup.charAt(0) === '<') {
return markup.substring(1, markup.indexOf(' '));
} else if (markup) {
return '#text';
} else {
return '';
}
}

module.exports = getNodeNameFromReactMarkup;
Loading