Update prettier to 1.8.1 (#10785)

* Change prettier dependency in package.json version 1.8.1

* Update yarn.lock

* Apply prettier changes

* Fix ReactDOMServerIntegration-test.js

* Fix test for ReactDOMComponent-test.js
This commit is contained in:
Clement Hoang 2017-11-07 18:09:33 +00:00 committed by GitHub
parent 05f3ecc3ea
commit 94f44aeba7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
160 changed files with 2494 additions and 1704 deletions

View File

@ -137,12 +137,12 @@ var RING_TWO_PATH =
var RING_THREE_PATH = var RING_THREE_PATH =
'M84,121 C130.391921,121 168,106.673113 168,89 C168,71.3268871 130.391921,57 84,57 C37.6080787,57 0,71.3268871 0,89 C0,106.673113 37.6080787,121 84,121 Z M84,121'; 'M84,121 C130.391921,121 168,106.673113 168,89 C168,71.3268871 130.391921,57 84,57 C37.6080787,57 0,71.3268871 0,89 C0,106.673113 37.6080787,121 84,121 Z M84,121';
var RING_TWO_ROTATE = new Transform() var RING_TWO_ROTATE = new Transform()
.translate(84.000000, 89.000000) .translate(84.0, 89.0)
.rotate(-240.000000) .rotate(-240.0)
.translate(-84.000000, -89.000000); .translate(-84.0, -89.0);
var RING_THREE_ROTATE = new Transform() var RING_THREE_ROTATE = new Transform()
.translate(84.000000, 89.000000) .translate(84.0, 89.0)
.rotate(-300.000000) .rotate(-300.0)
.translate(-84.000000, -89.000000); .translate(-84.0, -89.0);
module.exports = VectorWidget; module.exports = VectorWidget;

View File

@ -185,7 +185,9 @@ function getCanonicalizedValue(value) {
if (typeof value.length === 'number') { if (typeof value.length === 'number') {
return ( return (
'[' + '[' +
Array.from(value).map(v => getCanonicalizedValue(v)).join(', ') + Array.from(value)
.map(v => getCanonicalizedValue(v))
.join(', ') +
']' ']'
); );
} }
@ -459,7 +461,9 @@ function prepareState(initGlobals) {
hasSameBehaviorForAll, hasSameBehaviorForAll,
rowPatternHash, rowPatternHash,
// "Good enough" id that we can store in localStorage // "Good enough" id that we can store in localStorage
rowIdHash: `${attribute.name} ${attribute.tagName} ${attribute.overrideStringValue}`, rowIdHash: `${attribute.name} ${attribute.tagName} ${
attribute.overrideStringValue
}`,
}; };
const rowGroup = rowPatternHashes.get(rowPatternHash) || new Set(); const rowGroup = rowPatternHashes.get(rowPatternHash) || new Set();
rowGroup.add(row); rowGroup.add(row);
@ -677,9 +681,11 @@ function CellContent(props) {
<RowHeader <RowHeader
checked={completedHashes.has(rowPatternHash)} checked={completedHashes.has(rowPatternHash)}
onChange={() => toggleAttribute(rowPatternHash)}> onChange={() => toggleAttribute(rowPatternHash)}>
{row.hasSameBehaviorForAll {row.hasSameBehaviorForAll ? (
? attribute.name attribute.name
: <b css={{color: 'purple'}}>{attribute.name}</b>} ) : (
<b css={{color: 'purple'}}>{attribute.name}</b>
)}
</RowHeader> </RowHeader>
); );
} }
@ -754,8 +760,10 @@ class App extends React.Component {
async componentDidMount() { async componentDidMount() {
const sources = { const sources = {
ReactStable: 'https://unpkg.com/react@latest/umd/react.development.js', ReactStable: 'https://unpkg.com/react@latest/umd/react.development.js',
ReactDOMStable: 'https://unpkg.com/react-dom@latest/umd/react-dom.development.js', ReactDOMStable:
ReactDOMServerStable: 'https://unpkg.com/react-dom@latest/umd/react-dom-server.browser.development.js', 'https://unpkg.com/react-dom@latest/umd/react-dom.development.js',
ReactDOMServerStable:
'https://unpkg.com/react-dom@latest/umd/react-dom-server.browser.development.js',
ReactNext: '/react.development.js', ReactNext: '/react.development.js',
ReactDOMNext: '/react-dom.development.js', ReactDOMNext: '/react-dom.development.js',
ReactDOMServerNext: '/react-dom-server.browser.development.js', ReactDOMServerNext: '/react-dom-server.browser.development.js',
@ -860,12 +868,12 @@ class App extends React.Component {
case ALPHABETICAL: case ALPHABETICAL:
return filteredAttributes.sort( return filteredAttributes.sort(
(attr1, attr2) => (attr1, attr2) =>
(attr1.name.toLowerCase() < attr2.name.toLowerCase() ? -1 : 1) attr1.name.toLowerCase() < attr2.name.toLowerCase() ? -1 : 1
); );
case REV_ALPHABETICAL: case REV_ALPHABETICAL:
return filteredAttributes.sort( return filteredAttributes.sort(
(attr1, attr2) => (attr1, attr2) =>
(attr1.name.toLowerCase() < attr2.name.toLowerCase() ? 1 : -1) attr1.name.toLowerCase() < attr2.name.toLowerCase() ? 1 : -1
); );
case GROUPED_BY_ROW_PATTERN: { case GROUPED_BY_ROW_PATTERN: {
return filteredAttributes.sort((attr1, attr2) => { return filteredAttributes.sort((attr1, attr2) => {
@ -895,7 +903,8 @@ class App extends React.Component {
let log = ''; let log = '';
for (let attribute of attributes) { for (let attribute of attributes) {
log += `## \`${attribute.name}\` (on \`<${attribute.tagName || 'div'}>\` inside \`<${attribute.containerTagName || 'div'}>\`)\n`; log += `## \`${attribute.name}\` (on \`<${attribute.tagName ||
'div'}>\` inside \`<${attribute.containerTagName || 'div'}>\`)\n`;
log += '| Test Case | Flags | Result |\n'; log += '| Test Case | Flags | Result |\n';
log += '| --- | --- | --- |\n'; log += '| --- | --- | --- |\n';
@ -950,8 +959,9 @@ class App extends React.Component {
return ( return (
<div> <div>
<h1>Loading...</h1> <h1>Loading...</h1>
{!useFastMode && {!useFastMode && (
<h3>The progress is reported in the window title.</h3>} <h3>The progress is reported in the window title.</h3>
)}
</div> </div>
); );
} }
@ -959,31 +969,22 @@ class App extends React.Component {
<div> <div>
<div> <div>
<select value={this.state.sortOrder} onChange={this.onUpdateSort}> <select value={this.state.sortOrder} onChange={this.onUpdateSort}>
<option value={ALPHABETICAL}> <option value={ALPHABETICAL}>alphabetical</option>
alphabetical <option value={REV_ALPHABETICAL}>reverse alphabetical</option>
</option>
<option value={REV_ALPHABETICAL}>
reverse alphabetical
</option>
<option value={GROUPED_BY_ROW_PATTERN}> <option value={GROUPED_BY_ROW_PATTERN}>
grouped by row pattern :) grouped by row pattern :)
</option> </option>
</select> </select>
<select value={this.state.filter} onChange={this.onUpdateFilter}> <select value={this.state.filter} onChange={this.onUpdateFilter}>
<option value={ALL}> <option value={ALL}>all</option>
all <option value={INCOMPLETE}>incomplete</option>
</option> <option value={COMPLETE}>complete</option>
<option value={INCOMPLETE}>
incomplete
</option>
<option value={COMPLETE}>
complete
</option>
</select> </select>
<button style={{marginLeft: '10px'}} onClick={this.handleSaveClick}> <button style={{marginLeft: '10px'}} onClick={this.handleSaveClick}>
Save latest results to a file Save latest results to a file{' '}
{' '} <span role="img" aria-label="Save">
<span role="img" aria-label="Save">💾</span> 💾
</span>
</button> </button>
</div> </div>
<AutoSizer disableHeight={true}> <AutoSizer disableHeight={true}>

View File

@ -843,7 +843,8 @@ const attributes = [
name: 'gradientTransform', name: 'gradientTransform',
read: getSVGProperty('gradientTransform'), read: getSVGProperty('gradientTransform'),
containerTagName: 'svg', containerTagName: 'svg',
overrideStringValue: 'translate(-10,-20) scale(2) rotate(45) translate(5,10)', overrideStringValue:
'translate(-10,-20) scale(2) rotate(45) translate(5,10)',
tagName: 'linearGradient', tagName: 'linearGradient',
}, },
{ {
@ -1353,7 +1354,8 @@ const attributes = [
read: getSVGProperty('patternTransform'), read: getSVGProperty('patternTransform'),
containerTagName: 'svg', containerTagName: 'svg',
tagName: 'pattern', tagName: 'pattern',
overrideStringValue: 'translate(-10,-20) scale(2) rotate(45) translate(5,10)', overrideStringValue:
'translate(-10,-20) scale(2) rotate(45) translate(5,10)',
}, },
{ {
name: 'patternUnits', name: 'patternUnits',
@ -1940,7 +1942,8 @@ const attributes = [
read: getSVGProperty('transform'), read: getSVGProperty('transform'),
containerTagName: 'svg', containerTagName: 'svg',
tagName: 'a', tagName: 'a',
overrideStringValue: 'translate(-10,-20) scale(2) rotate(45) translate(5,10)', overrideStringValue:
'translate(-10,-20) scale(2) rotate(45) translate(5,10)',
}, },
{name: 'type', tagName: 'button', overrideStringValue: 'reset'}, {name: 'type', tagName: 'button', overrideStringValue: 'reset'},
{ {

View File

@ -9,11 +9,7 @@ class Fixture extends React.Component {
render() { render() {
const {children} = this.props; const {children} = this.props;
return ( return <div className="test-fixture">{children}</div>;
<div className="test-fixture">
{children}
</div>
);
} }
} }

View File

@ -71,7 +71,9 @@ class Header extends React.Component {
value={this.state.version} value={this.state.version}
onChange={this.handleVersionChange}> onChange={this.handleVersionChange}>
{this.state.versions.map(version => ( {this.state.versions.map(version => (
<option key={version} value={version}>{version}</option> <option key={version} value={version}>
{version}
</option>
))} ))}
</select> </select>
</label> </label>

View File

@ -59,60 +59,65 @@ class TestCase extends React.Component {
type="checkbox" type="checkbox"
checked={complete} checked={complete}
onChange={this.handleChange} onChange={this.handleChange}
/> />{' '}
{' '}{title} {title}
</label> </label>
</h2> </h2>
<dl className="test-case__details"> <dl className="test-case__details">
{introducedIn && <dt>First broken in: </dt>} {introducedIn && <dt>First broken in: </dt>}
{introducedIn && {introducedIn && (
<dd> <dd>
<a <a
href={'https://github.com/facebook/react/tag/v' + introducedIn}> href={'https://github.com/facebook/react/tag/v' + introducedIn}>
<code>{introducedIn}</code> <code>{introducedIn}</code>
</a> </a>
</dd>} </dd>
)}
{resolvedIn && <dt>First supported in: </dt>} {resolvedIn && <dt>First supported in: </dt>}
{resolvedIn && {resolvedIn && (
<dd> <dd>
<a href={'https://github.com/facebook/react/tag/v' + resolvedIn}> <a href={'https://github.com/facebook/react/tag/v' + resolvedIn}>
<code>{resolvedIn}</code> <code>{resolvedIn}</code>
</a> </a>
</dd>} </dd>
)}
{resolvedBy && <dt>Fixed by: </dt>} {resolvedBy && <dt>Fixed by: </dt>}
{resolvedBy && {resolvedBy && (
<dd> <dd>
<a <a
href={ href={
'https://github.com/facebook/react/pull/' + 'https://github.com/facebook/react/pull/' +
resolvedBy.slice(1) resolvedBy.slice(1)
}> }>
<code>{resolvedBy}</code> <code>{resolvedBy}</code>
</a> </a>
</dd>} </dd>
)}
{affectedBrowsers && <dt>Affected browsers: </dt>} {affectedBrowsers && <dt>Affected browsers: </dt>}
{affectedBrowsers && <dd>{affectedBrowsers}</dd>} {affectedBrowsers && <dd>{affectedBrowsers}</dd>}
{relatedIssues && <dt>Related Issues: </dt>} {relatedIssues && <dt>Related Issues: </dt>}
{relatedIssues && <dd><IssueList issues={relatedIssues} /></dd>} {relatedIssues && (
<dd>
<IssueList issues={relatedIssues} />
</dd>
)}
</dl> </dl>
<p className="test-case__desc"> <p className="test-case__desc">{description}</p>
{description}
</p>
<div className="test-case__body"> <div className="test-case__body">
{!isTestFixed && {!isTestFixed && (
<p className="test-case__invalid-version"> <p className="test-case__invalid-version">
<strong>Note:</strong> <strong>Note:</strong> This test case was fixed in a later version
{' '} of React. This test is not expected to pass for the selected
This test case was fixed in a later version of React. version, and that's ok!
This test is not expected to pass for the selected version, and that's ok! </p>
</p>} )}
{children} {children}
</div> </div>
@ -129,9 +134,7 @@ TestCase.Steps = class extends React.Component {
return ( return (
<div> <div>
<h3>Steps to reproduce:</h3> <h3>Steps to reproduce:</h3>
<ol> <ol>{children}</ol>
{children}
</ol>
</div> </div>
); );
} }
@ -143,9 +146,7 @@ TestCase.ExpectedResult = class extends React.Component {
return ( return (
<div> <div>
<h3>Expected Result:</h3> <h3>Expected Result:</h3>
<p> <p>{children}</p>
{children}
</p>
</div> </div>
); );
} }

View File

@ -20,7 +20,9 @@ export default class ButtonTestCases extends React.Component {
<TestCase.ExpectedResult> <TestCase.ExpectedResult>
Nothing should happen Nothing should happen
</TestCase.ExpectedResult> </TestCase.ExpectedResult>
<button disabled onClick={onButtonClick}>Click Me</button> <button disabled onClick={onButtonClick}>
Click Me
</button>
</TestCase> </TestCase>
<TestCase <TestCase
title="onClick with disabled buttons containing other elements" title="onClick with disabled buttons containing other elements"

View File

@ -42,11 +42,11 @@ export default class ButtonTestCases extends React.Component {
<TestCase.ExpectedResult> <TestCase.ExpectedResult>
You should see "Hello, World" printed below.{' '} You should see "Hello, World" printed below.{' '}
</TestCase.ExpectedResult> </TestCase.ExpectedResult>
{supportsCustomElements {supportsCustomElements ? (
? <my-element /> <my-element />
: <div> ) : (
This browser does not support custom elements. <div>This browser does not support custom elements.</div>
</div>} )}
</TestCase> </TestCase>
</FixtureSet> </FixtureSet>
); );

View File

@ -16,9 +16,8 @@ class DateInputFixtures extends React.Component {
</TestCase.Steps> </TestCase.Steps>
<TestCase.ExpectedResult> <TestCase.ExpectedResult>
The month, day, and year values should correctly The month, day, and year values should correctly transfer. The
transfer. The hours/minutes/seconds should not be hours/minutes/seconds should not be discarded.
discarded.
</TestCase.ExpectedResult> </TestCase.ExpectedResult>
<Fixture> <Fixture>

View File

@ -16,7 +16,9 @@ class SwitchDateTestCase extends React.Component {
return ( return (
<div> <div>
<p><b>{attrs.type}</b> input type ({attrs.value})</p> <p>
<b>{attrs.type}</b> input type ({attrs.value})
</p>
<p> <p>
<input <input
type={attrs.type} type={attrs.type}
@ -28,8 +30,7 @@ class SwitchDateTestCase extends React.Component {
type="checkbox" type="checkbox"
checked={this.state.fullDate} checked={this.state.fullDate}
onChange={this.updateFullDate} onChange={this.updateFullDate}
/> />{' '}
{' '}
Switch type Switch type
</label> </label>
</p> </p>

View File

@ -134,9 +134,9 @@ export default class ErrorHandlingTestCases extends React.Component {
</TestCase.Steps> </TestCase.Steps>
<TestCase.ExpectedResult> <TestCase.ExpectedResult>
The "Trigger error" button should be replaced with "Captured an The "Trigger error" button should be replaced with "Captured an
error: A cross-origin error was thrown [...]". The actual error message should error: A cross-origin error was thrown [...]". The actual error
be logged to the console: "Uncaught Error: Expected true to message should be logged to the console: "Uncaught Error: Expected
be false". true to be false".
</TestCase.ExpectedResult> </TestCase.ExpectedResult>
<Example <Example
buttonText="Trigger cross-origin error" buttonText="Trigger cross-origin error"
@ -154,7 +154,8 @@ export default class ErrorHandlingTestCases extends React.Component {
<li>Click the "Trigger render error and catch" button</li> <li>Click the "Trigger render error and catch" button</li>
</TestCase.Steps> </TestCase.Steps>
<TestCase.ExpectedResult> <TestCase.ExpectedResult>
Open the console. "Uncaught Error: Caught error" should have been logged by the browser. Open the console. "Uncaught Error: Caught error" should have been
logged by the browser.
</TestCase.ExpectedResult> </TestCase.ExpectedResult>
<TriggerErrorAndCatch /> <TriggerErrorAndCatch />
</TestCase> </TestCase>

View File

@ -35,12 +35,8 @@ class MouseMove extends React.Component {
<p> <p>
Was the event pooled?{' '} Was the event pooled?{' '}
<b> <b>
{events.length ? events.length <= 1 ? 'Yes' : 'No' : 'Unsure'} {events.length ? (events.length <= 1 ? 'Yes' : 'No') : 'Unsure'} (
{' '} {events.length} events)
(
{events.length}
{' '}
events)
</b> </b>
</p> </p>
</TestCase> </TestCase>

View File

@ -41,7 +41,8 @@ class Persistence extends React.Component {
</TestCase.Steps> </TestCase.Steps>
<TestCase.ExpectedResult> <TestCase.ExpectedResult>
The pool size should not increase above 1, but reduce to 0 when hovering over the persisted region. The pool size should not increase above 1, but reduce to 0 when
hovering over the persisted region.
</TestCase.ExpectedResult> </TestCase.ExpectedResult>
<h2>Add Pooled Event:</h2> <h2>Add Pooled Event:</h2>
@ -50,13 +51,9 @@ class Persistence extends React.Component {
<h2>Add Persisted Event:</h2> <h2>Add Persisted Event:</h2>
<HitBox onMouseMove={this.addPersisted} /> <HitBox onMouseMove={this.addPersisted} />
<p> <p>Pool size: {pooled.length}</p>
Pool size: {pooled.length}
</p>
<p> <p>Persisted size: {persisted}</p>
Persisted size: {persisted}
</p>
</TestCase> </TestCase>
); );
} }

View File

@ -41,14 +41,14 @@ class InputPlaceholderFixture extends React.Component {
type="text" type="text"
placeholder={placeholder} placeholder={placeholder}
onChange={this.handleChange} onChange={this.handleChange}
/> />{' '}
{' '}
<button onClick={this.handleGeneratePlaceholder}> <button onClick={this.handleGeneratePlaceholder}>
Change placeholder Change placeholder
</button> </button>
<p style={{color}}> <p style={{color}}>
<code>onChange</code>{' calls: '}<strong>{changeCount}</strong> <code>onChange</code>
{' calls: '}
<strong>{changeCount}</strong>
</p> </p>
<button onClick={this.handleReset}>Reset count</button> <button onClick={this.handleReset}>Reset count</button>
</Fixture> </Fixture>

View File

@ -34,10 +34,11 @@ class RadioClickFixture extends React.Component {
<label> <label>
<input defaultChecked type="radio" onChange={this.handleChange} /> <input defaultChecked type="radio" onChange={this.handleChange} />
Test case radio input Test case radio input
</label> </label>{' '}
{' '}
<p style={{color}}> <p style={{color}}>
<code>onChange</code>{' calls: '}<strong>{changeCount}</strong> <code>onChange</code>
{' calls: '}
<strong>{changeCount}</strong>
</p> </p>
<button onClick={this.handleReset}>Reset count</button> <button onClick={this.handleReset}>Reset count</button>
</Fixture> </Fixture>

View File

@ -43,11 +43,11 @@ class RadioGroupFixture extends React.Component {
<label> <label>
<input name="foo" type="radio" onChange={this.handleChange} /> <input name="foo" type="radio" onChange={this.handleChange} />
Radio 2 Radio 2
</label> </label>{' '}
{' '}
<p style={{color}}> <p style={{color}}>
<code>onChange</code>{' calls: '}<strong>{changeCount}</strong> <code>onChange</code>
{' calls: '}
<strong>{changeCount}</strong>
</p> </p>
<button onClick={this.handleReset}>Reset count</button> <button onClick={this.handleReset}>Reset count</button>
</Fixture> </Fixture>

View File

@ -60,16 +60,16 @@ class RangeKeyboardFixture extends React.Component {
ref={r => (this.input = r)} ref={r => (this.input = r)}
onChange={this.handleChange} onChange={this.handleChange}
/> />
<button onClick={() => this.input.focus()}> <button onClick={() => this.input.focus()}>Focus Knob</button>
Focus Knob </div>{' '}
</button>
</div>
{' '}
<p style={{color}}> <p style={{color}}>
<code>onKeyDown</code>{' calls: '}<strong>{keydownCount}</strong> <code>onKeyDown</code>
{' calls: '}
<strong>{keydownCount}</strong>
{' vs '} {' vs '}
<code>onChange</code>{' calls: '}<strong>{changeCount}</strong> <code>onChange</code>
{' calls: '}
<strong>{changeCount}</strong>
</p> </p>
<button onClick={this.handleReset}>Reset counts</button> <button onClick={this.handleReset}>Reset counts</button>
</Fixture> </Fixture>

View File

@ -24,8 +24,8 @@ class InputChangeEvents extends React.Component {
</TestCase.Steps> </TestCase.Steps>
<TestCase.ExpectedResult> <TestCase.ExpectedResult>
The <code>onKeyDown</code> call count should be equal to The <code>onKeyDown</code> call count should be equal to the{' '}
the <code>onChange</code> call count. <code>onChange</code> call count.
</TestCase.ExpectedResult> </TestCase.ExpectedResult>
<RangeKeyboardFixture /> <RangeKeyboardFixture />

View File

@ -24,7 +24,8 @@ class NumberTestCase extends React.Component {
onChange={this.onChange} onChange={this.onChange}
/> />
<span className="hint"> <span className="hint">
{' '}Value: {JSON.stringify(this.state.value)} {' '}
Value: {JSON.stringify(this.state.value)}
</span> </span>
</fieldset> </fieldset>

View File

@ -27,9 +27,9 @@ function NumberInputs() {
<NumberTestCase /> <NumberTestCase />
<p className="footnote"> <p className="footnote">
<b>Notes:</b> Chrome and Safari clear trailing <b>Notes:</b> Chrome and Safari clear trailing decimals on blur. React
decimals on blur. React makes this concession so that the makes this concession so that the value attribute remains in sync with
value attribute remains in sync with the value property. the value property.
</p> </p>
</TestCase> </TestCase>
@ -177,14 +177,13 @@ function NumberInputs() {
<NumberInputExtraZeroes /> <NumberInputExtraZeroes />
<p className="footnote"> <p className="footnote">
<b>Notes:</b> Firefox drops extraneous zeroes when <b>Notes:</b> Firefox drops extraneous zeroes when assigned. Zeroes
assigned. Zeroes are preserved when editing, however are preserved when editing, however directly assigning a new value
directly assigning a new value will drop zeroes. This will drop zeroes. This{' '}
{' '}
<a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1003896"> <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1003896">
is is a bug in Firefox
a bug in Firefox </a>{' '}
</a> that we can not control for. that we can not control for.
</p> </p>
</TestCase> </TestCase>
</FixtureSet> </FixtureSet>

View File

@ -21,7 +21,8 @@ class PasswordTestCase extends React.Component {
onChange={this.onChange} onChange={this.onChange}
/> />
<span className="hint"> <span className="hint">
{' '}Value: {JSON.stringify(this.state.value)} {' '}
Value: {JSON.stringify(this.state.value)}
</span> </span>
</fieldset> </fieldset>

View File

@ -84,13 +84,15 @@ class SelectFixture extends React.Component {
</TestCase.Steps> </TestCase.Steps>
<TestCase.ExpectedResult> <TestCase.ExpectedResult>
The initial picked option should be "Please select an The initial picked option should be "Please select an item", however
item", however it should not be a selectable option. it should not be a selectable option.
</TestCase.ExpectedResult> </TestCase.ExpectedResult>
<div className="test-fixture"> <div className="test-fixture">
<select defaultValue=""> <select defaultValue="">
<option value="" disabled>Please select an item</option> <option value="" disabled>
Please select an item
</option>
<option>0</option> <option>0</option>
<option>1</option> <option>1</option>
<option>2</option> <option>2</option>
@ -100,7 +102,8 @@ class SelectFixture extends React.Component {
<TestCase title="An unselected disabled option" relatedIssues="2803"> <TestCase title="An unselected disabled option" relatedIssues="2803">
<TestCase.ExpectedResult> <TestCase.ExpectedResult>
The initial picked option value should "0": the first non-disabled option. The initial picked option value should "0": the first non-disabled
option.
</TestCase.ExpectedResult> </TestCase.ExpectedResult>
<div className="test-fixture"> <div className="test-fixture">

View File

@ -43,9 +43,7 @@ class InputTestCase extends React.Component {
<fieldset> <fieldset>
<legend>Controlled {type}</legend> <legend>Controlled {type}</legend>
<input type={type} value={value} onChange={this.onChange} /> <input type={type} value={value} onChange={this.onChange} />
<p className="hint"> <p className="hint">Value: {JSON.stringify(this.state.value)}</p>
Value: {JSON.stringify(this.state.value)}
</p>
</fieldset> </fieldset>
<fieldset> <fieldset>

View File

@ -36,9 +36,9 @@ class TextInputFixtures extends React.Component {
</Fixture> </Fixture>
<p className="footnote"> <p className="footnote">
This issue was first introduced when we added extra logic This issue was first introduced when we added extra logic to number
to number inputs to prevent unexpected behavior in Chrome inputs to prevent unexpected behavior in Chrome and Safari (see the
and Safari (see the number input test case). number input test case).
</p> </p>
</TestCase> </TestCase>

View File

@ -27,9 +27,7 @@ export default class TextAreaFixtures extends React.Component {
</form> </form>
<div className="container"> <div className="container">
<h4>Controlled Output:</h4> <h4>Controlled Output:</h4>
<div className="output"> <div className="output">{this.state.value}</div>
{this.state.value}
</div>
</div> </div>
</div> </div>
</TestCase> </TestCase>

View File

@ -1,11 +1,13 @@
import './polyfills'; import './polyfills';
import loadReact from './react-loader'; import loadReact from './react-loader';
loadReact().then(() => import('./components/App')).then(App => { loadReact()
const {React, ReactDOM} = window; .then(() => import('./components/App'))
.then(App => {
const {React, ReactDOM} = window;
ReactDOM.render( ReactDOM.render(
React.createElement(App.default), React.createElement(App.default),
document.getElementById('root') document.getElementById('root')
); );
}); });

View File

@ -38,7 +38,7 @@ try {
* Attempts to load tags from sessionStorage. In cases where * Attempts to load tags from sessionStorage. In cases where
* sessionStorage is not available (Safari private browsing) or the * sessionStorage is not available (Safari private browsing) or the
* tags are cached a fetch request is made to the GitHub API. * tags are cached a fetch request is made to the GitHub API.
* *
* Returns a promise so that the consuming module can always assume * Returns a promise so that the consuming module can always assume
* the request is async, even if its loaded from sessionStorage. * the request is async, even if its loaded from sessionStorage.
*/ */

View File

@ -160,14 +160,15 @@ class App extends Component {
return ( return (
<div style={{height: '100%'}}> <div style={{height: '100%'}}>
{fibers && {fibers && (
<Draggable> <Draggable>
<Fibers <Fibers
fibers={fibers} fibers={fibers}
show={this.state.show} show={this.state.show}
graphSettings={this.state.graphSettings} graphSettings={this.state.graphSettings}
/> />
</Draggable>} </Draggable>
)}
<div <div
style={{ style={{
width: '100%', width: '100%',
@ -187,17 +188,12 @@ class App extends Component {
max={history.length - 1} max={history.length - 1}
value={currentStep} value={currentStep}
onChange={e => onChange={e =>
this.setState({currentStep: Number(e.target.value)})} this.setState({currentStep: Number(e.target.value)})
}
/> />
<p> <p>
Step Step {currentStep}
{' '} : {friendlyAction} (
{currentStep}
:
{' '}
{friendlyAction}
{' '}
(
<a style={{color: 'gray'}} onClick={this.handleEdit} href="#"> <a style={{color: 'gray'}} onClick={this.handleEdit} href="#">
Edit Edit
</a> </a>

View File

@ -83,7 +83,8 @@ function Graph(props) {
y: interpolatingStyle.y + props.dy, y: interpolatingStyle.y + props.dy,
vanillaX: node.x, vanillaX: node.x,
vanillaY: node.y, vanillaY: node.y,
})} })
}
</Motion> </Motion>
); );
}); });
@ -227,7 +228,8 @@ function Edge(props) {
/> />
<text> <text>
<textPath xlinkHref={`#${lineID}`}> <textPath xlinkHref={`#${lineID}`}>
{'     '}{props.children} {'     '}
{props.children}
</textPath> </textPath>
</text> </text>
</svg> </svg>
@ -258,9 +260,8 @@ export default function Fibers({fibers, show, graphSettings, ...rest}) {
); );
const isDragging = rest.className.indexOf('dragging') > -1; const isDragging = rest.className.indexOf('dragging') > -1;
const [_, sdx, sdy] = rest.style.transform.match( const [_, sdx, sdy] =
/translate\((-?\d+)px,(-?\d+)px\)/ rest.style.transform.match(/translate\((-?\d+)px,(-?\d+)px\)/) || [];
) || [];
const dx = Number(sdx); const dx = Number(sdx);
const dy = Number(sdy); const dy = Number(sdy);
@ -298,29 +299,31 @@ export default function Fibers({fibers, show, graphSettings, ...rest}) {
/*prettyFormat(fiber, { plugins: [reactElement ]})*/ /*prettyFormat(fiber, { plugins: [reactElement ]})*/
'todo: this was hanging last time I tried to pretty print' 'todo: this was hanging last time I tried to pretty print'
}> }>
<small>{fiber.tag} #{fiber.id}</small> <small>
{fiber.tag} #{fiber.id}
</small>
<br /> <br />
{fiber.type} {fiber.type}
<br /> <br />
{fibers.currentIDs.indexOf(fiber.id) === -1 {fibers.currentIDs.indexOf(fiber.id) === -1 ? (
? <small> <small>
{fiber.pendingWorkPriority !== 0 && [ {fiber.pendingWorkPriority !== 0 && [
<span key="span"> <span key="span">
Needs: {formatPriority(fiber.pendingWorkPriority)} Needs: {formatPriority(fiber.pendingWorkPriority)}
</span>, </span>,
<br key="br" />, <br key="br" />,
]} ]}
{fiber.memoizedProps !== null && {fiber.memoizedProps !== null &&
fiber.pendingProps !== null && [ fiber.pendingProps !== null && [
fiber.memoizedProps === fiber.pendingProps fiber.memoizedProps === fiber.pendingProps
? 'Can reuse memoized.' ? 'Can reuse memoized.'
: 'Cannot reuse memoized.', : 'Cannot reuse memoized.',
<br key="br" />, <br key="br" />,
]} ]}
</small> </small>
: <small> ) : (
Committed <small>Committed</small>
</small>} )}
{fiber.effectTag && [ {fiber.effectTag && [
<br key="br" />, <br key="br" />,
<small key="small">Effect: {fiber.effectTag}</small>, <small key="small">Effect: {fiber.effectTag}</small>,
@ -328,75 +331,82 @@ export default function Fibers({fibers, show, graphSettings, ...rest}) {
</div> </div>
</Vertex>, </Vertex>,
fiber.child && fiber.child &&
show.child && show.child && (
<Edge <Edge
source={fiber.id} source={fiber.id}
target={fiber.child} target={fiber.child}
kind="child" kind="child"
weight={1000} weight={1000}
key={`${fiber.id}-${fiber.child}-child`}> key={`${fiber.id}-${fiber.child}-child`}>
child child
</Edge>, </Edge>
),
fiber.sibling && fiber.sibling &&
show.sibling && show.sibling && (
<Edge <Edge
source={fiber.id} source={fiber.id}
target={fiber.sibling} target={fiber.sibling}
kind="sibling" kind="sibling"
weight={2000} weight={2000}
key={`${fiber.id}-${fiber.sibling}-sibling`}> key={`${fiber.id}-${fiber.sibling}-sibling`}>
sibling sibling
</Edge>, </Edge>
),
fiber.return && fiber.return &&
show.return && show.return && (
<Edge <Edge
source={fiber.id} source={fiber.id}
target={fiber.return} target={fiber.return}
kind="return" kind="return"
weight={1000} weight={1000}
key={`${fiber.id}-${fiber.return}-return`}> key={`${fiber.id}-${fiber.return}-return`}>
return return
</Edge>, </Edge>
),
fiber.nextEffect && fiber.nextEffect &&
show.fx && show.fx && (
<Edge <Edge
source={fiber.id} source={fiber.id}
target={fiber.nextEffect} target={fiber.nextEffect}
kind="fx" kind="fx"
weight={100} weight={100}
key={`${fiber.id}-${fiber.nextEffect}-nextEffect`}> key={`${fiber.id}-${fiber.nextEffect}-nextEffect`}>
nextFx nextFx
</Edge>, </Edge>
),
fiber.firstEffect && fiber.firstEffect &&
show.fx && show.fx && (
<Edge <Edge
source={fiber.id} source={fiber.id}
target={fiber.firstEffect} target={fiber.firstEffect}
kind="fx" kind="fx"
weight={100} weight={100}
key={`${fiber.id}-${fiber.firstEffect}-firstEffect`}> key={`${fiber.id}-${fiber.firstEffect}-firstEffect`}>
firstFx firstFx
</Edge>, </Edge>
),
fiber.lastEffect && fiber.lastEffect &&
show.fx && show.fx && (
<Edge <Edge
source={fiber.id} source={fiber.id}
target={fiber.lastEffect} target={fiber.lastEffect}
kind="fx" kind="fx"
weight={100} weight={100}
key={`${fiber.id}-${fiber.lastEffect}-lastEffect`}> key={`${fiber.id}-${fiber.lastEffect}-lastEffect`}>
lastFx lastFx
</Edge>, </Edge>
),
fiber.alternate && fiber.alternate &&
show.alt && show.alt && (
<Edge <Edge
source={fiber.id} source={fiber.id}
target={fiber.alternate} target={fiber.alternate}
kind="alt" kind="alt"
weight={10} weight={10}
key={`${fiber.id}-${fiber.alternate}-alt`}> key={`${fiber.id}-${fiber.alternate}-alt`}>
alt alt
</Edge>, </Edge>
),
])} ])}
</Graph> </Graph>
</div> </div>

View File

@ -297,7 +297,10 @@ Noop.render(
<div>Hello</div> <div>Hello</div>
<Children> <Children>
Hello world Hello world
<span>{'Number '}{42}</span> <span>
{'Number '}
{42}
</span>
<Test active={true} ref={t => (instance = t)} /> <Test active={true} ref={t => (instance = t)} />
</Children> </Children>
</main> </main>
@ -324,7 +327,7 @@ const expected1 = [
assert.deepEqual( assert.deepEqual(
actual1, actual1,
expected1, expected1,
'Error. Noop.getChildren() returned unexpected value.\nExpected:\ ' + 'Error. Noop.getChildren() returned unexpected value.\nExpected: ' +
JSON.stringify(expected1, null, 2) + JSON.stringify(expected1, null, 2) +
'\n\nActual:\n ' + '\n\nActual:\n ' +
JSON.stringify(actual1, null, 2) JSON.stringify(actual1, null, 2)
@ -357,7 +360,7 @@ const expected2 = [
assert.deepEqual( assert.deepEqual(
actual2, actual2,
expected2, expected2,
'Error. Noop.getChildren() returned unexpected value.\nExpected:\ ' + 'Error. Noop.getChildren() returned unexpected value.\nExpected: ' +
JSON.stringify(expected2, null, 2) + JSON.stringify(expected2, null, 2) +
'\n\nActual:\n ' + '\n\nActual:\n ' +
JSON.stringify(actual2, null, 2) JSON.stringify(actual2, null, 2)

View File

@ -20,19 +20,10 @@ export default class Page extends Component {
); );
return ( return (
<div> <div>
<p suppressHydrationWarning={true}> <p suppressHydrationWarning={true}>A random number: {Math.random()}</p>
A random number: {Math.random()} <p>Autofocus on page load: {autofocusedInputs}</p>
</p> <p>{!this.state.active ? link : 'Thanks!'}</p>
<p> {this.state.active && <p>Autofocus on update: {autofocusedInputs}</p>}
Autofocus on page load: {autofocusedInputs}
</p>
<p>
{!this.state.active ? link : 'Thanks!'}
</p>
{this.state.active &&
<p>
Autofocus on update: {autofocusedInputs}
</p>}
</div> </div>
); );
} }

View File

@ -73,7 +73,7 @@
"ncp": "^2.0.0", "ncp": "^2.0.0",
"object-assign": "^4.1.1", "object-assign": "^4.1.1",
"platform": "^1.1.0", "platform": "^1.1.0",
"prettier": "1.2.2", "prettier": "1.8.1",
"prop-types": "^15.6.0", "prop-types": "^15.6.0",
"rimraf": "^2.6.1", "rimraf": "^2.6.1",
"rollup": "^0.49.3", "rollup": "^0.49.3",

View File

@ -321,10 +321,10 @@ function setResponderAndExtractTransfer(
var shouldSetEventType = isStartish(topLevelType) var shouldSetEventType = isStartish(topLevelType)
? eventTypes.startShouldSetResponder ? eventTypes.startShouldSetResponder
: isMoveish(topLevelType) : isMoveish(topLevelType)
? eventTypes.moveShouldSetResponder ? eventTypes.moveShouldSetResponder
: topLevelType === 'topSelectionChange' : topLevelType === 'topSelectionChange'
? eventTypes.selectionChangeShouldSetResponder ? eventTypes.selectionChangeShouldSetResponder
: eventTypes.scrollShouldSetResponder; : eventTypes.scrollShouldSetResponder;
// TODO: stop one short of the current responder. // TODO: stop one short of the current responder.
var bubbleShouldSetFrom = !responderInst var bubbleShouldSetFrom = !responderInst
@ -518,8 +518,8 @@ var ResponderEventPlugin = {
var incrementalTouch = isResponderTouchStart var incrementalTouch = isResponderTouchStart
? eventTypes.responderStart ? eventTypes.responderStart
: isResponderTouchMove : isResponderTouchMove
? eventTypes.responderMove ? eventTypes.responderMove
: isResponderTouchEnd ? eventTypes.responderEnd : null; : isResponderTouchEnd ? eventTypes.responderEnd : null;
if (incrementalTouch) { if (incrementalTouch) {
var gesture = ResponderSyntheticEvent.getPooled( var gesture = ResponderSyntheticEvent.getPooled(

View File

@ -99,9 +99,10 @@ function SyntheticEvent(
} }
} }
var defaultPrevented = nativeEvent.defaultPrevented != null var defaultPrevented =
? nativeEvent.defaultPrevented nativeEvent.defaultPrevented != null
: nativeEvent.returnValue === false; ? nativeEvent.defaultPrevented
: nativeEvent.returnValue === false;
if (defaultPrevented) { if (defaultPrevented) {
this.isDefaultPrevented = emptyFunction.thatReturnsTrue; this.isDefaultPrevented = emptyFunction.thatReturnsTrue;
} else { } else {
@ -227,9 +228,9 @@ SyntheticEvent.augmentClass = function(Class, Interface) {
}; };
/** Proxying after everything set on SyntheticEvent /** Proxying after everything set on SyntheticEvent
* to resolve Proxy issue on some WebKit browsers * to resolve Proxy issue on some WebKit browsers
* in which some Event properties are set to undefined (GH#10010) * in which some Event properties are set to undefined (GH#10010)
*/ */
if (__DEV__) { if (__DEV__) {
if (isProxySupported) { if (isProxySupported) {
/*eslint-disable no-func-assign */ /*eslint-disable no-func-assign */
@ -267,12 +268,12 @@ if (__DEV__) {
addEventPoolingTo(SyntheticEvent); addEventPoolingTo(SyntheticEvent);
/** /**
* Helper to nullify syntheticEvent instance properties when destructing * Helper to nullify syntheticEvent instance properties when destructing
* *
* @param {String} propName * @param {String} propName
* @param {?object} getVal * @param {?object} getVal
* @return {object} defineProperty object * @return {object} defineProperty object
*/ */
function getPooledWarningPropertyDefinition(propName, getVal) { function getPooledWarningPropertyDefinition(propName, getVal) {
var isFunction = typeof getVal === 'function'; var isFunction = typeof getVal === 'function';
return { return {

View File

@ -32,22 +32,24 @@ var TouchHistoryMath = {
var total = 0; var total = 0;
var count = 0; var count = 0;
var oneTouchData = touchHistory.numberActiveTouches === 1 var oneTouchData =
? touchHistory.touchBank[touchHistory.indexOfSingleActiveTouch] touchHistory.numberActiveTouches === 1
: null; ? touchHistory.touchBank[touchHistory.indexOfSingleActiveTouch]
: null;
if (oneTouchData !== null) { if (oneTouchData !== null) {
if ( if (
oneTouchData.touchActive && oneTouchData.touchActive &&
oneTouchData.currentTimeStamp > touchesChangedAfter oneTouchData.currentTimeStamp > touchesChangedAfter
) { ) {
total += ofCurrent && isXAxis total +=
? oneTouchData.currentPageX ofCurrent && isXAxis
: ofCurrent && !isXAxis ? oneTouchData.currentPageX
: ofCurrent && !isXAxis
? oneTouchData.currentPageY ? oneTouchData.currentPageY
: !ofCurrent && isXAxis : !ofCurrent && isXAxis
? oneTouchData.previousPageX ? oneTouchData.previousPageX
: oneTouchData.previousPageY; : oneTouchData.previousPageY;
count = 1; count = 1;
} }
} else { } else {

View File

@ -61,7 +61,7 @@ var Wedge = createReactClass({
// 360, 720, etc. // 360, 720, etc.
return this.circleRadians; return this.circleRadians;
} else { } else {
return degrees * this.radiansPerDegree % this.circleRadians; return (degrees * this.radiansPerDegree) % this.circleRadians;
} }
}, },
@ -77,7 +77,10 @@ var Wedge = createReactClass({
_createCirclePath: function _createCirclePath(or, ir) { _createCirclePath: function _createCirclePath(or, ir) {
var path = Path(); var path = Path();
path.move(0, or).arc(or * 2, 0, or).arc(-or * 2, 0, or); path
.move(0, or)
.arc(or * 2, 0, or)
.arc(-or * 2, 0, or);
if (ir) { if (ir) {
path path

View File

@ -74,7 +74,13 @@ describe('ReactCallReturn', () => {
} }
function App() { function App() {
return <div><Parent foo={true}><Indirection /></Parent></div>; return (
<div>
<Parent foo={true}>
<Indirection />
</Parent>
</div>
);
} }
ReactNoop.render(<App />); ReactNoop.render(<App />);
@ -130,7 +136,13 @@ describe('ReactCallReturn', () => {
} }
function App(props) { function App(props) {
return <div><Parent foo={props.foo}><Indirection /></Parent></div>; return (
<div>
<Parent foo={props.foo}>
<Indirection />
</Parent>
</div>
);
} }
ReactNoop.render(<App foo={true} />); ReactNoop.render(<App foo={true} />);
@ -190,7 +202,11 @@ describe('ReactCallReturn', () => {
} }
} }
ReactNoop.render(<Parent><Child /></Parent>); ReactNoop.render(
<Parent>
<Child />
</Parent>,
);
ReactNoop.flush(); ReactNoop.flush();
expect(ops).toEqual(['Parent', 'Child', 'HandleReturns', 'Continuation']); expect(ops).toEqual(['Parent', 'Child', 'HandleReturns', 'Continuation']);

View File

@ -30,6 +30,6 @@ export function addUserTimingListener() {
// Flow magic to verify the exports of this file match the original version. // Flow magic to verify the exports of this file match the original version.
// eslint-disable-next-line no-unused-vars // eslint-disable-next-line no-unused-vars
type Check<_X, Y: _X, X: Y=_X> = null; type Check<_X, Y: _X, X: Y = _X> = null;
// eslint-disable-next-line no-unused-expressions // eslint-disable-next-line no-unused-expressions
(null: Check<CSFeatureFlagsType, FeatureFlagsType>); (null: Check<CSFeatureFlagsType, FeatureFlagsType>);

View File

@ -104,7 +104,11 @@ describe('ReactComponent', () => {
class Component extends React.Component { class Component extends React.Component {
render() { render() {
var inner = <Wrapper object={innerObj} ref="inner" />; var inner = <Wrapper object={innerObj} ref="inner" />;
var outer = <Wrapper object={outerObj} ref="outer">{inner}</Wrapper>; var outer = (
<Wrapper object={outerObj} ref="outer">
{inner}
</Wrapper>
);
return outer; return outer;
} }
@ -120,7 +124,11 @@ describe('ReactComponent', () => {
it('should not have refs on unmounted components', () => { it('should not have refs on unmounted components', () => {
class Parent extends React.Component { class Parent extends React.Component {
render() { render() {
return <Child><div ref="test" /></Child>; return (
<Child>
<div ref="test" />
</Child>
);
} }
componentDidMount() { componentDidMount() {
@ -357,7 +365,11 @@ describe('ReactComponent', () => {
} }
function Bar() { function Bar() {
return <Indirection><X /></Indirection>; return (
<Indirection>
<X />
</Indirection>
);
} }
function Foo() { function Foo() {
@ -513,7 +525,11 @@ describe('ReactComponent', () => {
it('warns on function as a child to host component', () => { it('warns on function as a child to host component', () => {
function Foo() { function Foo() {
return <div><span>{Foo}</span></div>; return (
<div>
<span>{Foo}</span>
</div>
);
} }
spyOn(console, 'error'); spyOn(console, 'error');
var container = document.createElement('div'); var container = document.createElement('div');
@ -553,8 +569,12 @@ describe('ReactComponent', () => {
render() { render() {
return ( return (
<div> <div>
{Foo}{Foo} {Foo}
<span>{Foo}{Foo}</span> {Foo}
<span>
{Foo}
{Foo}
</span>
</div> </div>
); );
} }

View File

@ -373,11 +373,7 @@ describe('ReactComponentLifeCycle', () => {
} }
// you would *NEVER* do anything like this in real code! // you would *NEVER* do anything like this in real code!
this.state.hasRenderCompleted = true; this.state.hasRenderCompleted = true;
return ( return <div ref="theDiv">I am the inner DIV</div>;
<div ref="theDiv">
I am the inner DIV
</div>
);
} }
componentWillUnmount() { componentWillUnmount() {
@ -536,7 +532,11 @@ describe('ReactComponentLifeCycle', () => {
componentDidUpdate = logger('outer componentDidUpdate'); componentDidUpdate = logger('outer componentDidUpdate');
componentWillUnmount = logger('outer componentWillUnmount'); componentWillUnmount = logger('outer componentWillUnmount');
render() { render() {
return <div><Inner x={this.props.x} /></div>; return (
<div>
<Inner x={this.props.x} />
</div>
);
} }
} }

View File

@ -48,9 +48,11 @@ describe('ReactCompositeComponent', () => {
render() { render() {
var toggleActivatedState = this._toggleActivatedState; var toggleActivatedState = this._toggleActivatedState;
return !this.state.activated return !this.state.activated ? (
? <a ref="x" onClick={toggleActivatedState} /> <a ref="x" onClick={toggleActivatedState} />
: <b ref="x" onClick={toggleActivatedState} />; ) : (
<b ref="x" onClick={toggleActivatedState} />
);
} }
}; };
@ -65,9 +67,11 @@ describe('ReactCompositeComponent', () => {
render() { render() {
var className = this.props.anchorClassOn ? 'anchorClass' : ''; var className = this.props.anchorClassOn ? 'anchorClass' : '';
return this.props.renderAnchor return this.props.renderAnchor ? (
? <a ref="anch" className={className} /> <a ref="anch" className={className} />
: <b />; ) : (
<b />
);
} }
}; };
}); });
@ -110,7 +114,11 @@ describe('ReactCompositeComponent', () => {
class Parent extends React.Component { class Parent extends React.Component {
render() { render() {
return <div><Child /></div>; return (
<div>
<Child />
</div>
);
} }
} }
@ -582,7 +590,11 @@ describe('ReactCompositeComponent', () => {
it('should pass context to children when not owner', () => { it('should pass context to children when not owner', () => {
class Parent extends React.Component { class Parent extends React.Component {
render() { render() {
return <Child><Grandchild /></Child>; return (
<Child>
<Grandchild />
</Child>
);
} }
} }
@ -685,7 +697,11 @@ describe('ReactCompositeComponent', () => {
} }
parentInstance = ReactTestUtils.renderIntoDocument( parentInstance = ReactTestUtils.renderIntoDocument(
<Parent><Middle><Child /></Middle></Parent>, <Parent>
<Middle>
<Child />
</Middle>
</Parent>,
); );
expect(parentInstance.state.flag).toBe(false); expect(parentInstance.state.flag).toBe(false);
@ -1139,15 +1155,23 @@ describe('ReactCompositeComponent', () => {
if (this.props.flipped) { if (this.props.flipped) {
return ( return (
<div> <div>
<Static ref="static0" key="B">B (ignored)</Static> <Static ref="static0" key="B">
<Static ref="static1" key="A">A (ignored)</Static> B (ignored)
</Static>
<Static ref="static1" key="A">
A (ignored)
</Static>
</div> </div>
); );
} else { } else {
return ( return (
<div> <div>
<Static ref="static0" key="A">A</Static> <Static ref="static0" key="A">
<Static ref="static1" key="B">B</Static> A
</Static>
<Static ref="static1" key="B">
B
</Static>
</div> </div>
); );
} }
@ -1221,7 +1245,12 @@ describe('ReactCompositeComponent', () => {
} }
var div = document.createElement('div'); var div = document.createElement('div');
ReactDOM.render(<Parent><Component /></Parent>, div); ReactDOM.render(
<Parent>
<Component />
</Parent>,
div,
);
}); });
it('should replace state', () => { it('should replace state', () => {
@ -1314,7 +1343,12 @@ describe('ReactCompositeComponent', () => {
} }
} }
ReactDOM.render(<Outer><Component /></Outer>, container); ReactDOM.render(
<Outer>
<Component />
</Outer>,
container,
);
ReactDOM.render(<Outer />, container); ReactDOM.render(<Outer />, container);
}); });

View File

@ -33,21 +33,13 @@ describe('ReactCompositeComponentDOMMinimalism', () => {
LowerLevelComposite = class extends React.Component { LowerLevelComposite = class extends React.Component {
render() { render() {
return ( return <div>{this.props.children}</div>;
<div>
{this.props.children}
</div>
);
} }
}; };
MyCompositeComponent = class extends React.Component { MyCompositeComponent = class extends React.Component {
render() { render() {
return ( return <LowerLevelComposite>{this.props.children}</LowerLevelComposite>;
<LowerLevelComposite>
{this.props.children}
</LowerLevelComposite>
);
} }
}; };
@ -58,11 +50,15 @@ describe('ReactCompositeComponentDOMMinimalism', () => {
}; };
}); });
it('should not render extra nodes for non-interpolated text', () => {
var instance = <MyCompositeComponent>A string child</MyCompositeComponent>;
instance = ReactTestUtils.renderIntoDocument(instance);
expectSingleChildlessDiv(instance);
});
it('should not render extra nodes for non-interpolated text', () => { it('should not render extra nodes for non-interpolated text', () => {
var instance = ( var instance = (
<MyCompositeComponent> <MyCompositeComponent>{'Interpolated String Child'}</MyCompositeComponent>
A string child
</MyCompositeComponent>
); );
instance = ReactTestUtils.renderIntoDocument(instance); instance = ReactTestUtils.renderIntoDocument(instance);
expectSingleChildlessDiv(instance); expectSingleChildlessDiv(instance);
@ -71,19 +67,7 @@ describe('ReactCompositeComponentDOMMinimalism', () => {
it('should not render extra nodes for non-interpolated text', () => { it('should not render extra nodes for non-interpolated text', () => {
var instance = ( var instance = (
<MyCompositeComponent> <MyCompositeComponent>
{'Interpolated String Child'} <ul>This text causes no children in ul, just innerHTML</ul>
</MyCompositeComponent>
);
instance = ReactTestUtils.renderIntoDocument(instance);
expectSingleChildlessDiv(instance);
});
it('should not render extra nodes for non-interpolated text', () => {
var instance = (
<MyCompositeComponent>
<ul>
This text causes no children in ul, just innerHTML
</ul>
</MyCompositeComponent> </MyCompositeComponent>
); );
instance = ReactTestUtils.renderIntoDocument(instance); instance = ReactTestUtils.renderIntoDocument(instance);

View File

@ -390,7 +390,8 @@ describe('ReactCompositeComponent-state', () => {
this.setState({step: 2}, () => { this.setState({step: 2}, () => {
// Tests that earlier setState callbacks are not dropped // Tests that earlier setState callbacks are not dropped
ops.push( ops.push(
`callback -- step: ${this.state.step}, extra: ${!!this.state.extra}`, `callback -- step: ${this.state.step}, extra: ${!!this.state
.extra}`,
); );
}); });
// Treat like replaceState // Treat like replaceState
@ -437,7 +438,8 @@ describe('ReactCompositeComponent-state', () => {
this.setState({step: 2}, () => { this.setState({step: 2}, () => {
// Tests that earlier setState callbacks are not dropped // Tests that earlier setState callbacks are not dropped
ops.push( ops.push(
`callback -- step: ${this.state.step}, extra: ${!!this.state.extra}`, `callback -- step: ${this.state.step}, extra: ${!!this.state
.extra}`,
); );
}); });
// Treat like replaceState // Treat like replaceState

View File

@ -207,8 +207,9 @@ describe('ReactDOM', () => {
return ( return (
<div> <div>
<input id="one" ref={r => (input = input || r)} /> <input id="one" ref={r => (input = input || r)} />
{this.props.showTwo && {this.props.showTwo && (
<input id="two" ref={r => (input2 = input2 || r)} />} <input id="two" ref={r => (input2 = input2 || r)} />
)}
</div> </div>
); );
} }

View File

@ -580,22 +580,40 @@ describe('ReactDOMComponent', () => {
it('should transition from innerHTML to children in nested el', () => { it('should transition from innerHTML to children in nested el', () => {
var container = document.createElement('div'); var container = document.createElement('div');
ReactDOM.render( ReactDOM.render(
<div><div dangerouslySetInnerHTML={{__html: 'bonjour'}} /></div>, <div>
<div dangerouslySetInnerHTML={{__html: 'bonjour'}} />
</div>,
container, container,
); );
expect(container.textContent).toEqual('bonjour'); expect(container.textContent).toEqual('bonjour');
ReactDOM.render(<div><div><span>adieu</span></div></div>, container); ReactDOM.render(
<div>
<div>
<span>adieu</span>
</div>
</div>,
container,
);
expect(container.textContent).toEqual('adieu'); expect(container.textContent).toEqual('adieu');
}); });
it('should transition from children to innerHTML in nested el', () => { it('should transition from children to innerHTML in nested el', () => {
var container = document.createElement('div'); var container = document.createElement('div');
ReactDOM.render(<div><div><span>adieu</span></div></div>, container); ReactDOM.render(
<div>
<div>
<span>adieu</span>
</div>
</div>,
container,
);
expect(container.textContent).toEqual('adieu'); expect(container.textContent).toEqual('adieu');
ReactDOM.render( ReactDOM.render(
<div><div dangerouslySetInnerHTML={{__html: 'bonjour'}} /></div>, <div>
<div dangerouslySetInnerHTML={{__html: 'bonjour'}} />
</div>,
container, container,
); );
expect(container.textContent).toEqual('bonjour'); expect(container.textContent).toEqual('bonjour');
@ -744,10 +762,12 @@ describe('ReactDOMComponent', () => {
ReactDOM.render( ReactDOM.render(
<div> <div>
<div key="one"> <div key="one">
<div key="A">A</div><div key="B">B</div> <div key="A">A</div>
<div key="B">B</div>
</div> </div>
<div key="two"> <div key="two">
<div key="C">C</div><div key="D">D</div> <div key="C">C</div>
<div key="D">D</div>
</div> </div>
</div>, </div>,
container, container,
@ -756,10 +776,12 @@ describe('ReactDOMComponent', () => {
ReactDOM.render( ReactDOM.render(
<div> <div>
<div key="one"> <div key="one">
<div key="B">B</div><div key="A">A</div> <div key="B">B</div>
<div key="A">A</div>
</div> </div>
<div key="two"> <div key="two">
<div key="D">D</div><div key="C">C</div> <div key="D">D</div>
<div key="C">C</div>
</div> </div>
</div>, </div>,
container, container,
@ -1050,13 +1072,20 @@ describe('ReactDOMComponent', () => {
var container = document.createElement('div'); var container = document.createElement('div');
var returnedValue = ReactDOMServer.renderToString( var returnedValue = ReactDOMServer.renderToString(
<menu><menuitem /></menu>, <menu>
<menuitem />
</menu>,
); );
expect(returnedValue).toContain('</menuitem>'); expect(returnedValue).toContain('</menuitem>');
expect(function() { expect(function() {
ReactDOM.render(<menu><menuitem>children</menuitem></menu>, container); ReactDOM.render(
<menu>
<menuitem>children</menuitem>
</menu>,
container,
);
}).toThrowError( }).toThrowError(
'menuitem is a void element tag and must neither have `children` nor use ' + 'menuitem is a void element tag and must neither have `children` nor use ' +
'`dangerouslySetInnerHTML`.', '`dangerouslySetInnerHTML`.',
@ -1275,7 +1304,12 @@ describe('ReactDOMComponent', () => {
it('should warn about contentEditable and children', () => { it('should warn about contentEditable and children', () => {
spyOn(console, 'error'); spyOn(console, 'error');
ReactDOM.render(<div contentEditable={true}><div /></div>, container); ReactDOM.render(
<div contentEditable={true}>
<div />
</div>,
container,
);
expectDev(console.error.calls.count()).toBe(1); expectDev(console.error.calls.count()).toBe(1);
expectDev(console.error.calls.argsFor(0)[0]).toContain('contentEditable'); expectDev(console.error.calls.argsFor(0)[0]).toContain('contentEditable');
}); });
@ -1352,7 +1386,12 @@ describe('ReactDOMComponent', () => {
} }
var container = document.createElement('div'); var container = document.createElement('div');
ReactDOM.render(<div><Inner /></div>, container); ReactDOM.render(
<div>
<Inner />
</div>,
container,
);
ReactDOM.unmountComponentAtNode(container); ReactDOM.unmountComponentAtNode(container);
}); });
}); });
@ -1386,21 +1425,37 @@ describe('ReactDOMComponent', () => {
describe('nesting validation', () => { describe('nesting validation', () => {
it('warns on invalid nesting', () => { it('warns on invalid nesting', () => {
spyOn(console, 'error'); spyOn(console, 'error');
ReactTestUtils.renderIntoDocument(<div><tr /><tr /></div>); ReactTestUtils.renderIntoDocument(
<div>
<tr />
<tr />
</div>,
);
expectDev(console.error.calls.count()).toBe(1); expectDev(console.error.calls.count()).toBe(2);
expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe( expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
'Warning: validateDOMNesting(...): <tr> cannot appear as a child of ' + 'Warning: validateDOMNesting(...): <tr> cannot appear as a child of ' +
'<div>.' + '<div>.' +
'\n in tr (at **)' + '\n in tr (at **)' +
'\n in div (at **)', '\n in div (at **)',
); );
expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(1)[0])).toBe(
'Warning: validateDOMNesting(...): <tr> cannot appear as a child of ' +
'<div>.' +
'\n in tr (at **)' +
'\n in div (at **)',
);
}); });
it('warns on invalid nesting at root', () => { it('warns on invalid nesting at root', () => {
spyOn(console, 'error'); spyOn(console, 'error');
var p = document.createElement('p'); var p = document.createElement('p');
ReactDOM.render(<span><p /></span>, p); ReactDOM.render(
<span>
<p />
</span>,
p,
);
expectDev(console.error.calls.count()).toBe(1); expectDev(console.error.calls.count()).toBe(1);
expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe( expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
@ -1423,7 +1478,11 @@ describe('ReactDOMComponent', () => {
class Foo extends React.Component { class Foo extends React.Component {
render() { render() {
return <table><Row /> </table>; return (
<table>
<Row />{' '}
</table>
);
} }
} }
@ -1480,7 +1539,11 @@ describe('ReactDOMComponent', () => {
} }
function Viz1() { function Viz1() {
return <table><FancyRow /></table>; return (
<table>
<FancyRow />
</table>
);
} }
function App1() { function App1() {
return <Viz1 />; return <Viz1 />;
@ -1498,7 +1561,11 @@ describe('ReactDOMComponent', () => {
); );
function Viz2() { function Viz2() {
return <FancyTable><FancyRow /></FancyTable>; return (
<FancyTable>
<FancyRow />
</FancyTable>
);
} }
function App2() { function App2() {
return <Viz2 />; return <Viz2 />;
@ -1517,7 +1584,11 @@ describe('ReactDOMComponent', () => {
'\n in Viz2 (at **)', '\n in Viz2 (at **)',
); );
ReactTestUtils.renderIntoDocument(<FancyTable><FancyRow /></FancyTable>); ReactTestUtils.renderIntoDocument(
<FancyTable>
<FancyRow />
</FancyTable>,
);
expectDev(console.error.calls.count()).toBe(3); expectDev(console.error.calls.count()).toBe(3);
expectDev( expectDev(
normalizeCodeLocInfo(console.error.calls.argsFor(2)[0]), normalizeCodeLocInfo(console.error.calls.argsFor(2)[0]),
@ -1530,7 +1601,11 @@ describe('ReactDOMComponent', () => {
'\n in FancyTable (at **)', '\n in FancyTable (at **)',
); );
ReactTestUtils.renderIntoDocument(<table><FancyRow /></table>); ReactTestUtils.renderIntoDocument(
<table>
<FancyRow />
</table>,
);
expectDev(console.error.calls.count()).toBe(4); expectDev(console.error.calls.count()).toBe(4);
expectDev( expectDev(
normalizeCodeLocInfo(console.error.calls.argsFor(3)[0]), normalizeCodeLocInfo(console.error.calls.argsFor(3)[0]),
@ -1541,7 +1616,11 @@ describe('ReactDOMComponent', () => {
'\n in table (at **)', '\n in table (at **)',
); );
ReactTestUtils.renderIntoDocument(<FancyTable><tr /></FancyTable>); ReactTestUtils.renderIntoDocument(
<FancyTable>
<tr />
</FancyTable>,
);
expectDev(console.error.calls.count()).toBe(5); expectDev(console.error.calls.count()).toBe(5);
expectDev( expectDev(
normalizeCodeLocInfo(console.error.calls.argsFor(4)[0]), normalizeCodeLocInfo(console.error.calls.argsFor(4)[0]),
@ -1558,7 +1637,13 @@ describe('ReactDOMComponent', () => {
} }
} }
ReactTestUtils.renderIntoDocument(<Link><div><Link /></div></Link>); ReactTestUtils.renderIntoDocument(
<Link>
<div>
<Link />
</div>
</Link>,
);
expectDev(console.error.calls.count()).toBe(6); expectDev(console.error.calls.count()).toBe(6);
expectDev( expectDev(
normalizeCodeLocInfo(console.error.calls.argsFor(5)[0]), normalizeCodeLocInfo(console.error.calls.argsFor(5)[0]),
@ -1771,8 +1856,8 @@ describe('ReactDOMComponent', () => {
var previousLine = (matches || [])[1]; var previousLine = (matches || [])[1];
expectDev(console.error.calls.argsFor(1)[0]).toContain('onClick'); expectDev(console.error.calls.argsFor(1)[0]).toContain('onClick');
matches = console.error.calls.argsFor(1)[0].match(/.*\(.*:(\d+)\).*/) || { matches =
}; console.error.calls.argsFor(1)[0].match(/.*\(.*:(\d+)\).*/) || {};
var currentLine = (matches || [])[1]; var currentLine = (matches || [])[1];
//verify line number has a proper relative difference, //verify line number has a proper relative difference,
@ -1786,7 +1871,14 @@ describe('ReactDOMComponent', () => {
class Parent extends React.Component { class Parent extends React.Component {
render() { render() {
return <div><Child1 /><Child2 /><Child3 /><Child4 /></div>; return (
<div>
<Child1 />
<Child2 />
<Child3 />
<Child4 />
</div>
);
} }
} }
@ -1837,7 +1929,14 @@ describe('ReactDOMComponent', () => {
class Parent extends React.Component { class Parent extends React.Component {
render() { render() {
return <div><Child1 /><Child2 /><Child3 /><Child4 /></div>; return (
<div>
<Child1 />
<Child2 />
<Child3 />
<Child4 />
</div>
);
} }
} }
@ -1980,7 +2079,9 @@ describe('ReactDOMComponent', () => {
spyOn(console, 'error'); spyOn(console, 'error');
var el = ReactTestUtils.renderIntoDocument( var el = ReactTestUtils.renderIntoDocument(
<svg><text arabic-form="initial" /></svg>, <svg>
<text arabic-form="initial" />
</svg>,
); );
var text = el.querySelector('text'); var text = el.querySelector('text');
@ -2264,7 +2365,9 @@ describe('ReactDOMComponent', () => {
it('the font-face element is not a custom element', function() { it('the font-face element is not a custom element', function() {
spyOn(console, 'error'); spyOn(console, 'error');
var el = ReactTestUtils.renderIntoDocument( var el = ReactTestUtils.renderIntoDocument(
<svg><font-face x-height={false} /></svg>, <svg>
<font-face x-height={false} />
</svg>,
); );
expect(el.querySelector('font-face').hasAttribute('x-height')).toBe( expect(el.querySelector('font-face').hasAttribute('x-height')).toBe(
@ -2280,7 +2383,9 @@ describe('ReactDOMComponent', () => {
it('the font-face element does not allow unknown boolean values', function() { it('the font-face element does not allow unknown boolean values', function() {
spyOn(console, 'error'); spyOn(console, 'error');
var el = ReactTestUtils.renderIntoDocument( var el = ReactTestUtils.renderIntoDocument(
<svg><font-face whatever={false} /></svg>, <svg>
<font-face whatever={false} />
</svg>,
); );
expect(el.querySelector('font-face').hasAttribute('whatever')).toBe( expect(el.querySelector('font-face').hasAttribute('whatever')).toBe(

View File

@ -85,7 +85,11 @@ describe('ReactDOMComponentTree', () => {
} }
function renderAndQuery(sel) { function renderAndQuery(sel) {
var root = renderMarkupIntoDocument(<section><Component /></section>); var root = renderMarkupIntoDocument(
<section>
<Component />
</section>,
);
return sel ? root.querySelector(sel) : root; return sel ? root.querySelector(sel) : root;
} }

View File

@ -193,7 +193,13 @@ describe('ReactDOMEventListener', () => {
render() { render() {
var inner = <div ref="inner">Inner</div>; var inner = <div ref="inner">Inner</div>;
return <div><div onMouseOut={onMouseOut} id="outer">{inner}</div></div>; return (
<div>
<div onMouseOut={onMouseOut} id="outer">
{inner}
</div>
</div>
);
} }
} }

View File

@ -133,7 +133,12 @@ describe('ReactDOMFiber', () => {
class Fragment extends React.Component { class Fragment extends React.Component {
render() { render() {
return [<Wrapper key="a"><div /></Wrapper>, <span key="b" />]; return [
<Wrapper key="a">
<div />
</Wrapper>,
<span key="b" />,
];
} }
} }
@ -204,9 +209,7 @@ describe('ReactDOMFiber', () => {
var portalContainer = document.createElement('div'); var portalContainer = document.createElement('div');
ReactDOM.render( ReactDOM.render(
<div> <div>{ReactDOM.createPortal(<div>portal</div>, portalContainer)}</div>,
{ReactDOM.createPortal(<div>portal</div>, portalContainer)}
</div>,
container, container,
); );
expect(portalContainer.innerHTML).toBe('<div>portal</div>'); expect(portalContainer.innerHTML).toBe('<div>portal</div>');
@ -382,54 +385,42 @@ describe('ReactDOMFiber', () => {
var portalContainer = document.createElement('div'); var portalContainer = document.createElement('div');
ReactDOM.render( ReactDOM.render(
<div> <div>{ReactDOM.createPortal(<div>portal:1</div>, portalContainer)}</div>,
{ReactDOM.createPortal(<div>portal:1</div>, portalContainer)}
</div>,
container, container,
); );
expect(portalContainer.innerHTML).toBe('<div>portal:1</div>'); expect(portalContainer.innerHTML).toBe('<div>portal:1</div>');
expect(container.innerHTML).toBe('<div></div>'); expect(container.innerHTML).toBe('<div></div>');
ReactDOM.render( ReactDOM.render(
<div> <div>{ReactDOM.createPortal(<div>portal:2</div>, portalContainer)}</div>,
{ReactDOM.createPortal(<div>portal:2</div>, portalContainer)}
</div>,
container, container,
); );
expect(portalContainer.innerHTML).toBe('<div>portal:2</div>'); expect(portalContainer.innerHTML).toBe('<div>portal:2</div>');
expect(container.innerHTML).toBe('<div></div>'); expect(container.innerHTML).toBe('<div></div>');
ReactDOM.render( ReactDOM.render(
<div> <div>{ReactDOM.createPortal(<p>portal:3</p>, portalContainer)}</div>,
{ReactDOM.createPortal(<p>portal:3</p>, portalContainer)}
</div>,
container, container,
); );
expect(portalContainer.innerHTML).toBe('<p>portal:3</p>'); expect(portalContainer.innerHTML).toBe('<p>portal:3</p>');
expect(container.innerHTML).toBe('<div></div>'); expect(container.innerHTML).toBe('<div></div>');
ReactDOM.render( ReactDOM.render(
<div> <div>{ReactDOM.createPortal(['Hi', 'Bye'], portalContainer)}</div>,
{ReactDOM.createPortal(['Hi', 'Bye'], portalContainer)}
</div>,
container, container,
); );
expect(portalContainer.innerHTML).toBe('HiBye'); expect(portalContainer.innerHTML).toBe('HiBye');
expect(container.innerHTML).toBe('<div></div>'); expect(container.innerHTML).toBe('<div></div>');
ReactDOM.render( ReactDOM.render(
<div> <div>{ReactDOM.createPortal(['Bye', 'Hi'], portalContainer)}</div>,
{ReactDOM.createPortal(['Bye', 'Hi'], portalContainer)}
</div>,
container, container,
); );
expect(portalContainer.innerHTML).toBe('ByeHi'); expect(portalContainer.innerHTML).toBe('ByeHi');
expect(container.innerHTML).toBe('<div></div>'); expect(container.innerHTML).toBe('<div></div>');
ReactDOM.render( ReactDOM.render(
<div> <div>{ReactDOM.createPortal(null, portalContainer)}</div>,
{ReactDOM.createPortal(null, portalContainer)}
</div>,
container, container,
); );
expect(portalContainer.innerHTML).toBe(''); expect(portalContainer.innerHTML).toBe('');

View File

@ -46,13 +46,17 @@ describe('ReactDOMFiberAsync', () => {
it('renders synchronously', () => { it('renders synchronously', () => {
ReactDOM.render( ReactDOM.render(
<AsyncComponent><div>Hi</div></AsyncComponent>, <AsyncComponent>
<div>Hi</div>
</AsyncComponent>,
container, container,
); );
expect(container.textContent).toEqual('Hi'); expect(container.textContent).toEqual('Hi');
ReactDOM.render( ReactDOM.render(
<AsyncComponent><div>Bye</div></AsyncComponent>, <AsyncComponent>
<div>Bye</div>
</AsyncComponent>,
container, container,
); );
expect(container.textContent).toEqual('Bye'); expect(container.textContent).toEqual('Bye');
@ -70,7 +74,9 @@ describe('ReactDOMFiberAsync', () => {
it('AsyncComponent at the root makes the entire tree async', () => { it('AsyncComponent at the root makes the entire tree async', () => {
ReactDOM.render( ReactDOM.render(
<AsyncComponent><div>Hi</div></AsyncComponent>, <AsyncComponent>
<div>Hi</div>
</AsyncComponent>,
container, container,
); );
expect(container.textContent).toEqual(''); expect(container.textContent).toEqual('');
@ -78,7 +84,9 @@ describe('ReactDOMFiberAsync', () => {
expect(container.textContent).toEqual('Hi'); expect(container.textContent).toEqual('Hi');
ReactDOM.render( ReactDOM.render(
<AsyncComponent><div>Bye</div></AsyncComponent>, <AsyncComponent>
<div>Bye</div>
</AsyncComponent>,
container, container,
); );
expect(container.textContent).toEqual('Hi'); expect(container.textContent).toEqual('Hi');
@ -97,7 +105,9 @@ describe('ReactDOMFiberAsync', () => {
} }
ReactDOM.render( ReactDOM.render(
<AsyncComponent><Component /></AsyncComponent>, <AsyncComponent>
<Component />
</AsyncComponent>,
container, container,
); );
expect(container.textContent).toEqual(''); expect(container.textContent).toEqual('');
@ -120,7 +130,12 @@ describe('ReactDOMFiberAsync', () => {
} }
} }
ReactDOM.render(<div><Component /></div>, container); ReactDOM.render(
<div>
<Component />
</div>,
container,
);
jest.runAllTimers(); jest.runAllTimers();
instance.setState({step: 1}); instance.setState({step: 1});
@ -145,7 +160,12 @@ describe('ReactDOMFiberAsync', () => {
} }
} }
ReactDOM.render(<div><Component /></div>, container); ReactDOM.render(
<div>
<Component />
</div>,
container,
);
jest.runAllTimers(); jest.runAllTimers();
instance.setState({step: 1}); instance.setState({step: 1});

View File

@ -629,7 +629,6 @@ describe('ReactDOMInput', () => {
A A
<input ref="b" type="radio" name="fruit" onChange={emptyFunction} /> <input ref="b" type="radio" name="fruit" onChange={emptyFunction} />
B B
<form> <form>
<input <input
ref="c" ref="c"

View File

@ -25,7 +25,11 @@ describe('ReactDOMOption', () => {
}); });
it('should flatten children to a string', () => { it('should flatten children to a string', () => {
var stub = <option>{1} {'foo'}</option>; var stub = (
<option>
{1} {'foo'}
</option>
);
stub = ReactTestUtils.renderIntoDocument(stub); stub = ReactTestUtils.renderIntoDocument(stub);
var node = ReactDOM.findDOMNode(stub); var node = ReactDOM.findDOMNode(stub);
@ -34,7 +38,11 @@ describe('ReactDOMOption', () => {
it('should ignore and warn invalid children types', () => { it('should ignore and warn invalid children types', () => {
spyOn(console, 'error'); spyOn(console, 'error');
var el = <option>{1} <div /> {2}</option>; var el = (
<option>
{1} <div /> {2}
</option>
);
var node = ReactTestUtils.renderIntoDocument(el); var node = ReactTestUtils.renderIntoDocument(el);
expect(node.innerHTML).toBe('1 2'); expect(node.innerHTML).toBe('1 2');
ReactTestUtils.renderIntoDocument(el); ReactTestUtils.renderIntoDocument(el);
@ -50,7 +58,14 @@ describe('ReactDOMOption', () => {
}); });
it('should ignore null/undefined/false children without warning', () => { it('should ignore null/undefined/false children without warning', () => {
var stub = <option>{1} {false}{true}{null}{undefined} {2}</option>; var stub = (
<option>
{1} {false}
{true}
{null}
{undefined} {2}
</option>
);
spyOn(console, 'error'); spyOn(console, 'error');
stub = ReactTestUtils.renderIntoDocument(stub); stub = ReactTestUtils.renderIntoDocument(stub);

View File

@ -205,7 +205,9 @@ describe('ReactDOMProduction', () => {
ReactDOM.render(<Component />, container); ReactDOM.render(<Component />, container);
}).toThrowError( }).toThrowError(
`Minified React error #${errorCode}; visit ` + `Minified React error #${errorCode}; visit ` +
`http://facebook.github.io/react/docs/error-decoder.html?invariant=${errorCode}&args[]=Component` + `http://facebook.github.io/react/docs/error-decoder.html?invariant=${
errorCode
}&args[]=Component` +
' for the full message or use the non-minified dev environment' + ' for the full message or use the non-minified dev environment' +
' for full errors and additional helpful warnings.', ' for full errors and additional helpful warnings.',
); );
@ -219,7 +221,9 @@ describe('ReactDOMProduction', () => {
ReactDOM.render(<input>children</input>, container), ReactDOM.render(<input>children</input>, container),
).toThrowError( ).toThrowError(
`Minified React error #${errorCode}; visit ` + `Minified React error #${errorCode}; visit ` +
`http://facebook.github.io/react/docs/error-decoder.html?invariant=${errorCode}&args[]=input&args[]=` + `http://facebook.github.io/react/docs/error-decoder.html?invariant=${
errorCode
}&args[]=input&args[]=` +
' for the full message or use the non-minified dev environment' + ' for the full message or use the non-minified dev environment' +
' for full errors and additional helpful warnings.', ' for full errors and additional helpful warnings.',
); );
@ -227,7 +231,9 @@ describe('ReactDOMProduction', () => {
ReactDOMServer.renderToString(<input>children</input>, container), ReactDOMServer.renderToString(<input>children</input>, container),
).toThrowError( ).toThrowError(
`Minified React error #${errorCode}; visit ` + `Minified React error #${errorCode}; visit ` +
`http://facebook.github.io/react/docs/error-decoder.html?invariant=${errorCode}&args[]=input&args[]=` + `http://facebook.github.io/react/docs/error-decoder.html?invariant=${
errorCode
}&args[]=input&args[]=` +
' for the full message or use the non-minified dev environment' + ' for the full message or use the non-minified dev environment' +
' for full errors and additional helpful warnings.', ' for full errors and additional helpful warnings.',
); );

View File

@ -38,7 +38,11 @@ describe('ReactDOMRoot', () => {
it('supports hydration', async () => { it('supports hydration', async () => {
const markup = await new Promise(resolve => const markup = await new Promise(resolve =>
resolve( resolve(
ReactDOMServer.renderToString(<div><span className="extra" /></div>), ReactDOMServer.renderToString(
<div>
<span className="extra" />
</div>,
),
), ),
); );
@ -48,14 +52,22 @@ describe('ReactDOMRoot', () => {
const container1 = document.createElement('div'); const container1 = document.createElement('div');
container1.innerHTML = markup; container1.innerHTML = markup;
const root1 = ReactDOM.createRoot(container1); const root1 = ReactDOM.createRoot(container1);
root1.render(<div><span /></div>); root1.render(
<div>
<span />
</div>,
);
expect(console.error.calls.count()).toBe(0); expect(console.error.calls.count()).toBe(0);
// Accepts `hydrate` option // Accepts `hydrate` option
const container2 = document.createElement('div'); const container2 = document.createElement('div');
container2.innerHTML = markup; container2.innerHTML = markup;
const root2 = ReactDOM.createRoot(container2, {hydrate: true}); const root2 = ReactDOM.createRoot(container2, {hydrate: true});
root2.render(<div><span /></div>); root2.render(
<div>
<span />
</div>,
);
expect(console.error.calls.count()).toBe(1); expect(console.error.calls.count()).toBe(1);
expect(console.error.calls.argsFor(0)[0]).toMatch('Extra attributes'); expect(console.error.calls.argsFor(0)[0]).toMatch('Extra attributes');
}); });
@ -64,9 +76,19 @@ describe('ReactDOMRoot', () => {
spyOn(console, 'error'); spyOn(console, 'error');
container.innerHTML = '<div>a</div><div>b</div>'; container.innerHTML = '<div>a</div><div>b</div>';
const root = ReactDOM.createRoot(container); const root = ReactDOM.createRoot(container);
root.render(<div><span>c</span><span>d</span></div>); root.render(
<div>
<span>c</span>
<span>d</span>
</div>,
);
expect(container.textContent).toEqual('abcd'); expect(container.textContent).toEqual('abcd');
root.render(<div><span>d</span><span>c</span></div>); root.render(
<div>
<span>d</span>
<span>c</span>
</div>,
);
expect(container.textContent).toEqual('abdc'); expect(container.textContent).toEqual('abdc');
}); });
}); });

View File

@ -95,7 +95,9 @@ describe('ReactDOMSelect', () => {
// Changing `defaultValue` should do nothing. // Changing `defaultValue` should do nothing.
ReactDOM.render( ReactDOM.render(
<select multiple={true} defaultValue={['monkey']}>{options}</select>, <select multiple={true} defaultValue={['monkey']}>
{options}
</select>,
container, container,
); );
@ -121,7 +123,9 @@ describe('ReactDOMSelect', () => {
// Changing the `value` prop should change the selected option. // Changing the `value` prop should change the selected option.
ReactDOM.render( ReactDOM.render(
<select value="gorilla" onChange={noop}>{options}</select>, <select value="gorilla" onChange={noop}>
{options}
</select>,
container, container,
); );
expect(node.value).toEqual('gorilla'); expect(node.value).toEqual('gorilla');
@ -160,7 +164,9 @@ describe('ReactDOMSelect', () => {
// Changing the `value` prop should change the selected option. // Changing the `value` prop should change the selected option.
ReactDOM.render( ReactDOM.render(
<select value="gorilla" onChange={noop}>{options}</select>, <select value="gorilla" onChange={noop}>
{options}
</select>,
container, container,
); );
expect(node.value).toEqual('gorilla'); expect(node.value).toEqual('gorilla');
@ -408,7 +414,9 @@ describe('ReactDOMSelect', () => {
var node = ReactDOM.findDOMNode(stub); var node = ReactDOM.findDOMNode(stub);
ReactDOM.render( ReactDOM.render(
<select value="gorilla" onChange={noop}>{options}</select>, <select value="gorilla" onChange={noop}>
{options}
</select>,
container, container,
); );
@ -470,9 +478,15 @@ describe('ReactDOMSelect', () => {
var select = ReactDOM.render( var select = ReactDOM.render(
<select multiple={true} defaultValue={['giraffe']}> <select multiple={true} defaultValue={['giraffe']}>
<option key="monkey" value="monkey">A monkey!</option> <option key="monkey" value="monkey">
<option key="giraffe" value="giraffe">A giraffe!</option> A monkey!
<option key="gorilla" value="gorilla">A gorilla!</option> </option>
<option key="giraffe" value="giraffe">
A giraffe!
</option>
<option key="gorilla" value="gorilla">
A gorilla!
</option>
</select>, </select>,
container, container,
); );
@ -484,8 +498,12 @@ describe('ReactDOMSelect', () => {
ReactDOM.render( ReactDOM.render(
<select multiple={true} defaultValue={['giraffe']}> <select multiple={true} defaultValue={['giraffe']}>
<option key="monkey" value="monkey">A monkey!</option> <option key="monkey" value="monkey">
<option key="gorilla" value="gorilla">A gorilla!</option> A monkey!
</option>
<option key="gorilla" value="gorilla">
A gorilla!
</option>
</select>, </select>,
container, container,
); );
@ -495,9 +513,15 @@ describe('ReactDOMSelect', () => {
ReactDOM.render( ReactDOM.render(
<select multiple={true} defaultValue={['giraffe']}> <select multiple={true} defaultValue={['giraffe']}>
<option key="monkey" value="monkey">A monkey!</option> <option key="monkey" value="monkey">
<option key="giraffe" value="giraffe">A giraffe!</option> A monkey!
<option key="gorilla" value="gorilla">A gorilla!</option> </option>
<option key="giraffe" value="giraffe">
A giraffe!
</option>
<option key="gorilla" value="gorilla">
A gorilla!
</option>
</select>, </select>,
container, container,
); );
@ -511,7 +535,9 @@ describe('ReactDOMSelect', () => {
spyOn(console, 'error'); spyOn(console, 'error');
ReactTestUtils.renderIntoDocument( ReactTestUtils.renderIntoDocument(
<select value={null}><option value="test" /></select>, <select value={null}>
<option value="test" />
</select>,
); );
expectDev(console.error.calls.argsFor(0)[0]).toContain( expectDev(console.error.calls.argsFor(0)[0]).toContain(
'`value` prop on `select` should not be null. ' + '`value` prop on `select` should not be null. ' +
@ -520,7 +546,9 @@ describe('ReactDOMSelect', () => {
); );
ReactTestUtils.renderIntoDocument( ReactTestUtils.renderIntoDocument(
<select value={null}><option value="test" /></select>, <select value={null}>
<option value="test" />
</select>,
); );
expectDev(console.error.calls.count()).toBe(1); expectDev(console.error.calls.count()).toBe(1);
}); });
@ -528,7 +556,9 @@ describe('ReactDOMSelect', () => {
it('should warn if value is null and multiple is true', () => { it('should warn if value is null and multiple is true', () => {
spyOn(console, 'error'); spyOn(console, 'error');
ReactTestUtils.renderIntoDocument( ReactTestUtils.renderIntoDocument(
<select value={null} multiple={true}><option value="test" /></select>, <select value={null} multiple={true}>
<option value="test" />
</select>,
); );
expectDev(console.error.calls.count()).toBe(1); expectDev(console.error.calls.count()).toBe(1);
@ -540,7 +570,9 @@ describe('ReactDOMSelect', () => {
); );
ReactTestUtils.renderIntoDocument( ReactTestUtils.renderIntoDocument(
<select value={null} multiple={true}><option value="test" /></select>, <select value={null} multiple={true}>
<option value="test" />
</select>,
); );
expectDev(console.error.calls.count()).toBe(1); expectDev(console.error.calls.count()).toBe(1);
}); });

View File

@ -51,7 +51,9 @@ async function expectErrors(fn, count) {
console.error.calls.count() !== 0 console.error.calls.count() !== 0
) { ) {
console.log( console.log(
`We expected ${count} warning(s), but saw ${console.error.calls.count()} warning(s).`, `We expected ${
count
} warning(s), but saw ${console.error.calls.count()} warning(s).`,
); );
if (console.error.calls.count() > 0) { if (console.error.calls.count() > 0) {
console.log(`We saw these warnings:`); console.log(`We saw these warnings:`);
@ -230,7 +232,9 @@ function itClientRenders(desc, testFn) {
testFn(clientCleanRender)); testFn(clientCleanRender));
it(`renders ${desc} with client render on top of good server markup`, () => it(`renders ${desc} with client render on top of good server markup`, () =>
testFn(clientRenderOnServerString)); testFn(clientRenderOnServerString));
it(`renders ${desc} with client render on top of bad server markup`, async () => { it(`renders ${
desc
} with client render on top of bad server markup`, async () => {
try { try {
await testFn(clientRenderOnBadMarkup); await testFn(clientRenderOnBadMarkup);
} catch (x) { } catch (x) {
@ -349,7 +353,11 @@ describe('ReactDOMServerIntegration', () => {
}); });
itRenders('a self-closing tag as a child', async render => { itRenders('a self-closing tag as a child', async render => {
const e = await render(<div><br /></div>); const e = await render(
<div>
<br />
</div>,
);
expect(e.childNodes.length).toBe(1); expect(e.childNodes.length).toBe(1);
expect(e.firstChild.tagName).toBe('BR'); expect(e.firstChild.tagName).toBe('BR');
}); });
@ -406,7 +414,11 @@ describe('ReactDOMServerIntegration', () => {
}); });
itRenders('a fragment with one child', async render => { itRenders('a fragment with one child', async render => {
let e = await render(<React.Fragment><div>text1</div></React.Fragment>); let e = await render(
<React.Fragment>
<div>text1</div>
</React.Fragment>,
);
let parent = e.parentNode; let parent = e.parentNode;
expect(parent.childNodes[0].tagName).toBe('DIV'); expect(parent.childNodes[0].tagName).toBe('DIV');
}); });
@ -416,7 +428,12 @@ describe('ReactDOMServerIntegration', () => {
return <p>header</p>; return <p>header</p>;
}; };
let Footer = props => { let Footer = props => {
return <React.Fragment><h2>footer</h2><h3>about</h3></React.Fragment>; return (
<React.Fragment>
<h2>footer</h2>
<h3>about</h3>
</React.Fragment>
);
}; };
let e = await render( let e = await render(
<React.Fragment> <React.Fragment>
@ -443,7 +460,11 @@ describe('ReactDOMServerIntegration', () => {
<span>text2</span> <span>text2</span>
<React.Fragment> <React.Fragment>
<React.Fragment> <React.Fragment>
<React.Fragment>{null}<p /></React.Fragment>{false} <React.Fragment>
{null}
<p />
</React.Fragment>
{false}
</React.Fragment> </React.Fragment>
</React.Fragment> </React.Fragment>
</React.Fragment>, </React.Fragment>,
@ -1018,7 +1039,11 @@ describe('ReactDOMServerIntegration', () => {
); );
itRenders('SVG tags with dashes in them', async render => { itRenders('SVG tags with dashes in them', async render => {
const e = await render(<svg><font-face accentHeight={10} /></svg>); const e = await render(
<svg>
<font-face accentHeight={10} />
</svg>,
);
expect(e.firstChild.hasAttribute('accentHeight')).toBe(false); expect(e.firstChild.hasAttribute('accentHeight')).toBe(false);
expect(e.firstChild.getAttribute('accent-height')).toBe('10'); expect(e.firstChild.getAttribute('accent-height')).toBe('10');
}); });
@ -1082,7 +1107,13 @@ describe('ReactDOMServerIntegration', () => {
}); });
itRenders('a div with multiple empty text children', async render => { itRenders('a div with multiple empty text children', async render => {
const e = await render(<div>{''}{''}{''}</div>); const e = await render(
<div>
{''}
{''}
{''}
</div>,
);
if (render === serverRender || render === streamRender) { if (render === serverRender || render === streamRender) {
// For plain server markup result we should have no text nodes if // For plain server markup result we should have no text nodes if
// they're all empty. // they're all empty.
@ -1097,6 +1128,7 @@ describe('ReactDOMServerIntegration', () => {
}); });
itRenders('a div with multiple whitespace children', async render => { itRenders('a div with multiple whitespace children', async render => {
// prettier-ignore
const e = await render(<div>{' '}{' '}{' '}</div>); const e = await render(<div>{' '}{' '}{' '}</div>);
if ( if (
render === serverRender || render === serverRender ||
@ -1118,7 +1150,11 @@ describe('ReactDOMServerIntegration', () => {
}); });
itRenders('a div with text sibling to a node', async render => { itRenders('a div with text sibling to a node', async render => {
const e = await render(<div>Text<span>More Text</span></div>); const e = await render(
<div>
Text<span>More Text</span>
</div>,
);
let spanNode; let spanNode;
expect(e.childNodes.length).toBe(2); expect(e.childNodes.length).toBe(2);
spanNode = e.childNodes[1]; spanNode = e.childNodes[1];
@ -1168,7 +1204,12 @@ describe('ReactDOMServerIntegration', () => {
}); });
itRenders('an element with two text children', async render => { itRenders('an element with two text children', async render => {
const e = await render(<div>{'foo'}{'bar'}</div>); const e = await render(
<div>
{'foo'}
{'bar'}
</div>,
);
if ( if (
render === serverRender || render === serverRender ||
render === clientRenderOnServerString || render === clientRenderOnServerString ||
@ -1189,7 +1230,13 @@ describe('ReactDOMServerIntegration', () => {
'a component returning text node between two text nodes', 'a component returning text node between two text nodes',
async render => { async render => {
const B = () => 'b'; const B = () => 'b';
const e = await render(<div>{'a'}<B />{'c'}</div>); const e = await render(
<div>
{'a'}
<B />
{'c'}
</div>,
);
if ( if (
render === serverRender || render === serverRender ||
render === clientRenderOnServerString || render === clientRenderOnServerString ||
@ -1272,7 +1319,12 @@ describe('ReactDOMServerIntegration', () => {
}); });
itRenders('an element with number and text children', async render => { itRenders('an element with number and text children', async render => {
const e = await render(<div>{'foo'}{40}</div>); const e = await render(
<div>
{'foo'}
{40}
</div>,
);
// with Fiber, there are just two text nodes. // with Fiber, there are just two text nodes.
if ( if (
render === serverRender || render === serverRender ||
@ -1309,7 +1361,11 @@ describe('ReactDOMServerIntegration', () => {
itRenders('a null component children as empty', async render => { itRenders('a null component children as empty', async render => {
const NullComponent = () => null; const NullComponent = () => null;
const e = await render(<div><NullComponent /></div>); const e = await render(
<div>
<NullComponent />
</div>,
);
expect(e.childNodes.length).toBe(0); expect(e.childNodes.length).toBe(0);
}); });
@ -1326,13 +1382,26 @@ describe('ReactDOMServerIntegration', () => {
}); });
itRenders('null and false children together as blank', async render => { itRenders('null and false children together as blank', async render => {
const e = await render(<div>{false}{null}foo{null}{false}</div>); const e = await render(
<div>
{false}
{null}foo{null}
{false}
</div>,
);
expect(e.childNodes.length).toBe(1); expect(e.childNodes.length).toBe(1);
expectTextNode(e.childNodes[0], 'foo'); expectTextNode(e.childNodes[0], 'foo');
}); });
itRenders('only null and false children as blank', async render => { itRenders('only null and false children as blank', async render => {
const e = await render(<div>{false}{null}{null}{false}</div>); const e = await render(
<div>
{false}
{null}
{null}
{false}
</div>,
);
expect(e.childNodes.length).toBe(0); expect(e.childNodes.length).toBe(0);
}); });
}); });
@ -1357,7 +1426,9 @@ describe('ReactDOMServerIntegration', () => {
'svg child element with a namespace attribute', 'svg child element with a namespace attribute',
async render => { async render => {
let e = await render( let e = await render(
<svg><image xlinkHref="http://i.imgur.com/w7GCRPb.png" /></svg>, <svg>
<image xlinkHref="http://i.imgur.com/w7GCRPb.png" />
</svg>,
); );
e = e.firstChild; e = e.firstChild;
expect(e.childNodes.length).toBe(0); expect(e.childNodes.length).toBe(0);
@ -1371,7 +1442,9 @@ describe('ReactDOMServerIntegration', () => {
itRenders('svg child element with a badly cased alias', async render => { itRenders('svg child element with a badly cased alias', async render => {
let e = await render( let e = await render(
<svg><image xlinkhref="http://i.imgur.com/w7GCRPb.png" /></svg>, <svg>
<image xlinkhref="http://i.imgur.com/w7GCRPb.png" />
</svg>,
1, 1,
); );
e = e.firstChild; e = e.firstChild;
@ -1397,7 +1470,13 @@ describe('ReactDOMServerIntegration', () => {
); );
itRenders('svg element with a mixed case name', async render => { itRenders('svg element with a mixed case name', async render => {
let e = await render(<svg><filter><feMorphology /></filter></svg>); let e = await render(
<svg>
<filter>
<feMorphology />
</filter>
</svg>,
);
e = e.firstChild.firstChild; e = e.firstChild.firstChild;
expect(e.childNodes.length).toBe(0); expect(e.childNodes.length).toBe(0);
expect(e.tagName).toBe('feMorphology'); expect(e.tagName).toBe('feMorphology');
@ -1516,10 +1595,12 @@ describe('ReactDOMServerIntegration', () => {
const e = await render( const e = await render(
<Component> <Component>
<Component> <Component>
<Component /><Component /> <Component />
<Component />
</Component> </Component>
<Component> <Component>
<Component /><Component /> <Component />
<Component />
</Component> </Component>
</Component>, </Component>,
); );
@ -1538,7 +1619,11 @@ describe('ReactDOMServerIntegration', () => {
}); });
itRenders('a div with a child', async render => { itRenders('a div with a child', async render => {
const e = await render(<div id="parent"><div id="child" /></div>); const e = await render(
<div id="parent">
<div id="child" />
</div>,
);
expect(e.id).toBe('parent'); expect(e.id).toBe('parent');
expect(e.childNodes.length).toBe(1); expect(e.childNodes.length).toBe(1);
expect(e.childNodes[0].id).toBe('child'); expect(e.childNodes[0].id).toBe('child');
@ -1547,7 +1632,10 @@ describe('ReactDOMServerIntegration', () => {
itRenders('a div with multiple children', async render => { itRenders('a div with multiple children', async render => {
const e = await render( const e = await render(
<div id="parent"><div id="child1" /><div id="child2" /></div>, <div id="parent">
<div id="child1" />
<div id="child2" />
</div>,
); );
expect(e.id).toBe('parent'); expect(e.id).toBe('parent');
expect(e.childNodes.length).toBe(2); expect(e.childNodes.length).toBe(2);
@ -1561,7 +1649,9 @@ describe('ReactDOMServerIntegration', () => {
'a div with multiple children separated by whitespace', 'a div with multiple children separated by whitespace',
async render => { async render => {
const e = await render( const e = await render(
<div id="parent"><div id="child1" /> <div id="child2" /></div>, <div id="parent">
<div id="child1" /> <div id="child2" />
</div>,
); );
expect(e.id).toBe('parent'); expect(e.id).toBe('parent');
let child1, child2, textNode; let child1, child2, textNode;
@ -1631,7 +1721,10 @@ describe('ReactDOMServerIntegration', () => {
itRenders('>,<, and & as multiple children', async render => { itRenders('>,<, and & as multiple children', async render => {
const e = await render( const e = await render(
<div>{'<span>Text1&quot;</span>'}{'<span>Text2&quot;</span>'}</div>, <div>
{'<span>Text1&quot;</span>'}
{'<span>Text2&quot;</span>'}
</div>,
); );
if ( if (
render === serverRender || render === serverRender ||
@ -1681,7 +1774,12 @@ describe('ReactDOMServerIntegration', () => {
itRenders( itRenders(
'an element with two text children with special characters', 'an element with two text children with special characters',
async render => { async render => {
const e = await render(<div>{'foo\rbar'}{'\r\nbaz\nqux\u0000'}</div>); const e = await render(
<div>
{'foo\rbar'}
{'\r\nbaz\nqux\u0000'}
</div>,
);
if (render === serverRender || render === streamRender) { if (render === serverRender || render === streamRender) {
// We have three nodes because there is a comment between them. // We have three nodes because there is a comment between them.
expect(e.childNodes.length).toBe(3); expect(e.childNodes.length).toBe(3);
@ -1975,9 +2073,15 @@ describe('ReactDOMServerIntegration', () => {
var options; var options;
beforeEach(function() { beforeEach(function() {
options = [ options = [
<option key={1} value="foo" id="foo">Foo</option>, <option key={1} value="foo" id="foo">
<option key={2} value="bar" id="bar">Bar</option>, Foo
<option key={3} value="baz" id="baz">Baz</option>, </option>,
<option key={2} value="bar" id="bar">
Bar
</option>,
<option key={3} value="baz" id="baz">
Baz
</option>,
]; ];
}); });
@ -2002,14 +2106,18 @@ describe('ReactDOMServerIntegration', () => {
itRenders('a select with a value and an onChange', async render => { itRenders('a select with a value and an onChange', async render => {
const e = await render( const e = await render(
<select value="bar" onChange={() => {}}>{options}</select>, <select value="bar" onChange={() => {}}>
{options}
</select>,
); );
expectSelectValue(e, 'bar'); expectSelectValue(e, 'bar');
}); });
itRenders('a select with a value and readOnly', async render => { itRenders('a select with a value and readOnly', async render => {
const e = await render( const e = await render(
<select value="bar" readOnly={true}>{options}</select>, <select value="bar" readOnly={true}>
{options}
</select>,
); );
expectSelectValue(e, 'bar'); expectSelectValue(e, 'bar');
}); });
@ -2160,8 +2268,12 @@ describe('ReactDOMServerIntegration', () => {
<select <select
value={this.state.value} value={this.state.value}
onChange={this.handleChange.bind(this)}> onChange={this.handleChange.bind(this)}>
<option key="1" value="Hello">Hello</option> <option key="1" value="Hello">
<option key="2" value="Goodbye">Goodbye</option> Hello
</option>
<option key="2" value="Goodbye">
Goodbye
</option>
</select> </select>
); );
} }
@ -2304,32 +2416,30 @@ describe('ReactDOMServerIntegration', () => {
// skipping this test because React 15 does the wrong thing. it blows // skipping this test because React 15 does the wrong thing. it blows
// away the user's typing in the textarea. // away the user's typing in the textarea.
xit( xit('should not blow away user-entered text on successful reconnect to an uncontrolled textarea', () =>
'should not blow away user-entered text on successful reconnect to an uncontrolled textarea', testUserInteractionBeforeClientRender(
() => <textarea defaultValue="Hello" />,
testUserInteractionBeforeClientRender( ));
<textarea defaultValue="Hello" />,
),
);
// skipping this test because React 15 does the wrong thing. it blows // skipping this test because React 15 does the wrong thing. it blows
// away the user's typing in the textarea. // away the user's typing in the textarea.
xit( xit('should not blow away user-entered text on successful reconnect to a controlled textarea', async () => {
'should not blow away user-entered text on successful reconnect to a controlled textarea', let changeCount = 0;
async () => { await testUserInteractionBeforeClientRender(
let changeCount = 0; <ControlledTextArea onChange={() => changeCount++} />,
await testUserInteractionBeforeClientRender( );
<ControlledTextArea onChange={() => changeCount++} />, expect(changeCount).toBe(0);
); });
expect(changeCount).toBe(0);
},
);
it('should not blow away user-selected value on successful reconnect to an uncontrolled select', () => it('should not blow away user-selected value on successful reconnect to an uncontrolled select', () =>
testUserInteractionBeforeClientRender( testUserInteractionBeforeClientRender(
<select defaultValue="Hello"> <select defaultValue="Hello">
<option key="1" value="Hello">Hello</option> <option key="1" value="Hello">
<option key="2" value="Goodbye">Goodbye</option> Hello
</option>
<option key="2" value="Goodbye">
Goodbye
</option>
</select>, </select>,
)); ));
@ -2370,7 +2480,9 @@ describe('ReactDOMServerIntegration', () => {
ClassChildWithContext.contextTypes = {text: PropTypes.string}; ClassChildWithContext.contextTypes = {text: PropTypes.string};
const e = await render( const e = await render(
<PurpleContext><ClassChildWithContext /></PurpleContext>, <PurpleContext>
<ClassChildWithContext />
</PurpleContext>,
); );
expect(e.textContent).toBe('purple'); expect(e.textContent).toBe('purple');
}); });
@ -2382,7 +2494,9 @@ describe('ReactDOMServerIntegration', () => {
StatelessChildWithContext.contextTypes = {text: PropTypes.string}; StatelessChildWithContext.contextTypes = {text: PropTypes.string};
const e = await render( const e = await render(
<PurpleContext><StatelessChildWithContext /></PurpleContext>, <PurpleContext>
<StatelessChildWithContext />
</PurpleContext>,
); );
expect(e.textContent).toBe('purple'); expect(e.textContent).toBe('purple');
}); });
@ -2396,7 +2510,9 @@ describe('ReactDOMServerIntegration', () => {
} }
const e = await render( const e = await render(
<PurpleContext><ClassChildWithoutContext /></PurpleContext>, <PurpleContext>
<ClassChildWithoutContext />
</PurpleContext>,
); );
expect(e.textContent).toBe(''); expect(e.textContent).toBe('');
}); });
@ -2408,7 +2524,9 @@ describe('ReactDOMServerIntegration', () => {
} }
const e = await render( const e = await render(
<PurpleContext><StatelessChildWithoutContext /></PurpleContext>, <PurpleContext>
<StatelessChildWithoutContext />
</PurpleContext>,
); );
expect(e.textContent).toBe(''); expect(e.textContent).toBe('');
}); });
@ -2423,7 +2541,9 @@ describe('ReactDOMServerIntegration', () => {
ClassChildWithWrongContext.contextTypes = {foo: PropTypes.string}; ClassChildWithWrongContext.contextTypes = {foo: PropTypes.string};
const e = await render( const e = await render(
<PurpleContext><ClassChildWithWrongContext /></PurpleContext>, <PurpleContext>
<ClassChildWithWrongContext />
</PurpleContext>,
); );
expect(e.textContent).toBe(''); expect(e.textContent).toBe('');
}); });
@ -2438,7 +2558,9 @@ describe('ReactDOMServerIntegration', () => {
}; };
const e = await render( const e = await render(
<PurpleContext><StatelessChildWithWrongContext /></PurpleContext>, <PurpleContext>
<StatelessChildWithWrongContext />
</PurpleContext>,
); );
expect(e.textContent).toBe(''); expect(e.textContent).toBe('');
}); });
@ -2451,7 +2573,11 @@ describe('ReactDOMServerIntegration', () => {
const Child = props => <Grandchild />; const Child = props => <Grandchild />;
const e = await render(<PurpleContext><Child /></PurpleContext>); const e = await render(
<PurpleContext>
<Child />
</PurpleContext>,
);
expect(e.textContent).toBe('purple'); expect(e.textContent).toBe('purple');
}); });
@ -2462,7 +2588,11 @@ describe('ReactDOMServerIntegration', () => {
Grandchild.contextTypes = {text: PropTypes.string}; Grandchild.contextTypes = {text: PropTypes.string};
const e = await render( const e = await render(
<PurpleContext><RedContext><Grandchild /></RedContext></PurpleContext>, <PurpleContext>
<RedContext>
<Grandchild />
</RedContext>
</PurpleContext>,
); );
expect(e.textContent).toBe('red'); expect(e.textContent).toBe('red');
}); });
@ -2707,8 +2837,12 @@ describe('ReactDOMServerIntegration', () => {
it('can explicitly ignore errors reconnecting different element types of children', () => it('can explicitly ignore errors reconnecting different element types of children', () =>
expectMarkupMatch( expectMarkupMatch(
<div><div /></div>, <div>
<div suppressHydrationWarning={true}><span /></div>, <div />
</div>,
<div suppressHydrationWarning={true}>
<span />
</div>,
)); ));
it('can explicitly ignore errors reconnecting missing attributes', () => it('can explicitly ignore errors reconnecting missing attributes', () =>
@ -2731,8 +2865,12 @@ describe('ReactDOMServerIntegration', () => {
it('can not deeply ignore errors reconnecting different attribute values', () => it('can not deeply ignore errors reconnecting different attribute values', () =>
expectMarkupMismatch( expectMarkupMismatch(
<div><div id="foo" /></div>, <div>
<div suppressHydrationWarning={true}><div id="bar" /></div>, <div id="foo" />
</div>,
<div suppressHydrationWarning={true}>
<div id="bar" />
</div>,
)); ));
}); });
@ -2801,8 +2939,14 @@ describe('ReactDOMServerIntegration', () => {
it('should error reconnecting different text in two code blocks', () => it('should error reconnecting different text in two code blocks', () =>
expectMarkupMismatch( expectMarkupMismatch(
<div>{'Text1'}{'Text2'}</div>, <div>
<div>{'Text1'}{'Text3'}</div>, {'Text1'}
{'Text2'}
</div>,
<div>
{'Text1'}
{'Text3'}
</div>,
)); ));
it('can explicitly ignore reconnecting different text', () => it('can explicitly ignore reconnecting different text', () =>
@ -2813,33 +2957,74 @@ describe('ReactDOMServerIntegration', () => {
it('can explicitly ignore reconnecting different text in two code blocks', () => it('can explicitly ignore reconnecting different text in two code blocks', () =>
expectMarkupMatch( expectMarkupMatch(
<div suppressHydrationWarning={true}>{'Text1'}{'Text2'}</div>, <div suppressHydrationWarning={true}>
<div suppressHydrationWarning={true}>{'Text1'}{'Text3'}</div>, {'Text1'}
{'Text2'}
</div>,
<div suppressHydrationWarning={true}>
{'Text1'}
{'Text3'}
</div>,
)); ));
}); });
describe('element trees and children', function() { describe('element trees and children', function() {
it('should error reconnecting missing children', () => it('should error reconnecting missing children', () =>
expectMarkupMismatch(<div><div /></div>, <div />)); expectMarkupMismatch(
<div>
<div />
</div>,
<div />,
));
it('should error reconnecting added children', () => it('should error reconnecting added children', () =>
expectMarkupMismatch(<div />, <div><div /></div>)); expectMarkupMismatch(
<div />,
<div>
<div />
</div>,
));
it('should error reconnecting more children', () => it('should error reconnecting more children', () =>
expectMarkupMismatch(<div><div /></div>, <div><div /><div /></div>)); expectMarkupMismatch(
<div>
<div />
</div>,
<div>
<div />
<div />
</div>,
));
it('should error reconnecting fewer children', () => it('should error reconnecting fewer children', () =>
expectMarkupMismatch(<div><div /><div /></div>, <div><div /></div>)); expectMarkupMismatch(
<div>
<div />
<div />
</div>,
<div>
<div />
</div>,
));
it('should error reconnecting reordered children', () => it('should error reconnecting reordered children', () =>
expectMarkupMismatch( expectMarkupMismatch(
<div><div /><span /></div>, <div>
<div><span /><div /></div>, <div />
<span />
</div>,
<div>
<span />
<div />
</div>,
)); ));
it('should error reconnecting a div with children separated by whitespace on the client', () => it('should error reconnecting a div with children separated by whitespace on the client', () =>
expectMarkupMismatch( expectMarkupMismatch(
<div id="parent"><div id="child1" /><div id="child2" /></div>, <div id="parent">
<div id="child1" />
<div id="child2" />
</div>,
// prettier-ignore // prettier-ignore
<div id="parent"><div id="child1" /> <div id="child2" /></div>, // eslint-disable-line no-multi-spaces <div id="parent"><div id="child1" /> <div id="child2" /></div>, // eslint-disable-line no-multi-spaces
)); ));
@ -2848,47 +3033,87 @@ describe('ReactDOMServerIntegration', () => {
expectMarkupMismatch( expectMarkupMismatch(
// prettier-ignore // prettier-ignore
<div id="parent"><div id="child1" /> <div id="child2" /></div>, // eslint-disable-line no-multi-spaces <div id="parent"><div id="child1" /> <div id="child2" /></div>, // eslint-disable-line no-multi-spaces
<div id="parent"><div id="child1" /><div id="child2" /></div>, <div id="parent">
<div id="child1" />
<div id="child2" />
</div>,
)); ));
it('should error reconnecting a div with children separated by different whitespace', () => it('should error reconnecting a div with children separated by different whitespace', () =>
expectMarkupMismatch( expectMarkupMismatch(
<div id="parent"><div id="child1" /> <div id="child2" /></div>, <div id="parent">
<div id="child1" /> <div id="child2" />
</div>,
// prettier-ignore // prettier-ignore
<div id="parent"><div id="child1" /> <div id="child2" /></div>, // eslint-disable-line no-multi-spaces <div id="parent"><div id="child1" /> <div id="child2" /></div>, // eslint-disable-line no-multi-spaces
)); ));
it('can distinguish an empty component from a dom node', () => it('can distinguish an empty component from a dom node', () =>
expectMarkupMismatch( expectMarkupMismatch(
<div><span /></div>, <div>
<div><EmptyComponent /></div>, <span />
</div>,
<div>
<EmptyComponent />
</div>,
)); ));
it('can distinguish an empty component from an empty text component', () => it('can distinguish an empty component from an empty text component', () =>
expectMarkupMatch(<div><EmptyComponent /></div>, <div>{''}</div>)); expectMarkupMatch(
<div>
<EmptyComponent />
</div>,
<div>{''}</div>,
));
it('can explicitly ignore reconnecting more children', () => it('can explicitly ignore reconnecting more children', () =>
expectMarkupMatch( expectMarkupMatch(
<div><div /></div>, <div>
<div suppressHydrationWarning={true}><div /><div /></div>, <div />
</div>,
<div suppressHydrationWarning={true}>
<div />
<div />
</div>,
)); ));
it('can explicitly ignore reconnecting fewer children', () => it('can explicitly ignore reconnecting fewer children', () =>
expectMarkupMatch( expectMarkupMatch(
<div><div /><div /></div>, <div>
<div suppressHydrationWarning={true}><div /></div>, <div />
<div />
</div>,
<div suppressHydrationWarning={true}>
<div />
</div>,
)); ));
it('can explicitly ignore reconnecting reordered children', () => it('can explicitly ignore reconnecting reordered children', () =>
expectMarkupMatch( expectMarkupMatch(
<div suppressHydrationWarning={true}><div /><span /></div>, <div suppressHydrationWarning={true}>
<div suppressHydrationWarning={true}><span /><div /></div>, <div />
<span />
</div>,
<div suppressHydrationWarning={true}>
<span />
<div />
</div>,
)); ));
it('can not deeply ignore reconnecting reordered children', () => it('can not deeply ignore reconnecting reordered children', () =>
expectMarkupMismatch( expectMarkupMismatch(
<div suppressHydrationWarning={true}><div><div /><span /></div></div>, <div suppressHydrationWarning={true}>
<div suppressHydrationWarning={true}><div><span /><div /></div></div>, <div>
<div />
<span />
</div>
</div>,
<div suppressHydrationWarning={true}>
<div>
<span />
<div />
</div>
</div>,
)); ));
}); });

View File

@ -31,7 +31,14 @@ describe('ReactDOMTextComponent', () => {
it('updates a mounted text component in place', () => { it('updates a mounted text component in place', () => {
var el = document.createElement('div'); var el = document.createElement('div');
var inst = ReactDOM.render(<div><span />{'foo'}{'bar'}</div>, el); var inst = ReactDOM.render(
<div>
<span />
{'foo'}
{'bar'}
</div>,
el,
);
let nodes = filterOutComments(ReactDOM.findDOMNode(inst).childNodes); let nodes = filterOutComments(ReactDOM.findDOMNode(inst).childNodes);
let foo = nodes[1]; let foo = nodes[1];
@ -39,7 +46,14 @@ describe('ReactDOMTextComponent', () => {
expect(foo.data).toBe('foo'); expect(foo.data).toBe('foo');
expect(bar.data).toBe('bar'); expect(bar.data).toBe('bar');
inst = ReactDOM.render(<div><span />{'baz'}{'qux'}</div>, el); inst = ReactDOM.render(
<div>
<span />
{'baz'}
{'qux'}
</div>,
el,
);
// After the update, the text nodes should have stayed in place (as opposed // After the update, the text nodes should have stayed in place (as opposed
// to getting unmounted and remounted) // to getting unmounted and remounted)
nodes = filterOutComments(ReactDOM.findDOMNode(inst).childNodes); nodes = filterOutComments(ReactDOM.findDOMNode(inst).childNodes);
@ -51,19 +65,40 @@ describe('ReactDOMTextComponent', () => {
it('can be toggled in and out of the markup', () => { it('can be toggled in and out of the markup', () => {
var el = document.createElement('div'); var el = document.createElement('div');
var inst = ReactDOM.render(<div>{'foo'}<div />{'bar'}</div>, el); var inst = ReactDOM.render(
<div>
{'foo'}
<div />
{'bar'}
</div>,
el,
);
var container = ReactDOM.findDOMNode(inst); var container = ReactDOM.findDOMNode(inst);
let childNodes = filterOutComments(container.childNodes); let childNodes = filterOutComments(container.childNodes);
let childDiv = childNodes[1]; let childDiv = childNodes[1];
inst = ReactDOM.render(<div>{null}<div />{null}</div>, el); inst = ReactDOM.render(
<div>
{null}
<div />
{null}
</div>,
el,
);
container = ReactDOM.findDOMNode(inst); container = ReactDOM.findDOMNode(inst);
childNodes = filterOutComments(container.childNodes); childNodes = filterOutComments(container.childNodes);
expect(childNodes.length).toBe(1); expect(childNodes.length).toBe(1);
expect(childNodes[0]).toBe(childDiv); expect(childNodes[0]).toBe(childDiv);
inst = ReactDOM.render(<div>{'foo'}<div />{'bar'}</div>, el); inst = ReactDOM.render(
<div>
{'foo'}
<div />
{'bar'}
</div>,
el,
);
container = ReactDOM.findDOMNode(inst); container = ReactDOM.findDOMNode(inst);
childNodes = filterOutComments(container.childNodes); childNodes = filterOutComments(container.childNodes);
expect(childNodes.length).toBe(3); expect(childNodes.length).toBe(3);
@ -77,42 +112,71 @@ describe('ReactDOMTextComponent', () => {
* See #9836 tracking whether we'll need to fix this or if it's unnecessary. * See #9836 tracking whether we'll need to fix this or if it's unnecessary.
*/ */
xit( xit('can reconcile text merged by Node.normalize() alongside other elements', () => {
'can reconcile text merged by Node.normalize() alongside other elements',
() => {
var el = document.createElement('div');
var inst = ReactDOM.render(
<div>{'foo'}{'bar'}{'baz'}<span />{'qux'}</div>,
el,
);
var container = ReactDOM.findDOMNode(inst);
container.normalize();
inst = ReactDOM.render(
<div>{'bar'}{'baz'}{'qux'}<span />{'foo'}</div>,
el,
);
container = ReactDOM.findDOMNode(inst);
expect(container.textContent).toBe('barbazquxfoo');
},
);
xit('can reconcile text merged by Node.normalize()', () => {
var el = document.createElement('div'); var el = document.createElement('div');
var inst = ReactDOM.render(<div>{'foo'}{'bar'}{'baz'}</div>, el); var inst = ReactDOM.render(
<div>
{'foo'}
{'bar'}
{'baz'}
<span />
{'qux'}
</div>,
el,
);
var container = ReactDOM.findDOMNode(inst); var container = ReactDOM.findDOMNode(inst);
container.normalize(); container.normalize();
inst = ReactDOM.render(<div>{'bar'}{'baz'}{'qux'}</div>, el); inst = ReactDOM.render(
<div>
{'bar'}
{'baz'}
{'qux'}
<span />
{'foo'}
</div>,
el,
);
container = ReactDOM.findDOMNode(inst);
expect(container.textContent).toBe('barbazquxfoo');
});
xit('can reconcile text merged by Node.normalize()', () => {
var el = document.createElement('div');
var inst = ReactDOM.render(
<div>
{'foo'}
{'bar'}
{'baz'}
</div>,
el,
);
var container = ReactDOM.findDOMNode(inst);
container.normalize();
inst = ReactDOM.render(
<div>
{'bar'}
{'baz'}
{'qux'}
</div>,
el,
);
container = ReactDOM.findDOMNode(inst); container = ReactDOM.findDOMNode(inst);
expect(container.textContent).toBe('barbazqux'); expect(container.textContent).toBe('barbazqux');
}); });
it('can reconcile text from pre-rendered markup', () => { it('can reconcile text from pre-rendered markup', () => {
var el = document.createElement('div'); var el = document.createElement('div');
var reactEl = <div>{'foo'}{'bar'}{'baz'}</div>; var reactEl = (
<div>
{'foo'}
{'bar'}
{'baz'}
</div>
);
el.innerHTML = ReactDOMServer.renderToString(reactEl); el.innerHTML = ReactDOMServer.renderToString(reactEl);
ReactDOM.hydrate(reactEl, el); ReactDOM.hydrate(reactEl, el);
@ -120,7 +184,13 @@ describe('ReactDOMTextComponent', () => {
ReactDOM.unmountComponentAtNode(el); ReactDOM.unmountComponentAtNode(el);
reactEl = <div>{''}{''}{''}</div>; reactEl = (
<div>
{''}
{''}
{''}
</div>
);
el.innerHTML = ReactDOMServer.renderToString(reactEl); el.innerHTML = ReactDOMServer.renderToString(reactEl);
ReactDOM.hydrate(reactEl, el); ReactDOM.hydrate(reactEl, el);
@ -129,7 +199,13 @@ describe('ReactDOMTextComponent', () => {
xit('can reconcile text arbitrarily split into multiple nodes', () => { xit('can reconcile text arbitrarily split into multiple nodes', () => {
var el = document.createElement('div'); var el = document.createElement('div');
var inst = ReactDOM.render(<div><span />{'foobarbaz'}</div>, el); var inst = ReactDOM.render(
<div>
<span />
{'foobarbaz'}
</div>,
el,
);
var container = ReactDOM.findDOMNode(inst); var container = ReactDOM.findDOMNode(inst);
let childNodes = filterOutComments(ReactDOM.findDOMNode(inst).childNodes); let childNodes = filterOutComments(ReactDOM.findDOMNode(inst).childNodes);
@ -144,55 +220,77 @@ describe('ReactDOMTextComponent', () => {
childNodes[1].nextSibling, childNodes[1].nextSibling,
); );
inst = ReactDOM.render(<div><span />{'barbazqux'}</div>, el); inst = ReactDOM.render(
<div>
<span />
{'barbazqux'}
</div>,
el,
);
container = ReactDOM.findDOMNode(inst); container = ReactDOM.findDOMNode(inst);
expect(container.textContent).toBe('barbazqux'); expect(container.textContent).toBe('barbazqux');
}); });
xit( xit('can reconcile text arbitrarily split into multiple nodes on some substitutions only', () => {
'can reconcile text arbitrarily split into multiple nodes on some substitutions only', var el = document.createElement('div');
() => { var inst = ReactDOM.render(
var el = document.createElement('div'); <div>
var inst = ReactDOM.render( <span />
<div> {'bar'}
<span />{'bar'}<span />{'foobarbaz'}{'foo'}{'barfoo'}<span /> <span />
</div>, {'foobarbaz'}
el, {'foo'}
); {'barfoo'}
<span />
</div>,
el,
);
var container = ReactDOM.findDOMNode(inst); var container = ReactDOM.findDOMNode(inst);
let childNodes = filterOutComments(ReactDOM.findDOMNode(inst).childNodes); let childNodes = filterOutComments(ReactDOM.findDOMNode(inst).childNodes);
let textNode = childNodes[3]; let textNode = childNodes[3];
textNode.textContent = 'foo'; textNode.textContent = 'foo';
container.insertBefore( container.insertBefore(
document.createTextNode('bar'), document.createTextNode('bar'),
childNodes[3].nextSibling, childNodes[3].nextSibling,
); );
container.insertBefore( container.insertBefore(
document.createTextNode('baz'), document.createTextNode('baz'),
childNodes[3].nextSibling, childNodes[3].nextSibling,
); );
let secondTextNode = childNodes[5]; let secondTextNode = childNodes[5];
secondTextNode.textContent = 'bar'; secondTextNode.textContent = 'bar';
container.insertBefore( container.insertBefore(
document.createTextNode('foo'), document.createTextNode('foo'),
childNodes[5].nextSibling, childNodes[5].nextSibling,
); );
inst = ReactDOM.render( inst = ReactDOM.render(
<div> <div>
<span />{'baz'}<span />{'barbazqux'}{'bar'}{'bazbar'}<span /> <span />
</div>, {'baz'}
el, <span />
); {'barbazqux'}
container = ReactDOM.findDOMNode(inst); {'bar'}
expect(container.textContent).toBe('bazbarbazquxbarbazbar'); {'bazbar'}
}, <span />
); </div>,
el,
);
container = ReactDOM.findDOMNode(inst);
expect(container.textContent).toBe('bazbarbazquxbarbazbar');
});
xit('can unmount normalized text nodes', () => { xit('can unmount normalized text nodes', () => {
var el = document.createElement('div'); var el = document.createElement('div');
ReactDOM.render(<div>{''}{'foo'}{'bar'}</div>, el); ReactDOM.render(
<div>
{''}
{'foo'}
{'bar'}
</div>,
el,
);
el.normalize(); el.normalize();
ReactDOM.render(<div />, el); ReactDOM.render(<div />, el);
expect(el.innerHTML).toBe('<div></div>'); expect(el.innerHTML).toBe('<div></div>');

View File

@ -329,7 +329,10 @@ describe('ReactDOMTextarea', () => {
expect(function() { expect(function() {
ReactTestUtils.renderIntoDocument( ReactTestUtils.renderIntoDocument(
<textarea>{'hello'}{'there'}</textarea>, <textarea>
{'hello'}
{'there'}
</textarea>,
); );
}).toThrow(); }).toThrow();
@ -337,7 +340,11 @@ describe('ReactDOMTextarea', () => {
var node; var node;
expect(function() { expect(function() {
node = renderTextarea(<textarea><strong /></textarea>); node = renderTextarea(
<textarea>
<strong />
</textarea>,
);
}).not.toThrow(); }).not.toThrow();
expect(node.value).toBe('[object Object]'); expect(node.value).toBe('[object Object]');

View File

@ -594,9 +594,7 @@ describe('ReactErrorBoundaries', () => {
ReactDOM.render(<span>After 1</span>, container1); ReactDOM.render(<span>After 1</span>, container1);
ReactDOM.render(<span>After 2</span>, container2); ReactDOM.render(<span>After 2</span>, container2);
ReactDOM.render( ReactDOM.render(
<ErrorBoundary forceRetry={true}> <ErrorBoundary forceRetry={true}>After 3</ErrorBoundary>,
After 3
</ErrorBoundary>,
container3, container3,
); );
expect(container1.firstChild.textContent).toBe('After 1'); expect(container1.firstChild.textContent).toBe('After 1');
@ -1621,18 +1619,14 @@ describe('ReactErrorBoundaries', () => {
var fail = false; var fail = false;
var container = document.createElement('div'); var container = document.createElement('div');
ReactDOM.render( ReactDOM.render(
<ErrorBoundary> <ErrorBoundary>{getAMixOfNormalAndBrokenRenderElements()}</ErrorBoundary>,
{getAMixOfNormalAndBrokenRenderElements()}
</ErrorBoundary>,
container, container,
); );
expect(container.textContent).not.toContain('Caught an error'); expect(container.textContent).not.toContain('Caught an error');
fail = true; fail = true;
ReactDOM.render( ReactDOM.render(
<ErrorBoundary> <ErrorBoundary>{getAMixOfNormalAndBrokenRenderElements()}</ErrorBoundary>,
{getAMixOfNormalAndBrokenRenderElements()}
</ErrorBoundary>,
container, container,
); );
expect(container.textContent).toBe('Caught an error: Hello.'); expect(container.textContent).toBe('Caught an error: Hello.');
@ -1784,9 +1778,7 @@ describe('ReactErrorBoundaries', () => {
<ErrorBoundary> <ErrorBoundary>
<BrokenComponentDidMountErrorBoundary <BrokenComponentDidMountErrorBoundary
renderError={error => ( renderError={error => (
<div> <div>We should never catch our own error: {error.message}.</div>
We should never catch our own error: {error.message}.
</div>
)} )}
/> />
</ErrorBoundary>, </ErrorBoundary>,

View File

@ -50,11 +50,15 @@ describe('ReactIdentity', () => {
var node1; var node1;
var node2; var node2;
ReactDOM.render( ReactDOM.render(
<Wrapper key="wrap1"><span ref={c => (node1 = c)} /></Wrapper>, <Wrapper key="wrap1">
<span ref={c => (node1 = c)} />
</Wrapper>,
container, container,
); );
ReactDOM.render( ReactDOM.render(
<Wrapper key="wrap2"><span ref={c => (node2 = c)} /></Wrapper>, <Wrapper key="wrap2">
<span ref={c => (node2 = c)} />
</Wrapper>,
container, container,
); );
@ -64,7 +68,11 @@ describe('ReactIdentity', () => {
function renderAComponentWithKeyIntoContainer(key, container) { function renderAComponentWithKeyIntoContainer(key, container) {
class Wrapper extends React.Component { class Wrapper extends React.Component {
render() { render() {
return <div><span ref="span" key={key} /></div>; return (
<div>
<span ref="span" key={key} />
</div>
);
} }
} }
@ -123,7 +131,12 @@ describe('ReactIdentity', () => {
class TestContainer extends React.Component { class TestContainer extends React.Component {
render() { render() {
return <TestComponent>{instance0}{instance1}</TestComponent>; return (
<TestComponent>
{instance0}
{instance1}
</TestComponent>
);
} }
} }
@ -153,7 +166,10 @@ describe('ReactIdentity', () => {
render() { render() {
return ( return (
<div> <div>
<TestComponent>{instance0}{instance1}</TestComponent> <TestComponent>
{instance0}
{instance1}
</TestComponent>
</div> </div>
); );
} }
@ -167,7 +183,12 @@ describe('ReactIdentity', () => {
it('should let text nodes retain their uniqueness', () => { it('should let text nodes retain their uniqueness', () => {
class TestComponent extends React.Component { class TestComponent extends React.Component {
render() { render() {
return <div>{this.props.children}<span /></div>; return (
<div>
{this.props.children}
<span />
</div>
);
} }
} }

View File

@ -195,7 +195,11 @@ describe('ReactMount', () => {
class Component extends React.Component { class Component extends React.Component {
render() { render() {
return <div><div /></div>; return (
<div>
<div />
</div>
);
} }
} }
@ -221,7 +225,11 @@ describe('ReactMount', () => {
class Component extends React.Component { class Component extends React.Component {
render() { render() {
return <div><div /></div>; return (
<div>
<div />
</div>
);
} }
} }

View File

@ -44,13 +44,23 @@ describe('ReactMultiChild', () => {
expect(mockUpdate.mock.calls.length).toBe(0); expect(mockUpdate.mock.calls.length).toBe(0);
expect(mockUnmount.mock.calls.length).toBe(0); expect(mockUnmount.mock.calls.length).toBe(0);
ReactDOM.render(<div><MockComponent /></div>, container); ReactDOM.render(
<div>
<MockComponent />
</div>,
container,
);
expect(mockMount.mock.calls.length).toBe(1); expect(mockMount.mock.calls.length).toBe(1);
expect(mockUpdate.mock.calls.length).toBe(0); expect(mockUpdate.mock.calls.length).toBe(0);
expect(mockUnmount.mock.calls.length).toBe(0); expect(mockUnmount.mock.calls.length).toBe(0);
ReactDOM.render(<div><MockComponent /></div>, container); ReactDOM.render(
<div>
<MockComponent />
</div>,
container,
);
expect(mockMount.mock.calls.length).toBe(1); expect(mockMount.mock.calls.length).toBe(1);
expect(mockUpdate.mock.calls.length).toBe(1); expect(mockUpdate.mock.calls.length).toBe(1);
@ -74,12 +84,22 @@ describe('ReactMultiChild', () => {
expect(mockMount.mock.calls.length).toBe(0); expect(mockMount.mock.calls.length).toBe(0);
expect(mockUnmount.mock.calls.length).toBe(0); expect(mockUnmount.mock.calls.length).toBe(0);
ReactDOM.render(<div><MockComponent /></div>, container); ReactDOM.render(
<div>
<MockComponent />
</div>,
container,
);
expect(mockMount.mock.calls.length).toBe(1); expect(mockMount.mock.calls.length).toBe(1);
expect(mockUnmount.mock.calls.length).toBe(0); expect(mockUnmount.mock.calls.length).toBe(0);
ReactDOM.render(<div><span /></div>, container); ReactDOM.render(
<div>
<span />
</div>,
container,
);
expect(mockMount.mock.calls.length).toBe(1); expect(mockMount.mock.calls.length).toBe(1);
expect(mockUnmount.mock.calls.length).toBe(1); expect(mockUnmount.mock.calls.length).toBe(1);
@ -114,7 +134,9 @@ describe('ReactMultiChild', () => {
expect(mockUnmount.mock.calls.length).toBe(0); expect(mockUnmount.mock.calls.length).toBe(0);
ReactDOM.render( ReactDOM.render(
<WrapperComponent><MockComponent /></WrapperComponent>, <WrapperComponent>
<MockComponent />
</WrapperComponent>,
container, container,
); );
@ -139,12 +161,22 @@ describe('ReactMultiChild', () => {
expect(mockMount.mock.calls.length).toBe(0); expect(mockMount.mock.calls.length).toBe(0);
expect(mockUnmount.mock.calls.length).toBe(0); expect(mockUnmount.mock.calls.length).toBe(0);
ReactDOM.render(<div><MockComponent key="A" /></div>, container); ReactDOM.render(
<div>
<MockComponent key="A" />
</div>,
container,
);
expect(mockMount.mock.calls.length).toBe(1); expect(mockMount.mock.calls.length).toBe(1);
expect(mockUnmount.mock.calls.length).toBe(0); expect(mockUnmount.mock.calls.length).toBe(0);
ReactDOM.render(<div><MockComponent key="B" /></div>, container); ReactDOM.render(
<div>
<MockComponent key="B" />
</div>,
container,
);
expect(mockMount.mock.calls.length).toBe(2); expect(mockMount.mock.calls.length).toBe(2);
expect(mockUnmount.mock.calls.length).toBe(1); expect(mockUnmount.mock.calls.length).toBe(1);
@ -165,9 +197,7 @@ describe('ReactMultiChild', () => {
render() { render() {
return ( return (
<div> <div>
<WrapperComponent> <WrapperComponent>{this.props.children}</WrapperComponent>
{this.props.children}
</WrapperComponent>
</div> </div>
); );
} }
@ -211,9 +241,7 @@ describe('ReactMultiChild', () => {
render() { render() {
return ( return (
<div> <div>
<WrapperComponent> <WrapperComponent>{this.props.children}</WrapperComponent>
{this.props.children}
</WrapperComponent>
</div> </div>
); );
} }

View File

@ -52,11 +52,7 @@ class StatusDisplay extends React.Component {
} }
render() { render() {
return ( return <div>{this.props.contentKey}</div>;
<div>
{this.props.contentKey}
</div>
);
} }
} }
@ -65,10 +61,10 @@ class StatusDisplay extends React.Component {
*/ */
class FriendsStatusDisplay extends React.Component { class FriendsStatusDisplay extends React.Component {
/** /**
* Gets the order directly from each rendered child's `index` field. * Gets the order directly from each rendered child's `index` field.
* Refs are not maintained in the rendered order, and neither is * Refs are not maintained in the rendered order, and neither is
* `this._renderedChildren` (surprisingly). * `this._renderedChildren` (surprisingly).
*/ */
getOriginalKeys() { getOriginalKeys() {
var originalKeys = []; var originalKeys = [];
for (var key in this.props.usernameToStatus) { for (var key in this.props.usernameToStatus) {
@ -117,23 +113,19 @@ class FriendsStatusDisplay extends React.Component {
for (var key in this.props.usernameToStatus) { for (var key in this.props.usernameToStatus) {
var status = this.props.usernameToStatus[key]; var status = this.props.usernameToStatus[key];
children.push( children.push(
!status !status ? null : (
? null <StatusDisplay
: <StatusDisplay key={key}
key={key} ref={key}
ref={key} contentKey={key}
contentKey={key} onFlush={this.verifyPreviousRefsResolved.bind(this, key)}
onFlush={this.verifyPreviousRefsResolved.bind(this, key)} status={status}
status={status} />
/>, ),
); );
} }
var childrenToRender = this.props.prepareChildren(children); var childrenToRender = this.props.prepareChildren(children);
return ( return <div>{childrenToRender}</div>;
<div>
{childrenToRender}
</div>
);
} }
} }

View File

@ -180,18 +180,37 @@ describe('ReactMultiChildText', () => {
}); });
it('should render between nested components and inline children', () => { it('should render between nested components and inline children', () => {
ReactTestUtils.renderIntoDocument(<div><h1><span /><span /></h1></div>); ReactTestUtils.renderIntoDocument(
<div>
<h1>
<span />
<span />
</h1>
</div>,
);
expect(function() { expect(function() {
ReactTestUtils.renderIntoDocument(<div><h1>A</h1></div>); ReactTestUtils.renderIntoDocument(
<div>
<h1>A</h1>
</div>,
);
}).not.toThrow(); }).not.toThrow();
expect(function() { expect(function() {
ReactTestUtils.renderIntoDocument(<div><h1>{['A']}</h1></div>); ReactTestUtils.renderIntoDocument(
<div>
<h1>{['A']}</h1>
</div>,
);
}).not.toThrow(); }).not.toThrow();
expect(function() { expect(function() {
ReactTestUtils.renderIntoDocument(<div><h1>{['A', 'B']}</h1></div>); ReactTestUtils.renderIntoDocument(
<div>
<h1>{['A', 'B']}</h1>
</div>,
);
}).not.toThrow(); }).not.toThrow();
}); });
}); });

View File

@ -52,9 +52,7 @@ describe('rendering React components at document', () => {
<head> <head>
<title>Hello World</title> <title>Hello World</title>
</head> </head>
<body> <body>{'Hello ' + this.props.hello}</body>
{'Hello ' + this.props.hello}
</body>
</html> </html>
); );
} }
@ -83,9 +81,7 @@ describe('rendering React components at document', () => {
<head> <head>
<title>Hello World</title> <title>Hello World</title>
</head> </head>
<body> <body>Hello world</body>
Hello world
</body>
</html> </html>
); );
} }
@ -112,9 +108,7 @@ describe('rendering React components at document', () => {
<head> <head>
<title>Hello World</title> <title>Hello World</title>
</head> </head>
<body> <body>Hello world</body>
Hello world
</body>
</html> </html>
); );
} }
@ -127,9 +121,7 @@ describe('rendering React components at document', () => {
<head> <head>
<title>Hello World</title> <title>Hello World</title>
</head> </head>
<body> <body>Goodbye world</body>
Goodbye world
</body>
</html> </html>
); );
} }
@ -157,9 +149,7 @@ describe('rendering React components at document', () => {
<head> <head>
<title>Hello World</title> <title>Hello World</title>
</head> </head>
<body> <body>{this.props.text}</body>
{this.props.text}
</body>
</html> </html>
); );
} }
@ -194,9 +184,7 @@ describe('rendering React components at document', () => {
<head> <head>
<title>Hello World</title> <title>Hello World</title>
</head> </head>
<body> <body>{this.props.text}</body>
{this.props.text}
</body>
</html> </html>
); );
} }
@ -233,9 +221,7 @@ describe('rendering React components at document', () => {
<head> <head>
<title>Hello World</title> <title>Hello World</title>
</head> </head>
<body> <body>{this.props.text}</body>
{this.props.text}
</body>
</html> </html>
); );
} }
@ -255,9 +241,7 @@ describe('rendering React components at document', () => {
<head> <head>
<title>Hello World</title> <title>Hello World</title>
</head> </head>
<body> <body>Hello world</body>
Hello world
</body>
</html> </html>
); );
@ -279,9 +263,7 @@ describe('rendering React components at document', () => {
<head> <head>
<title>Hello World</title> <title>Hello World</title>
</head> </head>
<body> <body>{'Hello ' + this.props.hello}</body>
{'Hello ' + this.props.hello}
</body>
</html> </html>
); );
} }
@ -308,9 +290,7 @@ describe('rendering React components at document', () => {
<head> <head>
<title>Hello World</title> <title>Hello World</title>
</head> </head>
<body> <body>Hello world</body>
Hello world
</body>
</html> </html>
); );
} }
@ -334,9 +314,7 @@ describe('rendering React components at document', () => {
<head> <head>
<title>Hello World</title> <title>Hello World</title>
</head> </head>
<body> <body>Hello world</body>
Hello world
</body>
</html> </html>
); );
} }
@ -349,9 +327,7 @@ describe('rendering React components at document', () => {
<head> <head>
<title>Hello World</title> <title>Hello World</title>
</head> </head>
<body> <body>Goodbye world</body>
Goodbye world
</body>
</html> </html>
); );
} }
@ -378,9 +354,7 @@ describe('rendering React components at document', () => {
<head> <head>
<title>Hello World</title> <title>Hello World</title>
</head> </head>
<body> <body>{this.props.text}</body>
{this.props.text}
</body>
</html> </html>
); );
} }
@ -416,9 +390,7 @@ describe('rendering React components at document', () => {
<head> <head>
<title>Hello World</title> <title>Hello World</title>
</head> </head>
<body> <body>{this.props.text}</body>
{this.props.text}
</body>
</html> </html>
); );
} }
@ -449,9 +421,7 @@ describe('rendering React components at document', () => {
<head> <head>
<title>Hello World</title> <title>Hello World</title>
</head> </head>
<body> <body>{this.props.text}</body>
{this.props.text}
</body>
</html> </html>
); );
} }
@ -472,9 +442,7 @@ describe('rendering React components at document', () => {
<head> <head>
<title>Hello World</title> <title>Hello World</title>
</head> </head>
<body> <body>Hello world</body>
Hello world
</body>
</html> </html>
); );

View File

@ -81,7 +81,11 @@ describe('ReactDOMServer', () => {
it('should render composite components', () => { it('should render composite components', () => {
class Parent extends React.Component { class Parent extends React.Component {
render() { render() {
return <div><Child name="child" /></div>; return (
<div>
<Child name="child" />
</div>
);
} }
} }
@ -198,7 +202,9 @@ describe('ReactDOMServer', () => {
render() { render() {
return ( return (
<span ref="span" onClick={this.click}>Name: {this.props.name}</span> <span ref="span" onClick={this.click}>
Name: {this.props.name}
</span>
); );
} }
} }
@ -410,7 +416,11 @@ describe('ReactDOMServer', () => {
class TestComponent extends React.Component { class TestComponent extends React.Component {
render() { render() {
return <span><NestedComponent /></span>; return (
<span>
<NestedComponent />
</span>
);
} }
} }
@ -422,7 +432,11 @@ describe('ReactDOMServer', () => {
it('should not put checksum and React ID on text components', () => { it('should not put checksum and React ID on text components', () => {
class TestComponent extends React.Component { class TestComponent extends React.Component {
render() { render() {
return <span>{'hello'} {'world'}</span>; return (
<span>
{'hello'} {'world'}
</span>
);
} }
} }
@ -595,7 +609,9 @@ describe('ReactDOMServer', () => {
}; };
var markup = ReactDOMServer.renderToString( var markup = ReactDOMServer.renderToString(
<ContextProvider><Component /></ContextProvider>, <ContextProvider>
<Component />
</ContextProvider>,
); );
expect(markup).toContain('hello, world'); expect(markup).toContain('hello, world');
}); });

View File

@ -126,7 +126,11 @@ describe('ReactStatelessComponent', () => {
it('should throw when stateless component returns undefined', () => { it('should throw when stateless component returns undefined', () => {
function NotAComponent() {} function NotAComponent() {}
expect(function() { expect(function() {
ReactTestUtils.renderIntoDocument(<div><NotAComponent /></div>); ReactTestUtils.renderIntoDocument(
<div>
<NotAComponent />
</div>,
);
}).toThrowError( }).toThrowError(
'NotAComponent(...): Nothing was returned from render. ' + 'NotAComponent(...): Nothing was returned from render. ' +
'This usually means a return statement is missing. Or, to render nothing, return null.', 'This usually means a return statement is missing. Or, to render nothing, return null.',

View File

@ -78,7 +78,11 @@ describe('ReactTestUtils', () => {
it('can scryRenderedDOMComponentsWithClass with TextComponent', () => { it('can scryRenderedDOMComponentsWithClass with TextComponent', () => {
class Wrapper extends React.Component { class Wrapper extends React.Component {
render() { render() {
return <div>Hello <span>Jim</span></div>; return (
<div>
Hello <span>Jim</span>
</div>
);
} }
} }
@ -93,7 +97,11 @@ describe('ReactTestUtils', () => {
it('can scryRenderedDOMComponentsWithClass with className contains \\n', () => { it('can scryRenderedDOMComponentsWithClass with className contains \\n', () => {
class Wrapper extends React.Component { class Wrapper extends React.Component {
render() { render() {
return <div>Hello <span className={'x\ny'}>Jim</span></div>; return (
<div>
Hello <span className={'x\ny'}>Jim</span>
</div>
);
} }
} }
@ -108,7 +116,11 @@ describe('ReactTestUtils', () => {
it('can scryRenderedDOMComponentsWithClass with multiple classes', () => { it('can scryRenderedDOMComponentsWithClass with multiple classes', () => {
class Wrapper extends React.Component { class Wrapper extends React.Component {
render() { render() {
return <div>Hello <span className={'x y z'}>Jim</span></div>; return (
<div>
Hello <span className={'x y z'}>Jim</span>
</div>
);
} }
} }
@ -210,9 +222,7 @@ describe('ReactTestUtils', () => {
<head ref="head"> <head ref="head">
<title>hello</title> <title>hello</title>
</head> </head>
<body ref="body"> <body ref="body">hello, world</body>
hello, world
</body>
</html> </html>
); );
} }
@ -231,7 +241,11 @@ describe('ReactTestUtils', () => {
}); });
it('can scry with stateless components involved', () => { it('can scry with stateless components involved', () => {
const Stateless = () => <div><hr /></div>; const Stateless = () => (
<div>
<hr />
</div>
);
class SomeComponent extends React.Component { class SomeComponent extends React.Component {
render() { render() {
@ -311,11 +325,7 @@ describe('ReactTestUtils', () => {
it('should throw when attempting to use a React element', () => { it('should throw when attempting to use a React element', () => {
class SomeComponent extends React.Component { class SomeComponent extends React.Component {
render() { render() {
return ( return <div onClick={this.props.handleClick}>hello, world.</div>;
<div onClick={this.props.handleClick}>
hello, world.
</div>
);
} }
} }
@ -336,11 +346,7 @@ describe('ReactTestUtils', () => {
it('should throw when attempting to use a component instance', () => { it('should throw when attempting to use a component instance', () => {
class SomeComponent extends React.Component { class SomeComponent extends React.Component {
render() { render() {
return ( return <div onClick={this.props.handleClick}>hello, world.</div>;
<div onClick={this.props.handleClick}>
hello, world.
</div>
);
} }
} }
@ -403,7 +409,11 @@ describe('ReactTestUtils', () => {
class MyComponent extends React.Component { class MyComponent extends React.Component {
render() { render() {
return <div><input type="text" onChange={onChange} /></div>; return (
<div>
<input type="text" onChange={onChange} />
</div>
);
} }
} }

View File

@ -60,7 +60,11 @@ describe('ReactUpdates', () => {
} }
render() { render() {
return <div>({this.state.x}, {this.state.y})</div>; return (
<div>
({this.state.x}, {this.state.y})
</div>
);
} }
} }
@ -92,7 +96,11 @@ describe('ReactUpdates', () => {
} }
render() { render() {
return <div>({this.props.x}, {this.state.y})</div>; return (
<div>
({this.props.x}, {this.state.y})
</div>
);
} }
} }
@ -125,7 +133,11 @@ describe('ReactUpdates', () => {
} }
render() { render() {
return <div><Child ref="child" x={this.state.x} /></div>; return (
<div>
<Child ref="child" x={this.state.x} />
</div>
);
} }
} }
@ -174,7 +186,11 @@ describe('ReactUpdates', () => {
} }
render() { render() {
return <div><Child ref="child" x={this.state.x} /></div>; return (
<div>
<Child ref="child" x={this.state.x} />
</div>
);
} }
} }
@ -347,7 +363,11 @@ describe('ReactUpdates', () => {
class Top extends React.Component { class Top extends React.Component {
render() { render() {
return <Middle><Bottom /></Middle>; return (
<Middle>
<Bottom />
</Middle>
);
} }
} }
@ -518,7 +538,12 @@ describe('ReactUpdates', () => {
var portal = null; var portal = null;
// If we're using Fiber, we use Portals instead to achieve this. // If we're using Fiber, we use Portals instead to achieve this.
portal = ReactDOM.createPortal(<B ref={n => (b = n)} />, bContainer); portal = ReactDOM.createPortal(<B ref={n => (b = n)} />, bContainer);
return <div>A{this.state.x}{portal}</div>; return (
<div>
A{this.state.x}
{portal}
</div>
);
} }
} }
@ -547,7 +572,11 @@ describe('ReactUpdates', () => {
render() { render() {
updates.push('Outer-render-' + this.state.x); updates.push('Outer-render-' + this.state.x);
return <div><Inner x={this.state.x} ref="inner" /></div>; return (
<div>
<Inner x={this.state.x} ref="inner" />
</div>
);
} }
componentDidUpdate() { componentDidUpdate() {
@ -1152,9 +1181,21 @@ describe('ReactUpdates', () => {
const container = document.createElement('div'); const container = document.createElement('div');
// Mount // Mount
ReactDOM.render(<div><Foo /><Bar /></div>, container); ReactDOM.render(
<div>
<Foo />
<Bar />
</div>,
container,
);
// Root update // Root update
ReactDOM.render(<div><Foo /><Bar /></div>, container); ReactDOM.render(
<div>
<Foo />
<Bar />
</div>,
container,
);
expect(ops).toEqual([ expect(ops).toEqual([
// Mount // Mount
'a: false', 'a: false',
@ -1239,7 +1280,9 @@ describe('ReactUpdates', () => {
ops.push('Foo'); ops.push('Foo');
return ( return (
<div> <div>
<div hidden={true}><Bar /></div> <div hidden={true}>
<Bar />
</div>
<Baz /> <Baz />
</div> </div>
); );
@ -1289,7 +1332,12 @@ describe('ReactUpdates', () => {
this.setState({step: 2}); this.setState({step: 2});
} }
render() { render() {
return <div>Hello {this.props.name}{this.state.step}</div>; return (
<div>
Hello {this.props.name}
{this.state.step}
</div>
);
} }
} }

View File

@ -21,7 +21,11 @@ describe('findDOMNode', () => {
it('findDOMNode should find dom element', () => { it('findDOMNode should find dom element', () => {
class MyNode extends React.Component { class MyNode extends React.Component {
render() { render() {
return <div><span>Noise</span></div>; return (
<div>
<span>Noise</span>
</div>
);
} }
} }

View File

@ -16,11 +16,7 @@ class TextWithStringRef extends React.Component {
render() { render() {
jest.resetModules(); jest.resetModules();
React = require('react'); React = require('react');
return ( return <span ref="foo">Hello world!</span>;
<span ref="foo">
Hello world!
</span>
);
} }
} }

View File

@ -27,11 +27,9 @@ describe('refs-destruction', () => {
render() { render() {
return ( return (
<div> <div>
{this.props.destroy {this.props.destroy ? null : (
? null <div ref="theInnerDiv">Lets try to destroy this.</div>
: <div ref="theInnerDiv"> )}
Lets try to destroy this.
</div>}
</div> </div>
); );
} }

View File

@ -353,7 +353,13 @@ describe('root level refs', () => {
var divInst = null; var divInst = null;
var ref2 = jest.fn(value => (divInst = value)); var ref2 = jest.fn(value => (divInst = value));
result = ReactDOM.render( result = ReactDOM.render(
[<Comp ref={ref} key="a" />, 5, <div ref={ref2} key="b">Hello</div>], [
<Comp ref={ref} key="a" />,
5,
<div ref={ref2} key="b">
Hello
</div>,
],
container, container,
); );

View File

@ -92,11 +92,11 @@ ReactControlledComponent.injection.injectFiberControlledHostComponent(
type DOMContainer = type DOMContainer =
| (Element & { | (Element & {
_reactRootContainer: ?Object, _reactRootContainer: ?Object,
}) })
| (Document & { | (Document & {
_reactRootContainer: ?Object, _reactRootContainer: ?Object,
}); });
type Container = Element | Document; type Container = Element | Document;
type Props = { type Props = {
@ -126,12 +126,14 @@ let selectionInformation: ?mixed = null;
* @internal * @internal
*/ */
function isValidContainer(node) { function isValidContainer(node) {
return !!(node && return !!(
node &&
(node.nodeType === ELEMENT_NODE || (node.nodeType === ELEMENT_NODE ||
node.nodeType === DOCUMENT_NODE || node.nodeType === DOCUMENT_NODE ||
node.nodeType === DOCUMENT_FRAGMENT_NODE || node.nodeType === DOCUMENT_FRAGMENT_NODE ||
(node.nodeType === COMMENT_NODE && (node.nodeType === COMMENT_NODE &&
node.nodeValue === ' react-mount-point-unstable '))); node.nodeValue === ' react-mount-point-unstable '))
);
} }
function getReactRootElementInContainer(container: any) { function getReactRootElementInContainer(container: any) {
@ -148,9 +150,11 @@ function getReactRootElementInContainer(container: any) {
function shouldHydrateDueToLegacyHeuristic(container) { function shouldHydrateDueToLegacyHeuristic(container) {
const rootElement = getReactRootElementInContainer(container); const rootElement = getReactRootElementInContainer(container);
return !!(rootElement && return !!(
rootElement &&
rootElement.nodeType === ELEMENT_NODE && rootElement.nodeType === ELEMENT_NODE &&
rootElement.hasAttribute(ROOT_ATTRIBUTE_NAME)); rootElement.hasAttribute(ROOT_ATTRIBUTE_NAME)
);
} }
function shouldAutoFocusHostComponent(type: string, props: Props): boolean { function shouldAutoFocusHostComponent(type: string, props: Props): boolean {
@ -178,9 +182,10 @@ const DOMRenderer = ReactFiberReconciler({
break; break;
} }
default: { default: {
const container: any = nodeType === COMMENT_NODE const container: any =
? rootContainerInstance.parentNode nodeType === COMMENT_NODE
: rootContainerInstance; ? rootContainerInstance.parentNode
: rootContainerInstance;
const ownNamespace = container.namespaceURI || null; const ownNamespace = container.namespaceURI || null;
type = container.tagName; type = container.tagName;
namespace = getChildNamespace(ownNamespace, type); namespace = getChildNamespace(ownNamespace, type);
@ -673,8 +678,9 @@ function renderSubtreeIntoContainer(
const isRootRenderedBySomeReact = !!container._reactRootContainer; const isRootRenderedBySomeReact = !!container._reactRootContainer;
const rootEl = getReactRootElementInContainer(container); const rootEl = getReactRootElementInContainer(container);
const hasNonRootReactChild = !!(rootEl && const hasNonRootReactChild = !!(
ReactDOMComponentTree.getInstanceFromNode(rootEl)); rootEl && ReactDOMComponentTree.getInstanceFromNode(rootEl)
);
warning( warning(
!hasNonRootReactChild || isRootRenderedBySomeReact, !hasNonRootReactChild || isRootRenderedBySomeReact,
@ -900,8 +906,9 @@ const ReactDOM: Object = {
} else { } else {
if (__DEV__) { if (__DEV__) {
const rootEl = getReactRootElementInContainer(container); const rootEl = getReactRootElementInContainer(container);
const hasNonRootReactChild = !!(rootEl && const hasNonRootReactChild = !!(
ReactDOMComponentTree.getInstanceFromNode(rootEl)); rootEl && ReactDOMComponentTree.getInstanceFromNode(rootEl)
);
// Check if the container itself is a React root node. // Check if the container itself is a React root node.
const isContainerReactRoot = const isContainerReactRoot =
@ -915,9 +922,9 @@ const ReactDOM: Object = {
'was rendered by React and is not a top-level container. %s', 'was rendered by React and is not a top-level container. %s',
isContainerReactRoot isContainerReactRoot
? 'You may have accidentally passed in a React root node instead ' + ? 'You may have accidentally passed in a React root node instead ' +
'of its container.' 'of its container.'
: 'Instead, have the parent component update its state and ' + : 'Instead, have the parent component update its state and ' +
'rerender in order to remove this component.', 'rerender in order to remove this component.',
); );
} }
@ -985,7 +992,7 @@ if (__DEV__) {
'https://fb.me/react-devtools' + 'https://fb.me/react-devtools' +
(protocol === 'file:' (protocol === 'file:'
? '\nYou might need to use a local HTTP server (instead of file://): ' + ? '\nYou might need to use a local HTTP server (instead of file://): ' +
'https://fb.me/react-devtools-faq' 'https://fb.me/react-devtools-faq'
: ''), : ''),
'font-weight:bold', 'font-weight:bold',
); );

View File

@ -8,7 +8,9 @@
import {HostComponent, HostText} from 'shared/ReactTypeOfWork'; import {HostComponent, HostText} from 'shared/ReactTypeOfWork';
import invariant from 'fbjs/lib/invariant'; import invariant from 'fbjs/lib/invariant';
const randomKey = Math.random().toString(36).slice(2); const randomKey = Math.random()
.toString(36)
.slice(2);
const internalInstanceKey = '__reactInternalInstance$' + randomKey; const internalInstanceKey = '__reactInternalInstance$' + randomKey;
const internalEventHandlersKey = '__reactEventHandlers$' + randomKey; const internalEventHandlersKey = '__reactEventHandlers$' + randomKey;

View File

@ -10,8 +10,7 @@
import * as ReactFiberTreeReflection from 'shared/ReactFiberTreeReflection'; import * as ReactFiberTreeReflection from 'shared/ReactFiberTreeReflection';
import * as ReactInstanceMap from 'shared/ReactInstanceMap'; import * as ReactInstanceMap from 'shared/ReactInstanceMap';
// TODO: direct imports like some-package/src/* are bad. Fix me. // TODO: direct imports like some-package/src/* are bad. Fix me.
import * as ReactFiberErrorLogger import * as ReactFiberErrorLogger from 'react-reconciler/src/ReactFiberErrorLogger';
from 'react-reconciler/src/ReactFiberErrorLogger';
import ReactErrorUtils from 'shared/ReactErrorUtils'; import ReactErrorUtils from 'shared/ReactErrorUtils';
import {addUserTimingListener} from 'shared/ReactFeatureFlags'; import {addUserTimingListener} from 'shared/ReactFeatureFlags';

View File

@ -8,8 +8,7 @@
*/ */
// TODO: direct imports like some-package/src/* are bad. Fix me. // TODO: direct imports like some-package/src/* are bad. Fix me.
import ReactDebugCurrentFiber import ReactDebugCurrentFiber from 'react-reconciler/src/ReactDebugCurrentFiber';
from 'react-reconciler/src/ReactDebugCurrentFiber';
import {registrationNameModules} from 'events/EventPluginRegistry'; import {registrationNameModules} from 'events/EventPluginRegistry';
import emptyFunction from 'fbjs/lib/emptyFunction'; import emptyFunction from 'fbjs/lib/emptyFunction';
import warning from 'fbjs/lib/warning'; import warning from 'fbjs/lib/warning';
@ -29,15 +28,9 @@ import {getPropertyInfo, shouldSetAttribute} from '../shared/DOMProperty';
import assertValidProps from '../shared/assertValidProps'; import assertValidProps from '../shared/assertValidProps';
import {DOCUMENT_NODE, DOCUMENT_FRAGMENT_NODE} from '../shared/HTMLNodeType'; import {DOCUMENT_NODE, DOCUMENT_FRAGMENT_NODE} from '../shared/HTMLNodeType';
import isCustomComponent from '../shared/isCustomComponent'; import isCustomComponent from '../shared/isCustomComponent';
import { import {validateProperties as validateARIAProperties} from '../shared/ReactDOMInvalidARIAHook';
validateProperties as validateARIAProperties, import {validateProperties as validateInputProperties} from '../shared/ReactDOMNullInputValuePropHook';
} from '../shared/ReactDOMInvalidARIAHook'; import {validateProperties as validateUnknownProperties} from '../shared/ReactDOMUnknownPropertyHook';
import {
validateProperties as validateInputProperties,
} from '../shared/ReactDOMNullInputValuePropHook';
import {
validateProperties as validateUnknownProperties,
} from '../shared/ReactDOMUnknownPropertyHook';
var { var {
getCurrentFiberOwnerName, getCurrentFiberOwnerName,
@ -86,9 +79,8 @@ if (__DEV__) {
var NORMALIZE_NULL_AND_REPLACEMENT_REGEX = /\u0000|\uFFFD/g; var NORMALIZE_NULL_AND_REPLACEMENT_REGEX = /\u0000|\uFFFD/g;
var normalizeMarkupForTextOrAttribute = function(markup: mixed): string { var normalizeMarkupForTextOrAttribute = function(markup: mixed): string {
const markupString = typeof markup === 'string' const markupString =
? markup typeof markup === 'string' ? markup : '' + (markup: any);
: '' + (markup: any);
return markupString return markupString
.replace(NORMALIZE_NEWLINES_REGEX, '\n') .replace(NORMALIZE_NEWLINES_REGEX, '\n')
.replace(NORMALIZE_NULL_AND_REPLACEMENT_REGEX, ''); .replace(NORMALIZE_NULL_AND_REPLACEMENT_REGEX, '');
@ -184,12 +176,13 @@ if (__DEV__) {
// re-initializing custom elements if they exist. But this breaks // re-initializing custom elements if they exist. But this breaks
// how <noscript> is being handled. So we use the same document. // how <noscript> is being handled. So we use the same document.
// See the discussion in https://github.com/facebook/react/pull/11157. // See the discussion in https://github.com/facebook/react/pull/11157.
var testElement = parent.namespaceURI === HTML_NAMESPACE var testElement =
? parent.ownerDocument.createElement(parent.tagName) parent.namespaceURI === HTML_NAMESPACE
: parent.ownerDocument.createElementNS( ? parent.ownerDocument.createElement(parent.tagName)
(parent.namespaceURI: any), : parent.ownerDocument.createElementNS(
parent.tagName, (parent.namespaceURI: any),
); parent.tagName,
);
testElement.innerHTML = html; testElement.innerHTML = html;
return testElement.innerHTML; return testElement.innerHTML;
}; };

View File

@ -8,15 +8,13 @@
*/ */
// TODO: direct imports like some-package/src/* are bad. Fix me. // TODO: direct imports like some-package/src/* are bad. Fix me.
import ReactDebugCurrentFiber import ReactDebugCurrentFiber from 'react-reconciler/src/ReactDebugCurrentFiber';
from 'react-reconciler/src/ReactDebugCurrentFiber';
import invariant from 'fbjs/lib/invariant'; import invariant from 'fbjs/lib/invariant';
import warning from 'fbjs/lib/warning'; import warning from 'fbjs/lib/warning';
import * as DOMPropertyOperations from './DOMPropertyOperations'; import * as DOMPropertyOperations from './DOMPropertyOperations';
import {getFiberCurrentPropsFromNode} from './ReactDOMComponentTree'; import {getFiberCurrentPropsFromNode} from './ReactDOMComponentTree';
import ReactControlledValuePropTypes import ReactControlledValuePropTypes from '../shared/ReactControlledValuePropTypes';
from '../shared/ReactControlledValuePropTypes';
type InputWithWrapperState = HTMLInputElement & { type InputWithWrapperState = HTMLInputElement & {
_wrapperState: { _wrapperState: {
@ -136,9 +134,8 @@ export function initWrapperState(element: Element, props: Object) {
var defaultValue = props.defaultValue; var defaultValue = props.defaultValue;
var node = ((element: any): InputWithWrapperState); var node = ((element: any): InputWithWrapperState);
node._wrapperState = { node._wrapperState = {
initialChecked: props.checked != null initialChecked:
? props.checked props.checked != null ? props.checked : props.defaultChecked,
: props.defaultChecked,
initialValue: props.value != null ? props.value : defaultValue, initialValue: props.value != null ? props.value : defaultValue,
controlled: isControlled(props), controlled: isControlled(props),
}; };

View File

@ -8,12 +8,10 @@
*/ */
// TODO: direct imports like some-package/src/* are bad. Fix me. // TODO: direct imports like some-package/src/* are bad. Fix me.
import ReactDebugCurrentFiber import ReactDebugCurrentFiber from 'react-reconciler/src/ReactDebugCurrentFiber';
from 'react-reconciler/src/ReactDebugCurrentFiber';
import warning from 'fbjs/lib/warning'; import warning from 'fbjs/lib/warning';
import ReactControlledValuePropTypes import ReactControlledValuePropTypes from '../shared/ReactControlledValuePropTypes';
from '../shared/ReactControlledValuePropTypes';
var { var {
getCurrentFiberOwnerName, getCurrentFiberOwnerName,

View File

@ -10,11 +10,9 @@
import invariant from 'fbjs/lib/invariant'; import invariant from 'fbjs/lib/invariant';
import warning from 'fbjs/lib/warning'; import warning from 'fbjs/lib/warning';
// TODO: direct imports like some-package/src/* are bad. Fix me. // TODO: direct imports like some-package/src/* are bad. Fix me.
import ReactDebugCurrentFiber import ReactDebugCurrentFiber from 'react-reconciler/src/ReactDebugCurrentFiber';
from 'react-reconciler/src/ReactDebugCurrentFiber';
import ReactControlledValuePropTypes import ReactControlledValuePropTypes from '../shared/ReactControlledValuePropTypes';
from '../shared/ReactControlledValuePropTypes';
var {getCurrentFiberStackAddendum} = ReactDebugCurrentFiber; var {getCurrentFiberStackAddendum} = ReactDebugCurrentFiber;
var didWarnValDefaultVal = false; var didWarnValDefaultVal = false;

View File

@ -19,9 +19,8 @@ function getTextContentAccessor() {
if (!contentKey && ExecutionEnvironment.canUseDOM) { if (!contentKey && ExecutionEnvironment.canUseDOM) {
// Prefer textContent to innerText because many browsers support both but // Prefer textContent to innerText because many browsers support both but
// SVG <text> elements don't support innerText even when <div> does. // SVG <text> elements don't support innerText even when <div> does.
contentKey = 'textContent' in document.documentElement contentKey =
? 'textContent' 'textContent' in document.documentElement ? 'textContent' : 'innerText';
: 'innerText';
} }
return contentKey; return contentKey;
} }

View File

@ -6,8 +6,7 @@
*/ */
import {Namespaces} from '../shared/DOMNamespaces'; import {Namespaces} from '../shared/DOMNamespaces';
import createMicrosoftUnsafeLocalFunction import createMicrosoftUnsafeLocalFunction from '../shared/createMicrosoftUnsafeLocalFunction';
from '../shared/createMicrosoftUnsafeLocalFunction';
// SVG temp container for IE lacking innerHTML // SVG temp container for IE lacking innerHTML
let reusableSVGContainer; let reusableSVGContainer;

View File

@ -8,8 +8,7 @@
import emptyFunction from 'fbjs/lib/emptyFunction'; import emptyFunction from 'fbjs/lib/emptyFunction';
import warning from 'fbjs/lib/warning'; import warning from 'fbjs/lib/warning';
// TODO: direct imports like some-package/src/* are bad. Fix me. // TODO: direct imports like some-package/src/* are bad. Fix me.
import ReactDebugCurrentFiber import ReactDebugCurrentFiber from 'react-reconciler/src/ReactDebugCurrentFiber';
from 'react-reconciler/src/ReactDebugCurrentFiber';
const {getCurrentFiberStackAddendum} = ReactDebugCurrentFiber; const {getCurrentFiberStackAddendum} = ReactDebugCurrentFiber;
var validateDOMNesting = emptyFunction; var validateDOMNesting = emptyFunction;

View File

@ -17,10 +17,10 @@ import getVendorPrefixedEventName from './getVendorPrefixedEventName';
var topLevelTypes = { var topLevelTypes = {
topAbort: 'abort', topAbort: 'abort',
topAnimationEnd: getVendorPrefixedEventName('animationend') || 'animationend', topAnimationEnd: getVendorPrefixedEventName('animationend') || 'animationend',
topAnimationIteration: getVendorPrefixedEventName('animationiteration') || topAnimationIteration:
'animationiteration', getVendorPrefixedEventName('animationiteration') || 'animationiteration',
topAnimationStart: getVendorPrefixedEventName('animationstart') || topAnimationStart:
'animationstart', getVendorPrefixedEventName('animationstart') || 'animationstart',
topBlur: 'blur', topBlur: 'blur',
topCancel: 'cancel', topCancel: 'cancel',
topCanPlay: 'canplay', topCanPlay: 'canplay',
@ -81,8 +81,8 @@ var topLevelTypes = {
topTouchEnd: 'touchend', topTouchEnd: 'touchend',
topTouchMove: 'touchmove', topTouchMove: 'touchmove',
topTouchStart: 'touchstart', topTouchStart: 'touchstart',
topTransitionEnd: getVendorPrefixedEventName('transitionend') || topTransitionEnd:
'transitionend', getVendorPrefixedEventName('transitionend') || 'transitionend',
topVolumeChange: 'volumechange', topVolumeChange: 'volumechange',
topWaiting: 'waiting', topWaiting: 'waiting',
topWheel: 'wheel', topWheel: 'wheel',

View File

@ -15,7 +15,7 @@ import getTextContentAccessor from '../client/getTextContentAccessor';
* both its text content and its current position in the DOM. Since the * both its text content and its current position in the DOM. Since the
* browser may natively replace the target node during composition, we can * browser may natively replace the target node during composition, we can
* use its position to find its replacement. * use its position to find its replacement.
* *
* *
*/ */
var compositionState = { var compositionState = {

View File

@ -140,9 +140,10 @@ var SelectEventPlugin = {
nativeEvent, nativeEvent,
nativeEventTarget, nativeEventTarget,
) { ) {
var doc = nativeEventTarget.window === nativeEventTarget var doc =
? nativeEventTarget.document nativeEventTarget.window === nativeEventTarget
: nativeEventTarget.nodeType === DOCUMENT_NODE ? nativeEventTarget.document
: nativeEventTarget.nodeType === DOCUMENT_NODE
? nativeEventTarget ? nativeEventTarget
: nativeEventTarget.ownerDocument; : nativeEventTarget.ownerDocument;
// Track whether all listeners exists for this plugin. If none exist, we do // Track whether all listeners exists for this plugin. If none exist, we do

View File

@ -23,9 +23,9 @@ var WheelEventInterface = {
? event.deltaY ? event.deltaY
: // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive). : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive).
'wheelDeltaY' in event 'wheelDeltaY' in event
? -event.wheelDeltaY ? -event.wheelDeltaY
: // Fallback to `wheelDelta` for IE<9 and normalize (down is positive). : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive).
'wheelDelta' in event ? -event.wheelDelta : 0; 'wheelDelta' in event ? -event.wheelDelta : 0;
}, },
deltaZ: null, deltaZ: null,

View File

@ -23,7 +23,7 @@ import SyntheticUIEvent from './SyntheticUIEvent';
type TouchPropertyKey = 'clientX' | 'clientY' | 'pageX' | 'pageY'; type TouchPropertyKey = 'clientX' | 'clientY' | 'pageX' | 'pageY';
declare class _Touch extends Touch { declare class _Touch extends Touch {
[key: TouchPropertyKey]: number, [key: TouchPropertyKey]: number;
} }
type AxisCoordinateData = { type AxisCoordinateData = {

View File

@ -93,8 +93,9 @@ describe('EnterLeaveEventPlugin', () => {
<div <div
onMouseEnter={() => parentEnterCalls++} onMouseEnter={() => parentEnterCalls++}
ref={node => (parent = node)}> ref={node => (parent = node)}>
{this.props.showChild && {this.props.showChild && (
<div onMouseEnter={() => childEnterCalls++} />} <div onMouseEnter={() => childEnterCalls++} />
)}
</div> </div>
); );
} }

View File

@ -46,7 +46,9 @@ describe('SimpleEventPlugin', function() {
it('A non-interactive tags clicks bubble when disabled', function() { it('A non-interactive tags clicks bubble when disabled', function() {
var element = ReactTestUtils.renderIntoDocument( var element = ReactTestUtils.renderIntoDocument(
<div onClick={onClick}><div /></div>, <div onClick={onClick}>
<div />
</div>,
); );
var child = ReactDOM.findDOMNode(element).firstChild; var child = ReactDOM.findDOMNode(element).firstChild;
@ -56,7 +58,9 @@ describe('SimpleEventPlugin', function() {
it('does not register a click when clicking a child of a disabled element', function() { it('does not register a click when clicking a child of a disabled element', function() {
var element = ReactTestUtils.renderIntoDocument( var element = ReactTestUtils.renderIntoDocument(
<button onClick={onClick} disabled={true}><span /></button>, <button onClick={onClick} disabled={true}>
<span />
</button>,
); );
var child = ReactDOM.findDOMNode(element).querySelector('span'); var child = ReactDOM.findDOMNode(element).querySelector('span');
@ -66,7 +70,9 @@ describe('SimpleEventPlugin', function() {
it('triggers click events for children of disabled elements', function() { it('triggers click events for children of disabled elements', function() {
var element = ReactTestUtils.renderIntoDocument( var element = ReactTestUtils.renderIntoDocument(
<button disabled={true}><span onClick={onClick} /></button>, <button disabled={true}>
<span onClick={onClick} />
</button>,
); );
var child = ReactDOM.findDOMNode(element).querySelector('span'); var child = ReactDOM.findDOMNode(element).querySelector('span');
@ -77,7 +83,9 @@ describe('SimpleEventPlugin', function() {
it('triggers parent captured click events when target is a child of a disabled elements', function() { it('triggers parent captured click events when target is a child of a disabled elements', function() {
var element = ReactTestUtils.renderIntoDocument( var element = ReactTestUtils.renderIntoDocument(
<div onClickCapture={onClick}> <div onClickCapture={onClick}>
<button disabled={true}><span /></button> <button disabled={true}>
<span />
</button>
</div>, </div>,
); );
var child = ReactDOM.findDOMNode(element).querySelector('span'); var child = ReactDOM.findDOMNode(element).querySelector('span');
@ -88,7 +96,9 @@ describe('SimpleEventPlugin', function() {
it('triggers captured click events for children of disabled elements', function() { it('triggers captured click events for children of disabled elements', function() {
var element = ReactTestUtils.renderIntoDocument( var element = ReactTestUtils.renderIntoDocument(
<button disabled={true}><span onClickCapture={onClick} /></button>, <button disabled={true}>
<span onClickCapture={onClick} />
</button>,
); );
var child = ReactDOM.findDOMNode(element).querySelector('span'); var child = ReactDOM.findDOMNode(element).querySelector('span');

View File

@ -146,32 +146,29 @@ describe('SyntheticEvent', () => {
// TODO: reenable this test. We are currently silencing these warnings when // TODO: reenable this test. We are currently silencing these warnings when
// using TestUtils.Simulate to avoid spurious warnings that result from the // using TestUtils.Simulate to avoid spurious warnings that result from the
// way we simulate events. // way we simulate events.
xit( xit('should properly log warnings when events simulated with rendered components', () => {
'should properly log warnings when events simulated with rendered components', spyOn(console, 'error');
() => { var event;
spyOn(console, 'error'); var element = document.createElement('div');
var event; function assignEvent(e) {
var element = document.createElement('div'); event = e;
function assignEvent(e) { }
event = e; var instance = ReactDOM.render(<div onClick={assignEvent} />, element);
} ReactTestUtils.Simulate.click(ReactDOM.findDOMNode(instance));
var instance = ReactDOM.render(<div onClick={assignEvent} />, element); expectDev(console.error.calls.count()).toBe(0);
ReactTestUtils.Simulate.click(ReactDOM.findDOMNode(instance));
expectDev(console.error.calls.count()).toBe(0);
// access a property to cause the warning // access a property to cause the warning
event.nativeEvent; // eslint-disable-line no-unused-expressions event.nativeEvent; // eslint-disable-line no-unused-expressions
expectDev(console.error.calls.count()).toBe(1); expectDev(console.error.calls.count()).toBe(1);
expectDev(console.error.calls.argsFor(0)[0]).toBe( expectDev(console.error.calls.argsFor(0)[0]).toBe(
'Warning: This synthetic event is reused for performance reasons. If ' + 'Warning: This synthetic event is reused for performance reasons. If ' +
"you're seeing this, you're accessing the property `nativeEvent` on a " + "you're seeing this, you're accessing the property `nativeEvent` on a " +
'released/nullified synthetic event. This is set to null. If you must ' + 'released/nullified synthetic event. This is set to null. If you must ' +
'keep the original synthetic event around, use event.persist(). ' + 'keep the original synthetic event around, use event.persist(). ' +
'See https://fb.me/react-event-pooling for more information.', 'See https://fb.me/react-event-pooling for more information.',
); );
}, });
);
it('should warn if Proxy is supported and the synthetic event is added a property', () => { it('should warn if Proxy is supported and the synthetic event is added a property', () => {
spyOn(console, 'error'); spyOn(console, 'error');

View File

@ -3,7 +3,7 @@
* *
* This source code is licensed under the MIT license found in the * This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree. * LICENSE file in the root directory of this source tree.
* *
* @flow * @flow
*/ */

View File

@ -14,8 +14,7 @@ import {
shouldAttributeAcceptBooleanValue, shouldAttributeAcceptBooleanValue,
shouldSetAttribute, shouldSetAttribute,
} from '../shared/DOMProperty'; } from '../shared/DOMProperty';
import quoteAttributeValueForBrowser import quoteAttributeValueForBrowser from '../shared/quoteAttributeValueForBrowser';
from '../shared/quoteAttributeValueForBrowser';
import warning from 'fbjs/lib/warning'; import warning from 'fbjs/lib/warning';
// isAttributeNameSafe() is currently duplicated in DOMPropertyOperations. // isAttributeNameSafe() is currently duplicated in DOMPropertyOperations.

View File

@ -30,23 +30,16 @@ import {
getIntrinsicNamespace, getIntrinsicNamespace,
getChildNamespace, getChildNamespace,
} from '../shared/DOMNamespaces'; } from '../shared/DOMNamespaces';
import ReactControlledValuePropTypes import ReactControlledValuePropTypes from '../shared/ReactControlledValuePropTypes';
from '../shared/ReactControlledValuePropTypes';
import assertValidProps from '../shared/assertValidProps'; import assertValidProps from '../shared/assertValidProps';
import dangerousStyleValue from '../shared/dangerousStyleValue'; import dangerousStyleValue from '../shared/dangerousStyleValue';
import escapeTextContentForBrowser from '../shared/escapeTextContentForBrowser'; import escapeTextContentForBrowser from '../shared/escapeTextContentForBrowser';
import isCustomComponent from '../shared/isCustomComponent'; import isCustomComponent from '../shared/isCustomComponent';
import omittedCloseTags from '../shared/omittedCloseTags'; import omittedCloseTags from '../shared/omittedCloseTags';
import warnValidStyle from '../shared/warnValidStyle'; import warnValidStyle from '../shared/warnValidStyle';
import { import {validateProperties as validateARIAProperties} from '../shared/ReactDOMInvalidARIAHook';
validateProperties as validateARIAProperties, import {validateProperties as validateInputProperties} from '../shared/ReactDOMNullInputValuePropHook';
} from '../shared/ReactDOMInvalidARIAHook'; import {validateProperties as validateUnknownProperties} from '../shared/ReactDOMUnknownPropertyHook';
import {
validateProperties as validateInputProperties,
} from '../shared/ReactDOMNullInputValuePropHook';
import {
validateProperties as validateUnknownProperties,
} from '../shared/ReactDOMUnknownPropertyHook';
var REACT_FRAGMENT_TYPE = var REACT_FRAGMENT_TYPE =
(typeof Symbol === 'function' && (typeof Symbol === 'function' &&
@ -435,9 +428,10 @@ function resolve(
var dontMutate = true; var dontMutate = true;
for (var i = oldReplace ? 1 : 0; i < oldQueue.length; i++) { for (var i = oldReplace ? 1 : 0; i < oldQueue.length; i++) {
var partial = oldQueue[i]; var partial = oldQueue[i];
var partialState = typeof partial === 'function' var partialState =
? partial.call(inst, nextState, element.props, publicContext) typeof partial === 'function'
: partial; ? partial.call(inst, nextState, element.props, publicContext)
: partial;
if (partialState) { if (partialState) {
if (dontMutate) { if (dontMutate) {
dontMutate = false; dontMutate = false;
@ -828,9 +822,8 @@ class ReactDOMServerRenderer {
didWarnDefaultSelectValue = true; didWarnDefaultSelectValue = true;
} }
} }
this.currentSelectValue = props.value != null this.currentSelectValue =
? props.value props.value != null ? props.value : props.defaultValue;
: props.defaultValue;
props = Object.assign({}, props, { props = Object.assign({}, props, {
value: undefined, value: undefined,
}); });

View File

@ -14,11 +14,11 @@ import warnValidStyle from './warnValidStyle';
*/ */
/** /**
* This creates a string that is expected to be equivalent to the style * This creates a string that is expected to be equivalent to the style
* attribute generated by server-side rendering. It by-passes warnings and * attribute generated by server-side rendering. It by-passes warnings and
* security checks so it's not safe to use this value for anything other than * security checks so it's not safe to use this value for anything other than
* comparison. It is only used in DEV for SSR validation. * comparison. It is only used in DEV for SSR validation.
*/ */
export function createDangerousStringForStyles(styles) { export function createDangerousStringForStyles(styles) {
if (__DEV__) { if (__DEV__) {
var serialized = ''; var serialized = '';
@ -45,12 +45,12 @@ export function createDangerousStringForStyles(styles) {
} }
/** /**
* Sets the value for multiple styles on a node. If a value is specified as * Sets the value for multiple styles on a node. If a value is specified as
* '' (empty string), the corresponding style property will be unset. * '' (empty string), the corresponding style property will be unset.
* *
* @param {DOMElement} node * @param {DOMElement} node
* @param {object} styles * @param {object} styles
*/ */
export function setValueForStyles(node, styles, getStack) { export function setValueForStyles(node, styles, getStack) {
var style = node.style; var style = node.style;
for (var styleName in styles) { for (var styleName in styles) {

View File

@ -461,9 +461,10 @@ function makeNativeSimulator(eventType) {
Object.keys(topLevelTypes).forEach(function(eventType) { Object.keys(topLevelTypes).forEach(function(eventType) {
// Event type is stored as 'topClick' - we transform that to 'click' // Event type is stored as 'topClick' - we transform that to 'click'
var convenienceName = eventType.indexOf('top') === 0 var convenienceName =
? eventType.charAt(3).toLowerCase() + eventType.substr(4) eventType.indexOf('top') === 0
: eventType; ? eventType.charAt(3).toLowerCase() + eventType.substr(4)
: eventType;
/** /**
* @param {!Element|ReactDOMComponent} domComponentOrNode * @param {!Element|ReactDOMComponent} domComponentOrNode
* @param {?Event} nativeEventData Fake native event to use in SyntheticEvent. * @param {?Event} nativeEventData Fake native event to use in SyntheticEvent.

View File

@ -106,9 +106,10 @@ function restoreDeletedValuesInNestedArray(
typeof attributeConfig.process === 'function' typeof attributeConfig.process === 'function'
) { ) {
// case: CustomAttributeConfiguration // case: CustomAttributeConfiguration
var nextValue = typeof attributeConfig.process === 'function' var nextValue =
? attributeConfig.process(nextProp) typeof attributeConfig.process === 'function'
: nextProp; ? attributeConfig.process(nextProp)
: nextProp;
updatePayload[propKey] = nextValue; updatePayload[propKey] = nextValue;
} }
removedKeys[propKey] = false; removedKeys[propKey] = false;
@ -123,9 +124,8 @@ function diffNestedArrayProperty(
nextArray: Array<NestedNode>, nextArray: Array<NestedNode>,
validAttributes: AttributeConfiguration, validAttributes: AttributeConfiguration,
): ?Object { ): ?Object {
var minLength = prevArray.length < nextArray.length var minLength =
? prevArray.length prevArray.length < nextArray.length ? prevArray.length : nextArray.length;
: nextArray.length;
var i; var i;
for (i = 0; i < minLength; i++) { for (i = 0; i < minLength; i++) {
// Diff any items in the array in the forward direction. Repeated keys // Diff any items in the array in the forward direction. Repeated keys
@ -350,9 +350,10 @@ function diffProperties(
typeof attributeConfig.process === 'function' typeof attributeConfig.process === 'function'
) { ) {
// case: CustomAttributeConfiguration // case: CustomAttributeConfiguration
var nextValue = typeof attributeConfig.process === 'function' var nextValue =
? attributeConfig.process(nextProp) typeof attributeConfig.process === 'function'
: nextProp; ? attributeConfig.process(nextProp)
: nextProp;
updatePayload[propKey] = nextValue; updatePayload[propKey] = nextValue;
} }
continue; continue;
@ -380,9 +381,10 @@ function diffProperties(
? attributeConfig.diff(prevProp, nextProp) ? attributeConfig.diff(prevProp, nextProp)
: defaultDiffer(prevProp, nextProp)); : defaultDiffer(prevProp, nextProp));
if (shouldUpdate) { if (shouldUpdate) {
nextValue = typeof attributeConfig.process === 'function' nextValue =
? attributeConfig.process(nextProp) typeof attributeConfig.process === 'function'
: nextProp; ? attributeConfig.process(nextProp)
: nextProp;
(updatePayload || (updatePayload = {}))[propKey] = nextValue; (updatePayload || (updatePayload = {}))[propKey] = nextValue;
} }
} else { } else {

View File

@ -37,8 +37,10 @@ import findNumericNodeHandle from './findNumericNodeHandle';
* *
* @abstract * @abstract
*/ */
class ReactNativeComponent<DefaultProps, Props, State> class ReactNativeComponent<DefaultProps, Props, State> extends React.Component<
extends React.Component<Props, State> { Props,
State,
> {
static defaultProps: $Abstract<DefaultProps>; static defaultProps: $Abstract<DefaultProps>;
props: Props; props: Props;
state: State; state: State;

View File

@ -145,10 +145,11 @@ export function receiveTouches(
touches: Array<Object>, touches: Array<Object>,
changedIndices: Array<number>, changedIndices: Array<number>,
) { ) {
var changedTouches = eventTopLevelType === 'topTouchEnd' || var changedTouches =
eventTopLevelType === 'topTouchEnd' ||
eventTopLevelType === 'topTouchCancel' eventTopLevelType === 'topTouchCancel'
? removeTouchesAtIndices(touches, changedIndices) ? removeTouchesAtIndices(touches, changedIndices)
: touchSubsequence(touches, changedIndices); : touchSubsequence(touches, changedIndices);
for (var jj = 0; jj < changedTouches.length; jj++) { for (var jj = 0; jj < changedTouches.length; jj++) {
var touch = changedTouches[jj]; var touch = changedTouches[jj];

View File

@ -30,7 +30,9 @@ export function showDialog(capturedError: CapturedError): boolean {
errorToHandle = error; errorToHandle = error;
try { try {
errorToHandle.message = `${summary}\n\nThis error is located at:${componentStack}`; errorToHandle.message = `${summary}\n\nThis error is located at:${
componentStack
}`;
} catch (e) {} } catch (e) {}
} else if (typeof error === 'string') { } else if (typeof error === 'string') {
errorToHandle = new Error( errorToHandle = new Error(

View File

@ -14,11 +14,9 @@ import emptyObject from 'fbjs/lib/emptyObject';
import invariant from 'fbjs/lib/invariant'; import invariant from 'fbjs/lib/invariant';
// Modules provided by RN: // Modules provided by RN:
import UIManager from 'UIManager'; import UIManager from 'UIManager';
import deepFreezeAndThrowOnMutationInDev import deepFreezeAndThrowOnMutationInDev from 'deepFreezeAndThrowOnMutationInDev';
from 'deepFreezeAndThrowOnMutationInDev';
import * as ReactNativeViewConfigRegistry import * as ReactNativeViewConfigRegistry from './ReactNativeViewConfigRegistry';
from './ReactNativeViewConfigRegistry';
import * as ReactNativeAttributePayload from './ReactNativeAttributePayload'; import * as ReactNativeAttributePayload from './ReactNativeAttributePayload';
import { import {
precacheFiberNode, precacheFiberNode,
@ -132,9 +130,9 @@ const NativeRenderer = ReactFiberReconciler({
// Either way we need to pass a copy of the Array to prevent it from being frozen. // Either way we need to pass a copy of the Array to prevent it from being frozen.
const nativeTags = parentInstance._children.map( const nativeTags = parentInstance._children.map(
child => child =>
(typeof child === 'number' typeof child === 'number'
? child // Leaf node (eg text) ? child // Leaf node (eg text)
: child._nativeTag), : child._nativeTag,
); );
UIManager.setChildren( UIManager.setChildren(

Some files were not shown because too many files have changed in this diff Show More