These are based on the ReactNoop renderer, which we use to test React
itself. This gives library authors (Relay, Apollo, Redux, et al.) a way
to test their components for async compatibility.
- Pass `unstable_isAsync` to `TestRenderer.create` to create an async
renderer instance. This causes updates to be lazily flushed.
- `renderer.unstable_yield` tells React to yield execution after the
currently rendering component.
- `renderer.unstable_flushAll` flushes all pending async work, and
returns an array of yielded values.
- `renderer.unstable_flushThrough` receives an array of expected values,
begins rendering, and stops once those values have been yielded. It
returns the array of values that are actually yielded. The user should
assert that they are equal.
Although we've used this pattern successfully in our own tests, I'm not
sure if these are the final APIs we'll make public.
* Call getSnapshotBeforeUpdate in separate traversal, before mutation (aka revert db84b9a) and add unit test.
* Added a new timer to ReactDebugFiberPerf for Snapshot effects
* 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
Is this necessary? I'd like to use the package in enzyme to avoid having to recopy/paste the symbols for better debugging names, but at hard dep in enzyme proper on a version of react isn't gonna work. This seems safe since nothing explicitly depends on React in here?
* Add a failing test verifying componentInfo is missing
* Pass componentInfo to componentDidCatch and getDerivedStateFromCatch
* Only expect stack in DEV
* Don't pass the stack to getDerivedStateFromCatch()
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)
```
* Add a regression test for the context infinite loop
* Fix the bug
We set .return pointer inside the loop, but the top-level parent-child relationship happens outside.
This ensures the top-level parent's child points to the right copy of the parent.
Otherwise we may end up in a situation where (workInProgress === nextFiber) is never true and we loop forever.
* Support ForwardRef type of work in TestRenderer and ShallowRenderer.
* Release script now updates inter-package dependencies too (e.g. react-test-renderer depends on react-is).
We'll use this in www to test whether the polyfill is better at
scheduling high-pri async work than the native one. My preliminary tests
suggest "yes" but it's hard to say for certain, given how difficult it
is to consistently reproduce the starvation issues we've been seeing.
* Use module pattern so context stack is isolated per renderer
* Unify context implementations
Implements the new context API on top of the existing ReactStack that we
already use for host context and legacy context. Now there is a single
array that we push and pop from.
This makes the interrupt path slightly slower, since when we reset the
unit of work pointer, we have to iterate over the stack (like before)
*and* switch on the type of work (not like before). On the other hand,
this unifies all of the unwinding behavior in the UnwindWork module.
* Add DEV only warning if stack is not reset properly
We have other tests that would have caught this if resuming were enabled
in all cases, but since it's currently only enabled for error
boundaries, the test I've added to prevent a regression is a
bit contrived.
* Context providers and consumers should bail-out on already finished work
Fixes bug where a consumer would re-render even if its props and context
had not changed.
* Encode output as JSON string
* Add weights to random action generator
* Add context to triangle fuzz tester
* Move bailouts to as early as possible
* Bailout if neither context value nor children haven't changed (sCU)
* Change prop type invariant to a DEV-only warning
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.
Changes `createResource` to return an object with `read` and `preload`
methods. Future methods may include `set`, `subscribe`, `invalidate`,
and so on.
* Don't expose ReactGlobalSharedState on React Native renderer
We should just go through the "react" package if need access to this one.
Removed the dependencies in React Native.
* No longer used by InspectorUtils
`oldProps` was null. This went uncaught by the unit tests because
ReactNoop did not use `oldProps` in either `prepareUpdate` or
`completeUpdate`. I added some invariants so we don't regress in
the future.
* 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.
* 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.
If we have multiple RN renderers running simultaneously, we should be able to send a single event to all of them and only if it recognizes the event will it do anything with it. Crucially, this avoids the 'Unsupported top level event type "%s" dispatched' invariant in those cases.
* [experimental] simple-cache-provider
Pushing an early version of this for testing and demonstration purposes.
* Change invariant to DEV-only warning
* Use function overloading for createResource type
Expresses that primitive keys do not require a hash function, but
non-primitive keys do.
* More tests
* Use export *
* Make Record type a disjoint union
* Pass miss argument separate from key to avoid a closure
* Disable DEV-only warnings for RN NativeMethodsMixin/create-react-class
* Tiny bit of cleanup
* Make strict-mode suppression check a little more robust
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.
* add failed tests for <unstable_AsyncMode> with server rendering
* Fix server render with <unstable_AsyncMode> component
* Merge StrictMode and AsyncMode tests into Modes file
* 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
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.
* 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
* 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
* 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
* 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_
* Suppress unsafe/deprecation warnings for polyfilled components.
* Don't invoke deprecated lifecycles if static gDSFP exists.
* Applied recent changes to server rendering also
A new feature flag has been added, debugRenderPhaseSideEffectsForStrictMode. When enabled, StrictMode subtrees will also double-invoke lifecycles in the same way as debugRenderPhaseSideEffects.
By default, this flag is enabled for __DEV__ only. Internally we can toggle it with a GK.
This breaks several of our incremental tests which make use of the noop-renderer. Updating the tests to account for the double-rendering in development mode makes them significantly more complicated. The most straight forward fix for this will be to convert them to be run as internal tests only. I believe this is reasonable since we are the only people making use of the noop renderer.
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
* 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
Added new StrictMode component for enabling async warnings (without enabling async rendering). This component can be used in the future to help with other warnings (eg compilation, Fabric).
Update debugRenderPhaseSideEffects behavior
This feature flag no longer double-invokes componentWillMount, componentWillReceiveProps, componentWillUpdate, or shouldComponentUpdate.
It continues to double-invoke the constructor, render, and setState updater functions as well as the recently added, static getDerivedStateFromProps method
Tests have been updated.
* 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
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.
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
* 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
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.
* Updated misleading error message in production environment when adding ref to a functional component
* Reverted changes to codes.json
* Updated error message
* Warn about spying on the console
* Added suppress warning flag for spyOn(console)
* Nits
* Removed spy-on-console guard
* Fixed a potential source of false-positives in toWarnDev() matcher
Also updated (most of) ReactIncrementalErrorLogging-test.internal to use the new matcher
* Removed unused third param to spyOn
* Improved clarity of inline comments
* Removed unused normalizeCodeLocInfo() method
* enables ctrl + enter for keypress event on browsers other than firefox
* makes comment more descriptive as to affected platforms
* reverting fiber results
* Reset changes to results.json
* Remove old test file
* Add tests in the right place
* Bump deps to Jest 22
* Prevent jsdom from logging intentionally thrown errors
This relies on our existing special field that we use to mute errors.
Perhaps, it would be better to instead rely on preventDefault() directly.
I outlined a possible strategy here: https://github.com/facebook/react/issues/11098#issuecomment-355032539
* Update snapshots
* Mock out a method called by ReactART that now throws
* Calling .click() no longer works, dispatch event instead
* Fix incorrect SVG element creation in test
* Render SVG elements inside <svg> to avoid extra warnings
* Fix range input test to use numeric value
* Fix creating SVG element in test
* Replace brittle test that relied on jsdom behavior
The test passed in jsdom due to its implementation details.
The original intention was to test the mutation method, but it was removed a while ago.
Following @nhunzaker's suggestion, I moved the tests to ReactDOMInput and adjusted them to not rely on implementation details.
* Add a workaround for the expected extra client-side warning
This is a bit ugly but it's just two places. I think we can live with this.
* Only warn once for mismatches caused by bad attribute casing
We used to warn both about bad casing and about a mismatch.
The mismatch warning was a bit confusing. We didn't know we warned twice because jsdom didn't faithfully emulate SVG.
This changes the behavior to only leave the warning about bad casing if that's what caused the mismatch.
It also adjusts the test to have an expectation that matches the real world behavior.
* Add an expected warning per comment in the same test
* Migrated several additional tests to use new .toWarnDev() matcher
* Migrated ReactDOMComponent-test to use .toWarnDev() matcher
Note this test previous had some hacky logic to verify errors were reported against unique line numbers. Since the new matcher doesn't suppor this, I replaced this check with an equivalent (I think) comparison of unique DOM elements (eg div -> span)
* Updated several additional tests to use the new .toWarnDev() matcher
* Updated many more tests to use .toWarnDev()
* Updated several additional tests to use .toWarnDev() matcher
* Updated ReactElementValidator to distinguish between Array and Object in its warning. Also updated its test to use .toWarnDev() matcher.
* Updated a couple of additional tests
* Removed unused normalizeCodeLocInfo() methods
* Migrated several additional tests to use new .toWarnDev() matcher
* Migrated ReactDOMComponent-test to use .toWarnDev() matcher
Note this test previous had some hacky logic to verify errors were reported against unique line numbers. Since the new matcher doesn't suppor this, I replaced this check with an equivalent (I think) comparison of unique DOM elements (eg div -> span)
* Updated several additional tests to use the new .toWarnDev() matcher
* Updated many more tests to use .toWarnDev()
* Added toWarnInDev matcher and connected to 1 test
* Added .toLowPriorityWarnDev() matcher
* Reply Jest spy with custom spy. Unregister spy after toWarnDev() so unexpected console.error/warn calls will fail tests.
* console warn/error throws immediately in tests by default (if not spied on)
* Pass-thru console message before erroring to make it easier to identify
* More robustly handle unexpected warnings within try/catch
* Error message includes remaining expected warnings in addition to unexpected warning
The BeforeInputPlugin dispatches null elements in an array if
composition or beforeInput events are not extracted. This causes a
an extra array allocation, but more importantly creates null states in
later event dispatch methods that are annoying to account for.
This commit makes it so that BeforeInputPlugin never returns a null
element inside an array.
* Add basic snapshot tests to ReactART components (Circle, Rectangle, Wedge)
* More tests on Circle, Rectangle, Wedge
* linc warning fixes
* - remove tests to Wedge component internal function
* More test on Wedge component, update snapshots
* Call and Return components should use ReactElement
ReactChildFiber contains lots of branches that do the same thing for
different child types. We can unify them by having more child types be
ReactElements. This requires that the `type` and `key` fields are
sufficient to determine the identity of the child.
The main benefit is decreased file size, especially as we add more
component types, like context providers and consumers.
This updates Call and Return components to use ReactElement. Portals are
left alone for now because their identity includes the host instance.
* Move server render invariant for call and return types
* Sort ReactElement type checks by most likely
* Performance timeline should skip over call components
Don't think these were intentionally omitted from the blacklist of
component types.
I went ahead and updated getComponentName to include special types, even
though I don't think they're used anywhere right now.
* Remove surrounding brackets from internal display names
* use different eslint config for es6 and es5
* remove confusing eslint/baseConfig.js & add more eslint setting for es5, es6
* more clear way to run eslint on es5 & es6 file
* seperate ESNext, ES6, ES6 path, and use different lint config
* rename eslint config file & update eslint rules
* Undo yarn.lock changes
* Rename a file
* Remove unnecessary exceptions
* Refactor a little bit
* Refactor and tweak the logic
* Minor issues
* fix#11759. false positive warning in IE11 when using React.Fragment
* simplify createElementWithValidation type check
* fix mistake
* Add an explanation
* We shouldn't use `number` for anything else
* Clarify further
* Harden tests around init/addition/update/removal of aliased attributes
I noticed some patterns weren't being tested.
* Call setValueForProperty() for null and undefined
The branching before the call is unnecessary because setValueForProperty() already
has an internal branch that delegates to deleteValueForProperty() for null and
undefined through the shouldIgnoreValue() check.
The goal is to start unifying these methods because their separation doesn't
reflect the current behavior (e.g. for unknown properties) anymore, and obscures
what actually happens with different inputs.
* Inline deleteValueForProperty() into setValueForProperty()
Now we don't read propertyInfo twice in this case.
I also dropped a few early returns. I added them a while ago when we had
Stack-only tracking of DOM operations, and some operations were being
counted twice because of how this code is structured. This isn't a problem
anymore (both because we don't track operations, and because I've just
inlined this method call).
* Inline deleteValueForAttribute() into setValueForAttribute()
The special cases for null and undefined already exist in setValueForAttribute().
* Delete some dead code
* Make setValueForAttribute() a branch of setValueForProperty()
Their naming is pretty confusing by now. For example setValueForProperty()
calls setValueForAttribute() when shouldSetAttribute() is false (!). I want
to refactor (as in, inline and then maybe factor it out differently) the relation
between them. For now, I'm consolidating the callers to use setValueForProperty().
* Make it more obvious where we skip and when we reset attributes
The naming of these methods is still very vague and conflicting in some cases.
Will need further work.
* Rewrite setValueForProperty() with early exits
This makes the flow clearer in my opinion.
* Move shouldIgnoreValue() into DOMProperty
It was previously duplicated.
It's also suspiciously similar in purpose to shouldTreatAttributeValueAsNull()
so I want to see if there is a way to unify them.
* Use more specific methods for testing validity
* Unify shouldTreatAttributeValueAsNull() and shouldIgnoreValue()
* Remove shouldSetAttribute()
Its naming was confusing and it was used all over the place instead of more specific checks.
Now that we only have one call site, we might as well inline and get rid of it.
* Remove unnecessary condition
* Remove another unnecessary condition
* Add Flow coverage
* Oops
* Fix lint (ESLint complains about Flow suppression)
* Fix treatment of Symbol/Function values on boolean attributes
They weren't being properly skipped because of the early return.
I added tests for this case.
* Avoid getPropertyInfo() calls
I think this PR looks worse on benchmarks because we have to read propertyInfo in different places.
Originally I tried to get rid of propertyInfo, but looks like it's important for performance after all.
So now I'm going into the opposite direction, and precompute propertyInfo as early as possible, and then just pass it around.
This way we can avoid extra lookups but keep functions nice and modular.
* Pass propertyInfo as argument to getValueForProperty()
It always exists because this function is only called for known properties.
* Make it clearer this branch is boolean-specific
I wrote this and then got confused myself.
* Memoize whether propertyInfo accepts boolean value
Since we run these checks for all booleans, might as well remember it.
* Fix a crash when numeric property is given a Symbol
* Record attribute table
The changes reflect that SSR doesn't crash with symbols anymore (and just warns, consistently with the client).
* Refactor attribute initialization
Instead of using flags, explicitly group similar attributes/properties.
* Optimization: we know built-in attributes are never invalid
* Use strict comparison
* Rename methods for clarity
* Lint nit
* Minor tweaks
* Document all the different attribute types
* Deduplication of warn selected on option
- Wrote a failing test
- Deduplication when selected is set on option
* Ran yarn preitter
* Fixed PR request
- Moved dedupe test to above
- Moved && case to seperate if to seperate static and dynamic things
- Render'd component twice
* Actually check for deduplication
* Minor nits
* Harden tests around init/addition/update/removal of aliased attributes
I noticed some patterns weren't being tested.
* Call setValueForProperty() for null and undefined
The branching before the call is unnecessary because setValueForProperty() already
has an internal branch that delegates to deleteValueForProperty() for null and
undefined through the shouldIgnoreValue() check.
The goal is to start unifying these methods because their separation doesn't
reflect the current behavior (e.g. for unknown properties) anymore, and obscures
what actually happens with different inputs.
* Inline deleteValueForProperty() into setValueForProperty()
Now we don't read propertyInfo twice in this case.
I also dropped a few early returns. I added them a while ago when we had
Stack-only tracking of DOM operations, and some operations were being
counted twice because of how this code is structured. This isn't a problem
anymore (both because we don't track operations, and because I've just
inlined this method call).
* Inline deleteValueForAttribute() into setValueForAttribute()
The special cases for null and undefined already exist in setValueForAttribute().
* Delete some dead code
* Make setValueForAttribute() a branch of setValueForProperty()
Their naming is pretty confusing by now. For example setValueForProperty()
calls setValueForAttribute() when shouldSetAttribute() is false (!). I want
to refactor (as in, inline and then maybe factor it out differently) the relation
between them. For now, I'm consolidating the callers to use setValueForProperty().
* Make it more obvious where we skip and when we reset attributes
The naming of these methods is still very vague and conflicting in some cases.
Will need further work.
* Rewrite setValueForProperty() with early exits
This makes the flow clearer in my opinion.
* Move shouldIgnoreValue() into DOMProperty
It was previously duplicated.
It's also suspiciously similar in purpose to shouldTreatAttributeValueAsNull()
so I want to see if there is a way to unify them.
* Use more specific methods for testing validity
* Unify shouldTreatAttributeValueAsNull() and shouldIgnoreValue()
* Remove shouldSetAttribute()
Its naming was confusing and it was used all over the place instead of more specific checks.
Now that we only have one call site, we might as well inline and get rid of it.
* Remove unnecessary condition
* Remove another unnecessary condition
* Add Flow coverage
* Oops
* Fix lint (ESLint complains about Flow suppression)
* Remove EventListener fbjs utility
EventListener normalizes event subscription for <= IE8. This is no
longer necessary. element.addEventListener is sufficient.
* Remove an extra allocation for open source bundles
* Split into two functions to avoid extra runtime checks
* Revert unrelated changes
* ValidateDOMNesting tests(#11299)
* Rewrite tests using only public API.
* Modified the tests to prevent duplication of code.
* Code review changes implemented.
* Removed the .internal from the test file name as
its now written using public APIs.
* Remove mutation
* Remove unnecessary argument
Now that we pass warnings, we don't need to pass a boolean.
* Move things around a bit, and add component stack assertions
* Fix autoFocus for hydration content when it is mismatched
* Add a test for mismatched content
* Fix a test for production
* Fix a spec description and verify console.error output
* Run prettier
* finalizeInitialChildren always returns `true`
* Revert "finalizeInitialChildren always returns `true`"
This reverts commit 58edd22804.
* Add a TODO comment
* Update ReactServerRendering-test.js
* Update ReactServerRendering-test.js
* Rewrite the comment
* Ensure value and defaultValue do not assign functions and symbols
* Eliminate assignProperty method from ReactDOMInput
* Restore original placement of defaultValue reservedProp
* Reduce branching. Make assignment more consistent
* Control for warnings in symbol/function tests
* Add boolean to readOnly assignments
* Tweak the tests
* Invalid value attributes should convert to an empty string
* Revert ChangeEventPlugin update. See #11746
* Format
* Replace shouldSetAttribute call with value specific type check
DOMProperty.shouldSetAttribute runs a few other checks that aren't
appropriate for determining if a value or defaultValue should be
assigned on an input. This commit replaces that call with an input
specific check.
* Remove unused import
* Eliminate unnecessary numeric equality checks (#11751)
* Eliminate unnecessary numeric equality checks
This commit changes the way numeric equality for number inputs works
such that it compares against `input.valueAsNumber`. This eliminates
quite a bit of branching around numeric equality.
* There is no need to compare valueAsNumber
* Add test cases for empty string to 0.
* Avoid implicit boolean JSX props
* Split up numeric equality test to isolate eslint disable command
* Fix typo in ReactDOMInput test
* Add todos
* Update the attribute table
I updated ReactDOMInput.synchronizeDefaultValue such that it assignes
the defaultValue property instead of the value attribute. I never
followed up on the ChangeEventPlugin's on blur behavior.
* Inline HTML and SVG configs into DOMProperty
* Replace invariants with warnings
These invariants can only happen if *we* mess up, and happen during init time.
So it's safe to make these warnings, as they would fail the tests anyway.
* Clearer variable naming
* Use defaultValue instead of setAttribute('value')
This commit replaces the method of synchronizing an input's value
attribute from using setAttribute to assigning defaultValue. This has
several benefits:
- Fixes issue where IE10+ and Edge password icon disappears (#7328)
- Fixes issue where toggling input types hides display value on dates
in Safari (unreported)
- Removes mutationMethod behaviors from DOMPropertyOperations
* initialValue in Input wrapperState is always a string
* The value property is assigned before the value attribute. Fix related tests.
* Remove initial value tests in ReactDOMInput
I added these tests after removing the `value` mutation
method. However they do not add any additional value over existing
tests.
* Improve clarity of value checks in ReactDOMInput.postMountWrapper
* Remove value and defaultValue from InputWithWrapperState type
They are already included in the type definition for HTMLInputElement
* Inline stringification of value in ReactDOMInput
Avoids eagier stringification and makes usage more consistent.
* Use consistent value/defaultValue presence in postMountHook
Other methods in ReactDOMInput check for null instead of
hasOwnProperty.
* Add missing semicolon
* Remove unused value argument in ReactDOMInput test
* Address cases where a value switches to undefined
When a controlled input value switches to undefined, it reverts back
to the initial state of the controlled input.
We didn't have test coverage for this case, so I've added two describe
blocks to cover both null and undefined.
* Test: create TapEventPlugin-test
* move TapEventPlugin to TapEventPlugin-test.internal.js from ReactBrowserEventEmitter-test.internal.js
* Prittier: run prittier
* run prittier
* Fix: fix CI test error
fix CI test error by lint
* Test: remove TapEventPlugin test code
* remove TapEventPlugin test code from ReactBrowserEventEmitter-test.internal.js
* Use `this` inside invokeGuardedCallback
It's slightly odd but that's exactly how our www fork works.
Might as well do it in the open source version to make it clear we rely on context here.
* Move invokeGuardedCallback into a separate file
This lets us introduce forks for it.
* Add a www fork for invokeGuardedCallback
* Fix Flow
* WIP:use public API
* ReactPortal shifted to shared:all passed
* wrote createPortal method for ReactNoop.(#11299)
* imported ReactNodeList type into ReactNoop.(#11299)
* createPortal method implemented.(#11299)
* exec yarn prettier-all.(#11299)
* Unify the way we fork modules
* Replace rollup-plugin-alias with our own plugin
This does exactly what we need and doesn't suffer from https://github.com/rollup/rollup-plugin-alias/issues/34.
* Move the new plugin to its own file
* Rename variable for consistency
I settled on calling them "forks" since we already have a different concept of "shims".
* Move fork config into its own file
* Rewrite SelectEventPlugin-test to test behavior using Public API
* Minor refactor
* Make sure that we test that "focus" event is ignored
Use newer API when creating events
* Rewrote the other test to use Public API as well
* Tweak the test
* Remove -internal suffix
* Oops
* Warn if `document` is missing by the time invokeGuardedCallback runs in DEV
* Typo
* Add a comment
* Use invariant() instead
* Create event immediately for clarity
* rewrite two phase traversal tests with public APIs
* rewrite enter/leave tests
* lift render into beforeEach, organise variables
* move getLowestCommonAncestor test
* remove internal tree traversal test
* fix linter errors
* move creation of outer nodes into {before,after}Each
* explain why getLowestCommonAncestor test was moved
* remove unnessecary ARG and ARG2 token
these were used for testing the internal API to simulate synthetic
events passed to traverseEnterLeave. since we're now dealing with
actual synthetic events we can remove them.
* run prettier
In the current implementation, pendingProps is null if there are no new
props since the last commit. When that happens, we bail out and reuse
the current props.
But it makes more sense to always set pendingProps to whatever the next
props will be. In other words, pendingProps is never null: it points to
either new props, or to the current props. Modeling it this way lets us
delete lots of code branches and is easier to reason about bail outs:
just compare the pending props to the current props.
API for batching top-level updates and deferring the commit.
- `root.createBatch` creates a batch with an async expiration time
associated with it.
- `batch.render` updates the children that the batch renders.
- `batch.then` resolves when the root has completed.
- `batch.commit` synchronously flushes any remaining work and commits.
No two batches can have the same expiration time. The only way to
commit a batch is by calling its `commit` method. E.g. flushing one
batch will not cause a different batch to also flush.
* Move ReactFiberTreeReflection to react-reconciler/reflection #11659
* Use * for react-reconciler
We don't know the latest local version, and release script currently doesn't bump deps automatically.
* Remove unused field
* Use CommonJS in entry point for consistency
* Undo the CommonJS change
I didn't realize it would break the build.
* Record sizes
* Remove reconciler fixtures
They're unnecessary now that we run real tests on reconciler bundles.