Commit Graph

252 Commits

Author SHA1 Message Date
Sophie Alpert
5855e9f215 Improve warning message for setState-on-unmounted (#12347)
This is one of the most common warnings people see, and I don't think the old text is especially clear. Improve it.
2018-03-29 16:21:22 +01:00
Dan Abramov
7a833dad95 setState() in componentDidMount() should flush synchronously even with createBatch() (#12466)
* Add a failing test for setState in cDM during batch.commit()

* Copy pasta

* Flush all follow-up Sync work on the committed batch

* Nit: Use performSyncWork

Call performSyncWork right after flushing the batch. Does effectively
the same thing by reusing the existing function.

Also added some comments.

* Delete accidentally duplicated test
2018-03-29 02:41:42 +01:00
Andrew Clark
c44665e832 Fix bug when fatal error is thrown as a result of batch.commit (#12480)
Fixes #12474
2018-03-28 18:18:09 -07:00
Brian Vaughn
61444a415b Updating package versions for release 16.3.0-rc.0 2018-03-27 19:07:53 -07:00
Brian Vaughn
ad5273d348 Call getSnapshotBeforeUpdate before mutation (#12468)
* Call getSnapshotBeforeUpdate in separate traversal, before mutation (aka revert db84b9a) and add unit test.

* Added a new timer to ReactDebugFiberPerf for Snapshot effects
2018-03-27 15:37:13 -07:00
Brian Vaughn
e1a106a071 New commit phase lifecycle: getSnapshotBeforeUpdate (#12404)
* Implemented new getSnapshotBeforeUpdate lifecycle
* Store snapshot value from Fiber to instance (__reactInternalSnapshotBeforeUpdate)
* Use commitAllHostEffects() traversal for getSnapshotBeforeUpdate()
* Added DEV warnings and tests for new lifecycle
* Don't invoke legacy lifecycles if getSnapshotBeforeUpdate() is defined. DEV warn about this.
* Converted did-warn objects to Sets in ReactFiberClassComponent
* Replaced redundant new lifecycle checks in a few methods
* Check for polyfill suppress flag on cWU as well before warning
* Added Snapshot bit to HostEffectMask
2018-03-26 13:28:10 -07:00
Brian Vaughn
02d4e5dd39 Updating package versions for release 16.3.0-alpha.3 2018-03-22 12:41:43 -07:00
Brian Vaughn
c1308adb4b Expanded DEV-only warnings for gDSFP and legacy lifecycles (#12419) 2018-03-22 11:16:54 -07:00
Brian Vaughn
dc48326cd5 Fixed a batched-state update bug with getDerivedStateFromProps (#12408) 2018-03-21 11:42:52 -07:00
Barry Michael Doyle
f9377c1762 Replaced object building loop with Object.assign function (#12414) 2018-03-21 09:45:45 -04:00
Vasiliy
33eddbc0c8 Fix falling in dev mode (#12407)
FiberNode stateNode could be null

So I get TypeError:

```
  at performWorkOnRoot (/tmp/my-project/node_modules/react-dom/cjs/react-dom.development.js:11014:24) TypeError: Cannot read property '_warnedAboutRefsInRender' of null
          at findDOMNode (/tmp/my-project/node_modules/react-dom/cjs/react-dom.development.js:15264:55)
```
2018-03-21 09:41:50 +00:00
Brian Vaughn
3961b8c7e7 Updating package versions for release 16.3.0-alpha.2 2018-03-14 13:23:21 -07:00
Brian Vaughn
bc70441c8b RFC #30: React.forwardRef implementation (#12346)
Added React.forwardRef support to react-reconciler based renders and the SSR partial renderer.
2018-03-14 13:07:58 -07:00
Brian Vaughn
77196100b8 Renamed createRef .value attribute to .current (#12375)
* Renamed createRef .value attribute to .current

* Warn if invalid ref object is passed
2018-03-14 09:43:20 -07:00
Andrew Clark
ad9544f48e Prefix internal context properties with underscore (#12358)
So these aren't mistaken for public properties. Ideally, we'd use
symbols or private fields.
2018-03-12 14:30:47 -07:00
Brandon Dail
280acbcb71 Initialize React prop name/attribute name mapping without Map (#12353)
Using `new Map(iterable)` isn't supported in IE11, so it ends up trying to iterate through an empty map and these attributes don't get defined in properties. Since this is only run once on startup inlining the attributeName array is probably fine.
2018-03-12 17:42:17 +00:00
Sophie Alpert
1d220ce0b7 Bug fix: SSR setState in diff components don't mix (#12323)
Previously, the `queue` and `replace` arguments were leaking across loops even though they should be captured.
2018-03-03 10:27:57 -08:00
Andrew Clark
94518b068b Add stack unwinding phase for handling errors (#12201)
* Add stack unwinding phase for handling errors

A rewrite of error handling, with semantics that more closely match
stack unwinding.

Errors that are thrown during the render phase unwind to the nearest
error boundary, like before. But rather than synchronously unmount the
children before retrying, we restart the failed subtree within the same
render phase. The failed children are still unmounted (as if all their
keys changed) but without an extra commit.

Commit phase errors are different. They work by scheduling an error on
the update queue of the error boundary. When we enter the render phase,
the error is popped off the queue. The rest of the algorithm is
the same.

This approach is designed to work for throwing non-errors, too, though
that feature is not implemented yet.

* Add experimental getDerivedStateFromCatch lifecycle

Fires during the render phase, so you can recover from an error within the same
pass. This aligns error boundaries more closely with try-catch semantics.

Let's keep this behind a feature flag until a future release. For now, the
recommendation is to keep using componentDidCatch. Eventually, the advice will
be to use getDerivedStateFromCatch for handling errors and componentDidCatch
only for logging.

* Reconcile twice to remount failed children, instead of using a boolean

* Handle effect immediately after its thrown

This way we don't have to store the thrown values on the effect list.

* ReactFiberIncompleteWork -> ReactFiberUnwindWork

* Remove startTime

* Remove TypeOfException

We don't need it yet. We'll reconsider once we add another exception type.

* Move replay to outer catch block

This moves it out of the hot path.
2018-02-23 17:38:42 -08:00
Gordon Dent
cf58f296e9 Add test exercising public API to test BeforeInputEventPlugin + FallbackCompositionState (#11849)
* Add test exercising public API to test BeforeInputEventPlugin + FallbackCompositionState

 - I've adopted a similar approach to the existing test for BeforeInputEventPlugin
 - I've simulated events and then assert the event handler for onBeforeInput is fired or not fired based on the test conditions
 - The scenarios are tested against IE11, Webkite and Presto environment simulations
 - I've encorporated what I understand to be the functionality in the FallbackCompositionState test

* Prettier

* Linting fixes

* Remove test for contenteditable in Presto - the contenteditable type is not supported in Presto powered browsers (Opera).

* Remove mention of Presto as this explicit condition is no longer handled in BeforeInputEventPlugin.

We still need to exercise usage of FallbackCompositionState though so let's keep a test where the env does not support Composition and Text events.

* Add tests for envs with only CompositionEvent support

* Remove internal tests no longer needed

* Shorten test case names to satisfy lint rules

* Add tests for onCompositionStart and onCompositionUpdte events

The BeforeInputEventPlugin is responsible for emitting these events so we need to add tests for this. This also ensure we exercise the code path that, L207, that was not previously exercised with the public tests.
2018-02-22 18:27:36 +00:00
Brian Vaughn
e00f8429bc Updating package versions for release 16.3.0-alpha.1 2018-02-12 10:38:24 -08:00
Dan Abramov
467b1034ce Disable for...of by default, rewrite cases where it matters (#12198)
* Add no-for-of lint rule

* Ignore legit use cases of for..of

* Rewrite for..of in source code
2018-02-09 16:11:22 +00:00
Brian Vaughn
d529d2035e Fixed descrepancy between host and class component refs (#12178)
When a ref is removed from a class component, React now calls the previous ref-setter (if there was one) with null. Previously this was the case only for host component refs.

A new test has been added.
2018-02-07 12:13:42 -08:00
C. T. Lin
4a20ff26ec Fix server render async mode (#12173)
* add failed tests for <unstable_AsyncMode> with server rendering

* Fix server render with <unstable_AsyncMode> component

* Merge StrictMode and AsyncMode tests into Modes file
2018-02-07 11:51:53 +00:00
C. T. Lin
18a81a4445 Fix server render strict mode (#12170)
* Fix server render with <StrictMode> component

* add failed tests for <StrictMode> with server rendering
2018-02-07 07:51:13 +00:00
Dominic Gannaway
8dc8f88d5a Adds createRef() as per RFC (#12162)
* Adds createRef() as per RFC
2018-02-06 20:19:49 +00:00
Nicolas Gallagher
3d8f465d99 Revert deprecation warnings for custom event plugin injection (#12167) 2018-02-06 18:39:03 +00:00
Brian Vaughn
f05296baf5 Changed cWM/cWRP/cWU deprecations to low-pri warnings (#12159) 2018-02-05 13:39:07 -08:00
Jordan Tepper
86914cb30a Clearer ssr error message 11902 (#11966)
* Match error message to one in `ReactFiber.js`

* Add undefined/null guard and tests

* Update tests and element check

* Remove beforeEach block
2018-02-05 17:09:09 +00:00
Brian Vaughn
dc271876a2 Pre-release version fix (#12148)
* Ran updated release script to fix deps
* Release script handles prerelease deps correctly
* Update noop-renderer dependencies on reconciler package
2018-02-04 08:54:42 -08:00
Brian Vaughn
8a995f7d56 Updating package versions for release 16.3.0-alpha.0 2018-02-02 12:58:26 -08:00
Brian Vaughn
4eed18dd72 Invoke both legacy and UNSAFE_ lifecycles when both are present (#12134)
* Invoke both legacy and UNSAFE_ lifecycles when both are present

This is to support edge cases with eg create-react-class where a mixin defines a legacy lifecycle but the component being created defines an UNSAFE one (or vice versa).

I did not warn about this case because the warning would be a bit redundant with the deprecation warning which we will soon be enabling. I could be convinced to change my stance here though.

* Added explicit function-type check to SS ReactPartialRenderer
2018-02-01 11:15:57 -08:00
Brian Vaughn
e202f984ea Add react-lifecycles-compat and update tests (#12127)
* Installed react-lifecycles-compat module

* Updated react-lifecycles-compat integration tests to use real polyfill
2018-01-31 10:33:59 -08:00
Andrew Clark
27fe752eea Interactive updates shouldn't flush until the end of the outermost batch
Accounts for the case where an event is dispatched synchronously from
inside another event, like `el.focus`. I've added a test, but in general
we need more coverage around this area.
2018-01-30 23:17:22 -08:00
Andrew Clark
28aa084ad8 Switch to JSX API for context (#12123)
* Switch to JSX API for context

80% sure this will be the final API. Merging this now so we can get this
into the next www sync in preparation for 16.3.

* Promote context to a stable API
2018-01-30 13:06:12 -08:00
Andrew Clark
8a09a2fc53 Interactive updates (#12100)
* Updates inside controlled events (onChange) are sync even in async mode

This guarantees the DOM is in a consistent state before we yield back
to the browser.

We'll need to figure out a separate strategy for other
interactive events.

* Don't rely on flushing behavior of public batchedUpdates implementation

Flush work as an explicit step at the end of the event, right before
restoring controlled state.

* Interactive updates

At the beginning of an interactive browser event (events that fire as
the result of a user interaction, like a click), check for pending
updates that were scheduled in a previous interactive event. Flush the
pending updates synchronously so that the event handlers are up-to-date
before responding to the current event.

We now have three classes of events:

- Controlled events. Updates are always flushed synchronously.
- Interactive events. Updates are async, unless another a subsequent
event is fired before it can complete, as described above. They are
also slightly higher priority than a normal async update.
- Non-interactive events. These are treated as normal, low-priority
async updates.

* Flush lowest pending interactive update time

Accounts for case when multiple interactive updates are scheduled at
different priorities. This can happen when an interactive event is
dispatched inside an async subtree, and there's an event handler on
an ancestor that is outside the subtree.

* Update comment about restoring controlled components
2018-01-29 23:49:10 -08:00
Andrew Clark
3e08e60a34 ReactDOM.flushControlled (#12118)
* ReactDOM.flushControlled

New API for wrapping event handlers that need to fire before React
yields to the browser. Previously we thought that flushSync was
sufficient for this use case, but it turns out that flushSync is only
safe if you're guaranteed to be at the top of the stack; that is, if
you know for sure that your event handler is not nested inside another
React event handler or lifecycle. This isn't true for cases like
el.focus, el.click, or dispatchEvent, where an event handler can be
invoked synchronously from inside an existing stack.

flushControlled has similar semantics to batchedUpdates, where if you
nest multiple batches, the work is not flushed until the end of the
outermost batch. The work is not guaranteed to synchronously flush, as
with flushSync, but it is guaranteed to flush before React yields to
the browser.

flushSync is still the preferred API in most cases, such as inside
a requestAnimationFrame callback.

* Test that flushControlled does not flush inside batchedUpdates

* Make flushControlled a void function

In the future, we may want to return a thenable work object. For now,
we'll return nothing.

* flushControlled -> unstable_flushControlled
2018-01-29 22:36:35 -08:00
Andrew Clark
9ea55516e6 Replace unstable_AsyncComponent with unstable_AsyncMode (#12117)
* Replace unstable_AsyncComponent with Unstable_AsyncMode

Mirrors the StrictMode API and uses the new Mode type of work.

* internalContextTag -> mode

Change this now that we have a better name

* Unstable_ -> unstable_
2018-01-29 19:11:59 -08:00
Brian Vaughn
a7b9f98e7a React lifecycles compat (#12105)
* Suppress unsafe/deprecation warnings for polyfilled components.
* Don't invoke deprecated lifecycles if static gDSFP exists.
* Applied recent changes to server rendering also
2018-01-29 08:06:50 -08:00
Hendrik Liebau
40a9e64e1f Move a comment to its original location (#12103)
`type` was added in #11818 below the comment that belongs to `domNamespace`
2018-01-26 13:34:05 +00:00
Brian Vaughn
6dabfca577 Coalesce lifecycle deprecation warnings until the commit phase (#12084)
Builds on top of PR #12083 and resolves issue #12044.

Coalesces deprecation warnings until the commit phase. This proposal extends the  utility introduced in #12060 to also coalesce deprecation warnings.

New warning format will look like this:
> componentWillMount is deprecated and will be removed in the next major version. Use componentDidMount instead. As a temporary workaround, you can rename to UNSAFE_componentWillMount.
>
> Please update the following components: Foo, Bar
>
> Learn more about this warning here:
> https://fb.me/react-async-component-lifecycle-hooks
2018-01-24 21:41:40 -08:00
Andrew Clark
87ae211ccd New context API (#11818)
* New context API

Introduces a declarative context API that propagates updates even when
shouldComponentUpdate returns false.

* Fuzz tester for context

* Use ReactElement for provider and consumer children

* Unify more branches in createFiberFromElement

* Compare context values using Object.is

Same semantics as PureComponent/shallowEqual.

* Add support for Provider and Consumer to server-side renderer

* Store providers on global stack

Rather than using a linked list stored on the context type. The global
stack can be reset in case of an interruption or error, whereas with the
linked list implementation, you'd need to keep track of every
context type.

* Put new context API behind a feature flag

We'll enable this in www only for now.

* Store nearest provider on context object

* Handle reentrancy in server renderer

Context stack should be per server renderer instance.

* Bailout of consumer updates using bitmask

The context type defines an optional function that compares two context
values, returning a bitfield. A consumer may specify the bits it needs
for rendering. If a provider's context changes, and the consumer's bits
do not intersect with the changed bits, we can skip the consumer.

This is similar to how selectors are used in Redux but fast enough to do
while scanning the tree. The only user code involved is the function
that computes the changed bits. But that's only called once per provider
update, not for every consumer.

* Store current value and changed bits on context object

There are fewer providers than consumers, so better to do this work
at the provider.

* Use maximum of 31 bits for bitmask

This is the largest integer size in V8 on 32-bit systems. Warn in
development if too large a number is used.

* ProviderComponent -> ContextProvider, ConsumerComponent -> ContextConsumer

* Inline Object.is

* Warn if multiple renderers concurrently render the same context provider

Let's see if we can get away with not supporting this for now. If it
turns out that it's needed, we can fall back to backtracking the
fiber return path.

* Nits that came up during review
2018-01-24 19:36:22 -08:00
Brian Vaughn
97e2911508 RFC 6: Deprecate unsafe lifecycles (#12028)
* Added unsafe_* lifecycles and deprecation warnings
If the old lifecycle hooks (componentWillMount, componentWillUpdate, componentWillReceiveProps) are detected, these methods will be called and a deprecation warning will be logged. (In other words, we do not check for both the presence of the old and new lifecycles.) This commit is expected to fail tests.

* Ran lifecycle hook codemod over project
This should handle the bulk of the updates. I will manually update TypeScript and CoffeeScript tests with another commit.
The actual command run with this commit was: jscodeshift --parser=flow -t ../react-codemod/transforms/rename-unsafe-lifecycles.js ./packages/**/src/**/*.js

* Manually migrated CoffeeScript and TypeScript tests

* Added inline note to createReactClassIntegration-test
Explaining why lifecycles hooks have not been renamed in this test.

* Udated NativeMethodsMixin with new lifecycle hooks

* Added static getDerivedStateFromProps to ReactPartialRenderer
Also added a new set of tests focused on server side lifecycle hooks.

* Added getDerivedStateFromProps to shallow renderer
Also added warnings for several cases involving getDerivedStateFromProps() as well as the deprecated lifecycles.
Also added tests for the above.

* Dedupe and DEV-only deprecation warning in server renderer

* Renamed unsafe_* prefix to UNSAFE_* to be more noticeable

* Added getDerivedStateFromProps to ReactFiberClassComponent
Also updated class component and lifecyle tests to cover the added functionality.

* Warn about UNSAFE_componentWillRecieveProps misspelling

* Added tests to createReactClassIntegration for new lifecycles

* Added warning for stateless functional components with gDSFP

* Added createReactClass test for static gDSFP

* Moved lifecycle deprecation warnings behind (disabled) feature flag

Updated tests accordingly, by temporarily splitting tests that were specific to this feature-flag into their own, internal tests. This was the only way I knew of to interact with the feature flag without breaking our build/dist tests.

* Tidying up

* Tweaked warning message wording slightly
Replaced 'You may may have returned undefined.' with 'You may have returned undefined.'

* Replaced truthy partialState checks with != null

* Call getDerivedStateFromProps via .call(null) to prevent type access

* Move shallow-renderer didWarn* maps off the instance

* Only call getDerivedStateFromProps if props instance has changed

* Avoid creating new state object if not necessary

* Inject state as a param to callGetDerivedStateFromProps
This value will be either workInProgress.memoizedState (for updates) or instance.state (for initialization).

* Explicitly warn about uninitialized state before calling getDerivedStateFromProps.
And added some new tests for this change.

Also:
* Improved a couple of falsy null/undefined checks to more explicitly check for null or undefined.
* Made some small tweaks to ReactFiberClassComponent WRT when and how it reads instance.state and sets to null.

* Improved wording for deprecation lifecycle warnings

* Fix state-regression for module-pattern components
Also add support for new static getDerivedStateFromProps method
2018-01-19 09:36:46 -08:00
Nathan Hunzaker
3766a014ae Add media events back to TestUtils.Simulate (#12010)
The TestUtils lost media events when they were pulled out of the
topLevelTypes constant. This commit adds them back by concatenating
the media event keys to the list of top level types.
2018-01-11 21:02:59 -05:00
Dan Abramov
73fa26a88b Drop some top-level events from the list (#11912)
* Drop some top-level events from the list

* Put both whitelists in one file
2018-01-11 18:38:13 -05:00
Semen Zhydenko
5b975411a1 Minor typos fixed (#12005)
* commiting -> committing

* doens't -> doesn't

* interuption -> interruption

* inital -> initial

* statment -> statement
2018-01-11 12:24:49 +00:00
Nathan Hunzaker
982a828844 Add test to ensure checked inputs don't accidentally get value="on" (#12000)
In absence of a value, radio and checkboxes report a value of
"on". Between 16 and 16.2, we assigned a node's value to it's current
value in order to "dettach" it from defaultValue. This had the
unfortunate side-effect of assigning value="on" to radio and
checkboxes

Related issues:
https://github.com/facebook/react/issues/11998
2018-01-09 23:45:29 +00:00
Neil Kistner
e6e393b9c5 Add warning in server renderer if class doesn't extend React.Component (#11993)
* Add warning in server renderer if class doesn't extend React.Component

In dev mode, while server rendering, a warning will be thrown if there is a class that doesn't extend React.Component.

* Use `.toWarnDev` matcher and deduplicate warnings

* Deduplicate client-side warning if class doesn't extend React.Component

* Default componentName to Unknown if null
2018-01-09 16:24:49 +00:00
Andrew Clark
13c5e2b531 Sync scheduling by default, with an async opt-in (#11771)
Removes the `useSyncScheduling` option from the HostConfig, since it's
no longer needed. Instead of globally flipping between sync and async,
our strategy will be to opt-in specific trees and subtrees.
2018-01-08 18:50:02 -08:00
Shi Yan
65aeb70195 Deduplicate warning on invalid callback (#11833) (#11833) 2018-01-07 11:52:52 +00:00
Haisheng Wu
96d7e53e69 topLevelUpdateWarnings is only for dev mode hence not necessary to have extra dev mode check. (#11924) 2018-01-05 18:51:02 +00:00