ReactTools is deprecated, it doesn't belong at the root of the project. We'll remove it after 0.14 but for now this moves it so that it's contained and not intermixed with the rest of the project. The currect behavior of copying src/ into the package is maintained.
This ensures that we can consume code from npm that has our process.env pattern. Unfortunately we'll run the same transform on minified builds but it's pretty quick.
This reworks a few things in building and distributing React. The biggest change is using fbjs to share dependencies with other libraries. We're also using Gulp for some build steps.
With this, ReactMultiChild handles all of the children-related operations for ReactDOMComponent so that we don't process operations out of order. This is necessary because ReactMultiChild does its own batching so there's no way without its cooperation to get the timing right here.
Ideally we'll factor this logic out a bit better in subsequent updates but this is the simplest way to fix#1232 which has embarrassingly been open for over a year.
I'm proposing these changes because I found some repetition / lack of
clarity and some language that suggested that you could mutate
`this.state` directly.
Rely on jest for now until we get a better and less hacky solution to running tests in the browser, probably a totally different test suite with different behavior/goals.
I came across an issue on a React project where I needed to programatically set the default value of an input as the result of an async call. (I was prepopulating a zip code field from the Google Maps Geocoding API). It didn't work when I passed in an updated defaultValue prop, until I came across this StackOverflow: http://stackoverflow.com/questions/30146105/react-input-defaultvalue-doesnt-update-with-state. I was able to get it to do what I wanted by passing in the value prop instead.
The addons module warning is currently causing issues with babel/JSPM due to the warning message getting parsed as a require statement. Adding a break using string concatenation appears to prevent any issues.
Example error using JSPM:
```
Error loading "react-addons-{addon}" from...
```
- Add missing object-assign dependency
- Add batchedUpdates to ReactDOMClient, rename the two addons to `unstable_`
- Delete react/addons/* (leaving react/addons with a slightly updated warning)
- Add README.md, LICENSE, PATENTS to each addons package
Changes:
- moves after_script to script
- adds `set -e`
- creates a seperate matrix 'build'
Way at the bottom of the travis output:
```
1571: curl: (26) couldn't open file "build/react.tgz"
```
This seems to be broken since 12c9fee94e
No reason to limit at 100. I can't imagine a reasonable tree with depth over 10,000 but that should still be small enough to "catch infinite loops" quickly.
This hack allow us to get rid of the stateful module ReactLifeCycle since
we can infer the value of isMounted even without it. This gets rid of
the try/catch which is deopting all mountComponent calls.
As a next step we could deprecate isMounted completely and avoid stateful
APIs. Since it can be easily simulated if you truly need it.
Since I fixed the server-side rendering it is now possible to trigger these
callbacks on the client alone. They will still be queued up on the server
but they are never executed.
This allows updates to be enqueued during render. setState in
componentWillMount will still be collected as part of the first pass so
if nothing else get added as pending, they won't trigger a second rerender.
This allow us to get rid of one more stateful special case.
This simply ignores any enqueued actions. This means that we don't have to have special logic for componentWillMount. It is just that those updates are never enqueued.
This was used for any invariant that was subsequently removed. It turns
out that this is completely unnecessary now. Any setState calls will
enqueue and update and the component added to the update queue. However,
since the pending fields are reset after componentWillUnmount, any update
will still be ignored.
It was impossible to get here because if you enqueue something
Also ensure that they're only used in DEV because we will be reading
state that is DEV only here.
This should only be used for tracking string refs. For that purpose, we
need a single central stateful module that is coupled to createElement.
Which is why it needs to live in isomorphic.
Eventually this will go away completely.
This decouples the stateful imperative API from the class creation.
Instead, they get injected into the class from the renderer. Stateful
modules should always be injected.
As a convenience, just like props/context/refs, we set it up after
construction using mutation. That way it is optional to pass it along
the super call constructor chain.
We won't be able to support this after DOM-components-as-refs but we don't expect many people to be passing DOM components to this function anyway, and it should be fairly straightforward for people to clean up failing unit tests using this function.
(This module also isn't public API and never has been.)
We won't be able to support this after DOM-components-as-refs but we don't expect many people to be passing DOM components to this function anyway, and it should be fairly straightforward for people to clean up failing unit tests using this function.
Squashed commit:
[4564e55] Ensures we don't need to update this page for every release.
[b0d60f9] update script sources to be even with the example file in reactjs/react-tutorial repo
This is kind of a confusing place for it but it is intimitely tied to the
update life cycle which is what the update queue is about.
This kills some dependencies from isomorphic to the renderer.
We keep track of the fact that something is rendering for a bunch of
warnings. (ReactCurrentOwner.current !== null)
Once we get rid of owner for string refs, I'll convert those to something
like "isRendering" instead. The interesting part is that feature `__DEV__`
only. It is only used for warnings. Except for this case.
This means that we can get rid of the special case for the isRendering
stack on in prod.
- babel-eslint ^3.1.14 fixesbabel/babel-eslint#120
- babel updated from ^5.3.3 to ^3.5.5, which changes stuff, I guess
- eslint updated from ^0.21.2 to ^0.22.1, which makes `no-shadow` also
check class declarations
In xml node name casing is exactly the same as the node was originally named.
Make sure to convert node and tag names to lower case before making any node
and tag name checks.
Fixes#3960.
spicyj noticed newer versions of babel-eslint seemed not to error on
no-unused-vars, and I was able to repro. It seems like something broke
between 3.1.9 and 3.1.10. (Smaller repro case and babel-eslint bug
report to come)
His commit failed on travis, but not on his local machine:
https://travis-ci.org/facebook/react/jobs/65468729
> The two callers of this function have different warning configs
> internally (static_upstream/core/createWarning.js) so we can't sync it
> like this without changing behavior. We should just split this out
> into two separate warning calls probably – this code is a little
> overabstracted.
https://github.com/facebook/react/pull/4021#discussion_r31690020
@spicyj
I think completely removing warnAndMonitorForKeyUse is a bit difficult, without
duplicating a ton of code. This at least ensures that the format string passed
to `warning` is unique. Plus, because the FB internal code in question only
matches the beginning of the format string, I think there should be zero
internal changes that need to be made to support this refactor.
The `warning` implementation checked that the message is long enough to
be useful. See commit f5038829d for more information.
It makes more sense to move this into a lint rule, and also to apply it
for both `warning` and `invariant`. We can safely remove stuff from the
`warning` implementation as we replace the function internally anyways.
https://github.com/facebook/react/pull/4021#issuecomment-108694976
@spicyj
The wording for an incorrect number of arguments based on counting %s
substitutions. The previous wording was backwards and a bit yoda-like
leading to possible ambiguity.
This should contain all the rules we probably want to use, except
react/wrap-multilines, which requires a larger codemod, and would
clutter this commit.
See #2869
Checks that the *second* argument of warning and invariant are a literal
string, or a concatination of literal strings, and that the number of
arguments is correct based on the number of %s substrings.
This commit also fixes a few places where the existing code had broken
error messages!
The rule itself is pretty straightforward, although adding the tests
ended up being a bit painful, as eslint-tester depends on mocha, and
therefore needs to be run in a separate grunt task.
This is a machine-generated codemod, but it's pretty safe since it was
generated by hooking into eslint's own report.
A few files had to be touched up by hand because there were existing
formatting issues with nested arrays/objects:
src/shared/utils/__tests__/OrderedMap-test.js
src/shared/utils/__tests__/Transaction-test.js
src/shared/utils/__tests__/traverseAllChildren-test.js
src/isomorphic/children/__tests__/ReactChildren-test.js
Introducing: a really lame version of composite components, right inside of ReactDOMComponent!
Now ReactDOMInput isn't an actual component. This brings us closer to exposing DOM nodes as refs.
Closes#3971.
> After #3968, the next thing we should do is start linting our tests.
> Historically we've ignored them due to lack of parser compatibility.
> But that shouldn't be a problem anymore. We may want to integrate
> https://www.npmjs.com/package/eslint-plugin-react to more aggressively
> lint our JSX in tests.
I understand this diff touches a lot of stuff, so I tried to keep it to
a near-minimal set of changes to make eslint happy.
- Removes esprima-fb dependency
- Tightens up eslintrc with some minor rules we were pretty-much
following anyways.
- Adds pretty colors to the `grunt lint` output
- Breaks block-scoped-var :(
Follow-up to #3963. (Returning an Error wasn't useful; it just caused a later error when actually using it because type checkers need to be functions.)
Chrome allowed some of these to be 'null' (allow `node.challenge` etc),
but FF didn't work. This will tell React to use node.setAttribute() to
set these values.
Tested in FF, Chrome, Safari. <keygen> isn't supported on IE.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/keygen
The code sample in tip 18 in the docs contained a call to the
.getDOMNode() method which has been deprecated. The method call was
replaced with a call to React.findDOMNode(), which is the preferred way
of getting DOM nodes from a ref.
This heuristic isn't great because it relies on inspecting deep children which aren't guaranteed to be React elements. In particular, this was causing stack overflows in a component we had that used a *DOM node* as children, like `<DOMContainer>{node}</DOMContainer>`.
This reverts commits:
0a3aa8493a64c9d9d7620c58f4f6b18cf226e442086636747f
The new folder structure is organized around major packages that are expected to ship separately in some form.
`/isomorphic`
I moved classic/modern and children utils into a directory called "isomorphic" with the main export being ReactIsomorphic. This will eventually become the "react" package.
This includes all the dependencies that you might need to create a component without dependencies on the renderer/reconciler.
The rest moves into decoupled renderers.
`/renderers/dom/client` - This is the main renderer for DOM.
`/renderers/dom/server` - This is the server-side renderer for HTML strings.
`/addons` and `/test` - Same as before for now.
You're not supposed to take on a dependency inside another package.
Shared code is organized into a "shared" directory which is intended to support all the packages in that subdirectory. Meaning that once we swap to CommonJS modules, the only time you should use `..` is to target `../shared/` or `../../shared`.
E.g. `/shared/` is common utils that are used by everything.
`/renderers/shared/` is code that is shared by all renderers, such as the main reconciliation algorithm.
Shared code will likely be copied into each package rather than referenced. This allow us to have separate state and allow inlining and deadcode elimination.
Size comparison:
```
raw gz Compared to master @ 6ed98ec0c8
= = build/JSXTransformer.js
-15736 -3247 build/react-with-addons.js
+287 +7 build/react-with-addons.min.js
-14412 -2887 build/react.js
+274 +15 build/react.min.js
```
Differences mostly look to be various bits of whitespace that Babel ends up removing during its transforms (https://gist.github.com/spicyj/21ef31f4d95fb7a58daf). In minified files, mostly additions of `"use strict";`.
My old code here didn't work properly -- for a string child, getIteratorFn would return an iterator that gave each character as its own string, and we'd attempt to loop over that too.
Tests now work in Chrome again.
Also when reusing elements in multiple contexts -- before we were mutating each element to indicate its validity; now we mutate the array containing it (which we create, in the case of rest-arg children).
Fixes#2496. Fixes#3348.
Updated documentation to reflect that using React.cloneElement is the new way to copy an element and preserve `key` and `ref`.
Fixes#3432, closes#3447.
Update links to use https:// where it is supported. There's probably a lot
more that could be fixed, but these are the core ones I found (especially
the download links in order to prevent MITM attacks). Note that there are
some fb.me links that will redirect to http:// even while accessed over
https://, but this seemed like the best way to fix those for now.
NOTE: Only non-third-party files were modified. There are references to
http:// URLs in vendored/third-party files, but seems appropriate to fix
upstream for those rather than editing the files.
Also, copy one image locally to the blog, as it was hotlinking to a site
that did not support https://.
Last, use youtube-nocookie.com instead of youtube.com for video embeds,
as the former doesn't try to set a cookie on load (privacy enhancement).
I'm not super attached to this, but this feels cleaner to me. Might even be faster since flattenChildren doesn't use the index. Probably no change though.
If there are no listeners for `onSelect` yet, do not extract events. This way we can avoid issues where listeners have been set up for some event dependencies for `SelectEventPlugin`, but not all.
For instance, if `topMouseDown` has been registered but not `topMouseUp`, event extraction will set the `mouseDown` flag to true but never unset it. This leads to bugs when `onSelect` is registered and should be firing during normal key behavior. Since no `topMouseUp` has yet occurred to unset the flag, `onSelect` fails to fire.
When the style property existed, but was set to null, `this._previousStyleCopy`
was not set back to `null` causing an old value to persist. This broke setting
the style to `null` the next time.
Fixes#3606.
As far as I can tell, this is almost equivalent and is simpler. When a component's componentDidMount is called, all the listeners for that subtree will have been attached which I think is all that matters.
All testes successfully completed.
- for-in in browsers is slow, i replaced him by Object.keys + for(array)
- simple check of lengths let us not iterate if not same
- now we dont need to test for B's keys missing from A, because if length's is same and prev check success - objB hasn't more keys
- micro optimize: calling objB.hasOwnProperty
- micro optimize: replaced !objA || !obj for more speedy check === null
#inspiredby https://github.com/jurassix/react-immutable-render-mixin/pull/4
$REACT_WEBSITE_BRANCH in https://travis-ci.org/facebook/react/settings/env_vars now needs to point to the stable branch (currently 0.13-stable). I haven't tested the commit-and-push part of this but everything else works so I'm hopeful.
I ended up needing to add this attribute to work around a common IE bug, that clicking on a scrollbar gives focus to the scroll container. I needed to set it as MUST_USE_ATTRIBUTE or the attribute would not be passed through by React successfully.
remove trailing spaces
The current documentation states that the `<select>` tag supports `defaultChecked`, but it actually doesn't. I believe this documentation was meant to be written in the proposed order.
Non-working fiddle using `defaultChecked`: http://jsfiddle.net/jqs1hsLr/1/
Working fiddle using `defaultValue`: http://jsfiddle.net/nv7z0yzL/1/
Turns out lots of people write invalid HTML all the time and no one, including your browser or React, cares. Most invalid HTML combinations don't cause magic reparented nodes; only some do. The HTML5 parsing spec (https://html.spec.whatwg.org/multipage/syntax.html) specifies which tag combinations cause strange parsing behavior. I did my best to encode the logic here. It's more lenient than before in some cases, but more strict in others (before we didn't look at the whole stack of tags; now we warn with deeply nested `p` or `form` or `a` tags).
Rendering to `document.body` in the examples is conveniently short, but it can
be misleading at the same time, especially for newcomers.
While it's possible to render React components to `document.body`, any 3rd
party scripts can also mess up with it, and it can have unintended consequences
and be source of difficult-to-trace bugs.
Now that #1169 is fixed, the only thing this is used for is to determine whether `onTouchTap` causes touch listeners to be added. The only internal uses of TapEventPlugin are where touch events are already initialized (so this doesn't make a difference) and we don't support `onTouchTap` as part of the public API so this should be safe.
This reverts an early commit that made it so that elements from two
different owner in the same slot wouldn't share state.
That behavior was helpful, and we did hit a case which was solved by this.
However, this pattern is extremely uncommon. I've yet to even find the
original case, let alone any existing cases in our codebase.
Therefore, we're dropping this to simplify elements and enable new
optimizations.
We currently override a couple DOM components. We need to ensure everything we
override is still treated as a DOM component, even if it has a composite
component wrapper.
_mountImageIntoNode moved into ReactMount and wasn't being counted where it was supposed to be. In addition, all DOM elements are now wrapped in a composite wrapper but for the perf tools we want to skip over those or else we'll double-count (at least with the current accounting -- and that's effectively what we did before so this brings us back up to parity).
Fixes#3407.
Test Plan:
Used the jsbin from #3407 and saw similar output from this branch and 0.12:

$TRAVIS_COMMIT_RANGE was broken but it seems what we're doing is worse and
resulting in false negatives.
The result of the bad range was that we weren't running lint or tests for
things we should have been. It actually looks like $TRAVIS_COMMIT has been
wrong and it's not clear why this has been working at all.
ReactDOMComponent maintains a copy of the previous style
object to support in-place mutations of props.style.
This cached object was not cleared when the style
property was removed in a props update.
Fixes#3409
There is an exception when value or defaultValue is set but there are no
children as ReactDOMSelect tries to mark the first children as selected
even if there are no children.
I mis-parsed 'shallow copies' as adjective noun, instead of as a compound verb. I've adjusted the text to make it easier to parse on the first read, which should also help ESL learners to be able to parse it easier.
Summary:
Right now, if a component specifies a propType as, for example,
`myProp: React.PropTypes.shape`, without an actual shape
parameter, any prop type will be accepted, because
`React.PropTypes.shape` returns a function (the actual validator),
not an Error, currently indicating that propType checking passed.
This can create an unfortunate situation where a component looks
like it has fully specified `propTypes`, but in fact does not.
This commit addresses this by warning if a propType checker returns
anything non-falsy that is not an Error (currently all the library
PropTypes return null or an Error).
Test Plan:
Added a unit test; ran `jest` in the root repo directory.
Also ran `grunt lint` and `grunt test`
If either argument is not an object and unequal, then shallowEqual should return false.
If only one argument is an object, then shallowEqual should return false.
Fixes#3369
This is in response to #3207 to address concerns regarding third-party
scripts and browser plugins potentially altering DOM nodes within
document.body, causing problems with reconciliation.
Closes#3211.
The only substantial difference here is that I made the harmony example use ES6
classes. The server rendering example was pretty wacky and hard to run but
I did confirm that it works.
Console is undefined in earlier versions of IE when it is not open. This causes an uncaught exception, and breaks applications in these versions of IE when attempting to warn when the console is closed.
Admittedly, console will usually be open when testing in development, but still React should not break the application when it is not.
We added this test internally and it never got added here. We haven't broken it
with any transforms *yet* but it's still good to actually run all of our tests
here too.
These are the only places that seems to be including environment specific
variables in the message format.
By ensuring that they're static, we make it easier to group logs by
format. I also ensure that I keep each addendum separate so that they can
be filtered/grouped separately.
This is a new version of cloneWithProps but this one is moving out of
add-ons. Unlike cloneWithProps, this one doesn't have special logic for
style, className and children.
This one also preserves the original ref. This is critical when upgrading
from a mutative pattern where a child might have a ref on it.
It also preserves context, which is similar to how context would work when
it is parent based. It also ensures that we're compatible with the old
mutative pattern which makes updates easier.
Note: we need to manually specify date in these files so that the sort order is
correct (2 posts on the same day). Otherwise it will just be ABC order, which
is wrong.
Closes: #3256
Without this, transitioning from `<div onClick={null} />` to `<div />` triggered `willDeleteListener` to delete the `click` handler which caused problems; now, we only call `putListener` and `deleteListener` when we have an actual listener.
I now also clean up the `onClickListeners` map upon deletion and don't double-listen when updating the event listener.
* 'master' of https://github.com/facebook/react: (30 commits)
Expose --target flag on jsx executable
Contributing: cleanup quote style
Add Relay blog post
Fix long lines in vendor/fbtransform/visitors
lint vendor/*.js
fix .eslintignore
remove ballmer example
Fix a doc. cloneWithProps clones a ReactElement.
lint from root
Fixed mistake in jsdocs types for cloneWithProps
Put deprecation warning for classSet
Lint vendor/fbtransform as well
More warnings to ReactFragment.create
Warn when using constructor function directly
Move option parsing into react-tools proper.
Remove lodash devDependency
Added the immutability talk to the React.js Conf update.
Use same pathways for browser transforms as we use in react-tools
lint: remove spaces from array brackets
lint: remove spaces from object braces
...
Valid values are 'es3' and 'es5'.
es3: perform reserved words quoting, don't use defineProperty
es5: default, don't do the above, class methods non-enumerable
Apparently I could've used these too because if you accept an arbitrary
node, then these could end up being objects, but those objects might
also be arrays or elements.
We no longer support the legacy factory style of calling component constructors
directly. We only support createElement or the wrapping of classes with
createFactory. Instead of letting this fail in a gross way as we try to run,
add a nice warning that shows up before the gross TypeError.
We were doing some preprocessing for module options in the command line. Since
we also expose the same API via react-tools (and JSXTransformer), we need to do
the same processing from the API. So just move it all to the same place.
This makes sure we can use the same options everywhere, even from react-rails,
without having to specify each one separately in JSXTransformer as well.
When animating the max-height property in Safari, entering the leave state would trigger an animation to `max-height: 0`. Then when the active state kicked in, it would jump and didn't really look right. Moving the `transition` css property to the active version fixed the issue for me and worked on Safari, Chrome and Firefox. Unfortunately I'm not in a position to test in IE at the moment, but I'll do that at my first convenience tomorrow.
This is an anti-pattern that can be easily avoided by putting the logic
in componentDidMount and componentDidUpdate instead.
It creates a dependency on stale data inside render without enforcing
a two-pass render.
We're not sure if this is the way we want to support this API. It creates
two ways of doing things.
It is convenient to avoid needing to explicitly redefine the key of Maps.
However, this use case isn't as common as having an iterable where the
key is on the value, not the key.
This was an important convenience as an upgrade path but shouldn't be
necessary if you're using best-practice of calling createFactory in the
consuming component.
Summary:
This section was confusing. I reworded it from:
"JSX is completely optional. You don't have to use JSX with React.
You can create these trees through `React.createElement`. The first
argument is the tag, pass a properties object as the second
argument and children to the third argument."
to:
"JSX is completely optional; you don't have to use JSX with React.
You can create React elements in plain JavaScript using
`React.createElement`, which takes a tag name or component, a
properties object, and variable number of optional child
arguments."
and additionally added another child element to the example code.
Test Plan:
Read the new paragraph!
Fixes#1297.
onMouseEnter and onMouseLeave shouldn't *actually* use direct dispatch, but doing so is more useful than doing nothing (and I don't think it precludes adding proper enter/leave dispatching later, either).
Test Plan:
grunt test
Previously, `checkAndWarnForMutatedProps` would flag `NaN` props as
having been mutated, because `NaN !== NaN`. This prevents that warning
from being emitted by explicitly checking for `NaN`s.
This ensures that we have a prefix that can be easily identified in logs
so that we can filter out warnings based on their prefix.
This also turns the remaining two monitorCodeUse callers into warnings.
We'll probably still use monitorCodeUse until we know if we want to
deprecate but most releases should only have warnings.
Updated the mention of "facebook.com" on line 3 of the CONTRIBUTING.md file to link to Facebook. Previously, this mention was just in plain text.
Changed from `facebook.com` to `[facebook.com](https://facebook.com)`
No other content has been changed. Content has not been removed from this file in any way.
I made this mistake while upgrading a few callers.
I'm leaving this as warning so that it is always safe to wrap any existing
child in React.addons.createFragment without breaking prod.
This makes upgrading easier.
Currently we use an invariant to prevent this code pattern. That is really
aggressive for something that doesn't actually put React in a bad state. This
diff replaces invariants with warnings and makes those code paths no-ops.
Eslint now allows us to use a different parser, which allows us to use
esprima-fb explicitly. This means we don't have to wait for espree to add
things like rest-param parsing. Though we do need eslint to upgrade its rules
to handle that AST.
I had hoped to enable parsing of our tests but we can't do that until we
change esprima-fb's XJS nodes to JSX.
While I was here, I also enabled the no-unused-vars rule since eslint
understands template strings. I also made the single quote enforcement
actually fail instead of just warn.
This triggers a warning if you try to pass a keyed object as a child.
You now have to wrap it in React.addons.createFragment(object) which
creates a proxy (in dev) which warns if it is accessed. The purpose of
this is to make these into opaque objects so that nobody relies on its
data structure.
After that we can turn it into a different data structure such as a
ReactFragment node or an iterable of flattened ReactElements.
We've actually diverged more with some modules, but we don't want
a cascade of dependencies out here. Mostly, the changes internally that
we don't want are tied to FB infrastructure but otherwise are
functionally equivalent (usually around error reporting, code monitoring).
This diff enables setState to accept a function in addition to a state partial. If you provide a function, it will be called with the up-to-date `state, props, context` as arguments.
This enables some nicer syntax for complex setState patterns:
If setState is doing an increment and wants to guarantee atomicy, you need a function:
```
this.setState(state => ({ number: state.number + 1 }));
```
This atomicy is particularly important if setState is called multiple times in a single frame of execution as the result of complex user actions. It's a tricky bug to chase down and difficult to determine how to fix when you find it. The current pattern of reaching into _pendingState relies on an implementation detail.
In this example: props.doAction() may result in your ancestor re-rendering and providing you with new props. If setState is called directly with an object literal referencing `this.props`, it will use the *old* version of props, not the new value. Using a function solves for this case:
```
this.props.doAction();
this.setState((state, props) => ({ number: state.number * props.multiplier }));
```
enqueueCallbackInternal forgot to schedule an update.
We could rely on the implicit contract of enqueueElement to do it. However,
if we're currently outside a transaction, it'll flush synchronously. Before
we enqueue the callback. We could also enqueueCallback before we
enqueueElement, but that causes a fragile relationship between them. E.g.
enqueueElement should not need to schedule an update if it is the same
element.
In 1.4.0 we can use the TypeScript API directly to preprocess our files.
This lets us get rid of a dependency.
https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API
We can also use this to provide our default libraries so that we don't
need to keep the references in the test file.
This is to make sure we don't end up with differences in our different
testing methods. We may switch out the failure allowances later (maybe
just jest will be good enough and we can let phantom fail for a little
bit).
It's possible to configure Jest to not dump the module cache between
specs. This makes it tricky when we silence warnings one a 2nd call.
In this case, the same message was getting logged so when we expected
the count of warning calls to increment, it didn't.
This makes it more difficult to find bugs in mixins both dynamically
and using a static type system.
We also don't have a way to find these to be upgraded to a new mixin
syntax if we needed to.
This hook is currently an optional noop but could be made required to
create a mixin class.
We freed up this internal name by removing the internal base class.
We're now free to use this name as it was intended.
ReactDOMComponent and ReactCompositeComponent are still confusing as
they're internal but we'll rename them later.
All entry points are for reconciliation are within batching strategies.
Since we don't have any batching strategies with synchronous updates,
there can't be more than one life-cycle method on the stack at any given
time.
Therefore, it's safe to move the composite life cycle flag to a singleton.
This saves us some memory management.
I think that we can get rid of these life cycle states completely in the
future.
Currently, the first setState that happens during initial render will
start a new batch. Any subsequent updates will be batched. That means that
the first setState is synchronous but any subsequent setStates are
asynchronous.
This commit makes it so that the batching starts at the root. That way all
the setStates that happen within life-cycle methods are asynchronous.
I originally did this work so that we could allow setState to be called
before the internal ReactCompositeComponent was constructed. It's unlikely
that we'll go down that route now but this still seems like a better
abstraction. It communicates that this is not immediately updating an
object oriented class. It's just a queue which a minor optimization.
It also avoids bloating the ReactCompositeComponent file.
Since they both depend on the life cycle I break that out into a common
shared dependency. In a follow up I'll refactor the life-cycle management.
We need to move instantiation into the mount phase for context purposes.
To do this I moved the shallow rendering stuff into ReactTestUtils and
reused more of the existing code for it by instantiating a noop child.
Everywhere we refer to the "type" we should pass it to ReactNativeComponent
to resolve any string value into the underlying composite.
As part of the new class effort it is now possible to define React
Components using any type of generic JavaScript class syntax.
This includes TypeScript classes. This test ensures that we don't regress
that support, and also serves as an example for using React in TypeScript.
TypeScript provides a good demo of where we think property initializers
are going.
We don't have any official *type* support for TypeScript yet.
This test trails the ReactES6Class-test file. Some manual tweaking is
required when converting tests.
This adds a matcher called toEqualSpecsIn which executes two test suites,
without reporting the result. It then compares the specs and the number
of expects executed by each spec.
This will be used to ensure that tests written in other languages test the
same thing as the base line, ES6 classes.
Sets up CoffeeScript equivalence test.
As part of the new class effort it is now possible to define React
Components using any type of generic JavaScript class syntax.
This includes CoffeeScript. This test ensures that we don't regress that
support, and also serves as an example for using React in CoffeeScript.
This test fail trails the ReactES6Class-test file. Some manual tweaking is
required when converting tests.
There is no way to queue an update to a context so there is no need for
this field. The only way to get a new context is from above.
Soon _pendingElement will get the same treatment. Once _setPropsInternal
can be removed.
Instead of putting the shared code in a base class method, we use a wrapper
call around all invokations. That way they're free to add code before AND
after the non-shared code.
That way we ensure that component extensions don't need to implement
ReactComponentMixin and do super() calls into it. This helps to create a
tighter API for custom component extensions.
This provides the first step towards moving these methods to static
methods which allows to use a different dispatch mechanism instead of
virtual method calls. E.g. pattern matching.
We need to move instantiation into the mount phase for context purposes.
To do this I moved the shallow rendering stuff into ReactTestUtils and
reused more of the existing code for it by instantiating a noop child.
Everywhere we refer to the "type" we should pass it to ReactNativeComponent
to resolve any string value into the underlying composite.
You can only get a ref to a ReactCompositeComponent, so move the ref code here which gives us more flexibility to put it at the correct time in the lifecycle.
There should be no behavior change in this commit.
Test Plan: jest
This will be based on the site generation time, making doc generation
slightly less deterministic but that's ok. Now we won't depend on
helpful community members updating it for us (#2874) when we forget,
it'll just happen naturally the next time the site is generated.
Summary:
If `getDOMNode()` returns null in `LocalEventTrapMixin`, `listener` will also be null and `accumulateInto` will throw. This changes `LocalEventTrapMixin` to throw a more helpful error message.
Test Plan:
Ran unit test successfully:
```
npm test LocalEventTrapMixin-test.js
```
document.createElement throws an error if you don't pass it any
arguments. Neither PhantomJS nor jest (via jsdom at version jest is
using) behave as browsers do now so this went unnoticed.
This allows state to be set up in the constructor instead of through
getInitialState. getInitialState is now considered part of "classic".
Therefore, they move into ReactClass's constructor.
As a consequence of this, we no longer have a mapping between the internal
representation and the public instance during the mounting process.
Because the constructor hasn't returned yet.
We used to have a special case for calling setState in getInitialState
which was just ignored. This makes that throw and the component is
considered unmounted during the construction phase.
We added a bind to the public instance, but instead we can just pass the
public instance as the context when we execute.
This avoids a warning that fires when we call bind on auto-bound methods.
I don't agree with 80 on principal but it's what we have for now.
This fixes the reasonable cases. Most of the long lines are in docblocks
with long type information or containing links.
These rules are very close to what we have internally. We may still miss
a couple things (jsdoc params being a big one) but it's good enough.
This is also more restrictive than what we enforce internally, but it's
for the best.
In ReactClass we use early validation to warn you if a accidentally defined
propTypes in the wrong place or if you mispelled componentShouldUpdate.
For plain JS classes there is no early validation process. Therefore, we
wait to do this validation until the component is mounted before we issue
the warning.
This should bring us to warning-parity with ReactClass.
This is the base class that will be used by ES6 classes.
I'm only moving setState and forceUpdate to this base class and the other
functions are disabled for modern classes as we're intending to deprecate
them. The base classes only have getters that warn if accessed. It's as if
they didn't exist.
ReactClass now extends ReactComponentBase but also adds the deprecated
methods. They are not yet fully deprecated on the ReactClass API.
I added some extra tests to composite component which we weren't testing
to avoid regressions.
I also added some test for ES6 classes. These are not testing the new
state initialization process. That's coming in a follow up.
Fix outdated copyright year (update to 2015)
The copyright year was out of date. Copyright notices must reflect the current year. This commit updates the listed year to 2015.
ES6 classes won't have an early validation step. Therefore I added some
extra validation later on in the process. These would've normally have
been caught by createClass in classic React.
This throws an error that is immediately caught. This allows you to use the
debugger's "break on caught exception" feature to break on warnings.
This should help with tracking down these warnings using the stack.
However, it could also add more noise to other debugging pattern.
This essentially copies all classic element creation tests to the modern
JSX tests. The classic tests doesn't use JSX and modern tests do.
The idea is that the JSX tests can start dropping dynamic checks once
we have Flow support for those features. JSX won't be necessary for
dropping dynamic checks. Plain object will also work. Flow will also not
be necessary for JSX. However, the tests should test for the suggested
combination (JSX + Flow).
This also moves some misplaced tests to ReactDOM and Validator.
Note that the modern tests uses ES6 classes. I will add separate tests for
those. However, these are not guaranteed to have .displayName so all our
error messages should check .name if available instead. This should be
better abstracted but I just adhoc fix this for now.
This should make it more clear that even though `$` is used in 4 methods, only 2 of them are crucial for integrating the modal into the components lifecycle methods and the other 2 are just helpers.
This adds a warning to React.createElement in __DEV__ about using null
or undefined. This is technically valid since element creation can be
considered safe and usable in multiple rendering environments. But
rendering in a DOM environment with an element with null/undefined type
is not safe.
Update tutorial.md to improve grammatical parallelism in features list. Also added periods to follow first item's syntax.
BEFORE: "Live updates: as other users comment we'll pop them into the comment view in real time"
AFTER: "Live updates: other users' comments are popped into the comment view in real time."
BEFORE: "Markdown formatting: users can use Markdown to format their text"
AFTER: "Markdown formatting: users can use Markdown to format their text."
This moves ReactClass, ReactElement and ReactPropTypes into a legacy folder
but since it's not quite legacy yet, I call it "classic".
These are "classic" because they are decoupled and can be replaced by
ES6 classes, JSX and Flow respectively.
This also extracts unit tests from ReactCompositeComponent, which was
terribly overloaded, into the new corresponding test suites.
There is one weird case for ReactContextValidator. This actually happens in
core, and technically belongs to ReactCompositeComponent. I'm not sure
we will be able to statically validate contexts so this might be a case
for dynamic checks even in the future. Leaving the unit tests in classic
until we can figure out what to do with them.
In order to improve support for Chinese and Japanese IME input in
Internet Explorer, use a fallback composition state to determine
inserted text. IE composition events are mostly okay, except for
certain punctuation characters that are ignored. Using the fallback, we
can detect these characters.
The fallback is also useful for emitting `beforeInput` events, so it
makes sense to simply combine these plugins.
This change also incorporates a recent change to the Google Input Tools
browser extension that exposes a `data` field via the `detail` object
on the custom composition events it emits.
IE9+ has support for window.getSelection, but we’re still using
document.selection for IE9/10. Only use the old IE selection API if the
modern one is unavailable.
Based on conversation in https://github.com/facebook/react/pull/2501. A good place to guide people further in finding the complete set of tools needed to build an application.
This was a file we probably never should have synced out in the first
place. We don't use it and it provides the same basic functionality that
bin/jsx provides.
ART, just like MultiChild adds an expando property to manage it's diffing
state. This is ugly and bad. We should be moving this state outside the
component for use by the diffing algorithm. This state is not needed by
components nested in composites, and varies by diffing algorithm.
It sucks that I have to add it to every component just to support ART,
but that's the quickest solution, other than disabling preventExtensions.
At least now we know that it sucks.
This separates the reconciliation step of children into a separate module.
This is the first step towards prerendering.
The stateful instances are reconciled and put into a "rendered children"
set. Updates creates a new of these sets. These two sets are then diffed
to create insert/move/remove operations on the set.
The next step is to move the ReactChildReconciler step to before the
native DOM component. That way it's possible to rely on child
reconciliation without relying on diffing.
Summary:
After #2570, `mountDepth` is only used to enforce that `setProps` and `replaceProps` is only invoked on the top-level component. This replaces `mountDepth` with a simpler `isTopLevel` boolean set by `ReactMount` which reduces the surface area of the internal API and removes the need to thread `mountDepth` throughout React core.
Reviewers: @sebmarkbage @zpao
Test Plan:
Ran unit tests successfully:
```
npm run jest
```
Currently, `ReactUpdates` updates dirty components in increasing order of mount depth. However, mount depth is only relative to the component passed into `React.render`. This breaks down for components that invoke `React.render` as an implementation detail because the child components will be updated before the parent component.
This fixes the problem by using the order in which components are mounted (instead of their depth). The mount order transcends component trees (rooted at `React.render` calls).
Reviewers: @sebmarkbage @zpao
Test Plan:
Ran unit tests successfully:
```
npm run jest
```
Summary:
Changes the way we instrument methods for `ReactPerf` so that developer tools can assign implicit method names to measured functions.
Reviewers: @zpao @sebmarkbage
Update to the animation documentation for ReactTransitionGroup to clear the air on where one can use it.
If someone tries to use it off of React.addons.ReactTransitionGroup, which is undefined, instead of its real location, React.addons.TransitionGroup, they get a vague error about being unable to set defaultProps of undefined in the React createElement body.
Summary:
Currently, `ReactClass` mutates values returned by `getDefaultProps`, `getInitialState`, and `getChildContext`. This is bad because the objects may, for example, be cached and re-used across instances of a React component.
This changes `ReactClass` to instead create a new object. In return for allocating a new object, I've replaced `mapObject` with a `for ... in` so that we are no longer allocating an unused object.
Fair trade, IMO.
Test Plan:
Ran unit tests successfully:
```
npm run jest
```
Conflicts:
src/core/ReactCompositeComponent.js
Conflicts:
src/class/ReactClass.js
The word "Friends" does establish a relationship however it does not fit in the vernacular of react.
This change makes the phrase more explicit and more familiar.
We currently have three DOM specific hooks that get injected. I move those
out to ReactComponentEnvironment. The idea is to eventually remove this
injection as the reconciler gets refactored.
There is also a BackendIDOperation which is specific to the DOM component
itself so I move this injection to be more specific to the DOMComponent.
E.g. it makes sense for it to be injectable for cross-worker DOM operations
but it doesn't make sense for ART components.
If several children complete leaving before rendering TransitionGroup,
only the last one was removed. This could easily happen if
callback in componentWillLeave is called synchronously and several items
are removed from array. The other case is when ReactCSSTransitionGroup
has transitionLeave={false} and array is also cleaned up.
The bug was happening because this.state.children was used as a base for
children removal and it wasn't updated until the render, so only the last
removal was actually happening.
Fix involves keeping the updated children state between invocations of
_handleDoneLeaving. After updating this.state and rendering,
updatedState is cleaned up and ready for subsequent array modifications.
Test case included.
This is part of moving more logic out of the base classes.
setProps, replaceProps etc. are not accessible from anything other than
ReactClass so we can safely move it to ReactCompositeComponent.
mountComponentIntoNode is tightly coupled to ReactMount. It's part of the
outer abstraction, the mount point, not the individual component.
The _owner field is unnecessary since it's reachable from _currentElement.
The _lifeCycle field is unnecessary because an internal component should
not even need to exist at all if it's unmounted. It should be dereferenced
internally, and never exposed externally.
The only case where it's important is for batching updates where we
currently avoid calling performUpdateIfNecessary if it's mounted. However,
this function is already only executed "if necessary" so we just make sure
that it's not necessary after unmount by resetting all the pending fields.
We currently make a copy of .style because we support mutating the style object in place. Instead of storing it back on props, store it separately on the component instance so that we don't mutate props anywhere. This is gross but should all be cleaned up after #2008 is resolved.
Test Plan: jest
createFullPageComponent doesn't reference ReactBrowserComponentMixin directly so the mixin should get injected before the components are created. Previously, this test failed because getDOMNode wasn't present on the component instance.
Test Plan: jest
...unless they already have a wrapper. Also, add tagName to every wrapper.
This ensures that refs are consistent. They always look like composite
components. This effectively hides the internal implementation details of
real DOM components since you can no longer get a ref to one.
In the future we might want to drop this wrapper and have refs refer
directly to the DOM node.
I currently use a hacky way of auto-wrapping inside of ReactNativeComponent
so that any given string can be wrapped. Better suggestions are welcome.
Fixes#2493, also closes#2353 as it incorporates a variant of that fix.
- Instead of having getEmptyComponent return `<noscript />` directly, wrap it in a class that we can easily identify later as being an empty component
- Cache the empty component element instead of recreating one each time
- Avoid touching the nullComponentIdsRegistry dictionary at all when not dealing with empty components
- Move empty-component tests to a separate file
Test Plan: jest
ReactTextComponent's implementation is DOM-specific; instead of flattenChildren creating the ReactTextComponent instances, ReactNativeComponent now takes care of having ReactTextComponent injected and creating the component instance. I also renamed ReactTextComponent to ReactDOMTextComponent and moved it to browser/ui/ where it belongs. ReactDOMTextComponent no longer inherits directly from ReactComponent and instead implements construct and {mount,receive,unmount}Component directly.
This diff removes `ReactTestUtils.isTextComponent` which should have previously never returned true when using public APIs.
Test Plan: jest, use ballmer-peak example.
"appear" differs from "enter" in that all children of a transition group at mount time will "appear" but will not "enter". All children later added to an existing transition group will "enter" but not "appear".
This extra transition phase allows for animation-on-mount effects.
A mirroring "appear" prop has been added to ReactCSSTransitionGroup, however for reverse-compatibility (and because "appear" is less common) it defaults to false.
Thanks to @afa for his work investigating the possible ways to implement this.
monitorScrollValue is only called with `ViewportMetrics.refreshScrollValues` (https://github.com/facebook/react/blob/master/src/browser/ReactBrowserEventEmitter.js#L333-L334) and the window scroll properties (scrollTop and scrollLeft) don't change on resize (from my testings), so there is no need to listen for window resizes.
I also tried to see why the resize listener was added from the history but it was introduced on the initial commits.
I created a simple page that shows that http://jsbin.com/nuhice, open the console.
While working on #2382, I accidentally broke this behavior (causing text components to get unmounted and remounted for any update) but we didn't have any unit test for it. Now we do.
Test Plan: jest TextComponent
ReactClass is now composed by ReactCompositeComponent rather than
inherit from it.
The state transition functions currently use ReactInstanceMap to map an
instance back to an internal representation.
I updated some tests to use public APIs. Other unit tests still reach into
internals but now we can find them using ReactInstanceMap.
I will do more cleanup in follow ups. The purpose of this diff is to
preserve semantics and most of the existing code.
This effectively enables support for ES6 classes. All you would need to
expose is ReactClassMixin.
The use of the conjunction "and" leads to an improper assertion about what should/shouldn't be done. Using a semicolon resolves this by indicating the contrasting alternative.
* master: (113 commits)
Remove esprima-fb and use Syntax from jstransform
Update React.renderToString argument type in docs
[traverseAllChildren] fix out-of-scope var use.
Use double quote for transformed `displayName` and `data-*`
Remove unrelated comment
Fix typo in If/Else JSX doc.
Cleanup a couple unused variables
Use dump cache and remove factory from ReactElement-test
Update deprecated propTypes
Bring in jsfiddle integration script, add harmony
Extending period in which click events are ignored
React.renderComponent --> React.render
Followup fix for React.PropTypes.node
Add comma for readability in tutorial
Drop internal uses of .type on the class
Drop Legacy Factories Around Classes
Drop ReactDOM from internal DOM extensions
Added comma to increase readability.
Add 0.12 starter kit
Change the date and the link url to match the proper roundup
...
Conflicts:
docs/docs/02.1-jsx-in-depth.md
Dear ES6 gods, bring us `let` soon.
This fixes an issue where non-keyed iterables are used as children and the value of `i` would be undefined because its used out of scope. This adds a separately scoped iteration index value and appropriately increments it as iteration continues. Doi.
While I'm in there, make the usage of falsey `nameSoFar` more obvious and more consistent with the existing usage on L115
Test plan: first wrote a test covering this previously untested path. Saw an identical issue as was experienced in development environment. Then ensured test passed after this diff.
JSX currently transforms everything to double quote except these two. This way, it's at least consistent and will satisfy half of the people who do put a strict quotation linting on their project.
Test: `jest`, check the double quoted transformed `data-bla="something"`.
We need to use dump cache because we don't enable it by default internally.
While I'm at it, I might as well kill the ComponentFactory variable which
is now just an alias.
Classes are now pure classes without a legacy factory around them.
Since classes will become just any function that returns a valid instance,
let's drop isValidClass.
There's some hacks in here for auto-mocking frameworks (jest) that mock the
prototype of these classes. These hacks allow these classes to be mounted.
On ios device, browser simulates mouse events, but does that with
a delay, because of double tap gesture. The problem is that
TapEventPlugins listens to both types of events, so it fires twice
Everytime there is a touch event, we should ignore mouse events that
follow it. This way, we still respond to both mouse and touch events,
just ignore the device generated ones.
For example, warning might be replaced with a module that throws errors,
as is the case internally when running tests. Previously we were
whitelisting this test to provide time to update callsites. Now we
aren't and it fails.
Hi in chrome debugger, the files that use sourcemaps from the transformer get "null" as the filename during debug, https://github.com/facebook/react/blob/master/main.js#L15 "sourceFilename" is used instead of "filename" to specify the filename in the sourcemap.
This prevents feature tests like:
var ReactElement = React.createElement(...).constructor;
if (element.constructor === ReactElement)
This is intentional so that we have the option to make these plain objects.
E.g. for direct inlining or replacing them with value types.
This prevents feature tests like:
var ReactElement = React.createElement(...).constructor;
if (element.constructor === ReactElement)
This is intentional so that we have the option to make these plain objects.
E.g. for direct inlining or replacing them with value types.
This moves logic responsible for class creation and mixins into
the ReactClass module. This currently creates a class that extends
the ReactCompositeBase but in the future, this will be decoupled as
ReactCompositeComponent will compose these classes.
This is just a cut/paste.
Fixes#1392.
Previously, ReactComponent.updateComponent set the new props and owner and updated the component's refs. Because it did the actual props assignment, it had to be called by ReactCompositeComponent between componentWillMount and componentDidMount, meaning that it was skipped if shouldComponentUpdate returned false. Now, updateComponent takes the old and new descriptors and only updates refs, allowing a subclass to call updateComponent at a convenient time (specifically, it can be before `this._descriptor` is updated if the subclass also overrides performUpdateIfNecessary).
The new update cycle for composites is:
- receiveComponent is called which stores `this._pendingDescriptor` and calls performUpdateIfNecessary directly or a state update is enqueued, in which case ReactUpdates will call performUpdateIfNecessary
- performUpdateIfNecessary ensures that an update is still pending (which might no longer be the case if an update is queued for a subcomponent that was updated through a parent's reconciliation) and calls updateComponent with the old and new descriptors
- updateComponent calls super to update refs, then calls componentWillReceiveProps (if applicable) and shouldComponentUpdate -- if shouldComponentUpdate returns false, `this._descriptor`, `this.props`, and `this.state` are updated and the update is skipped; else, _performComponentUpdate is called
- _performComponentUpdate calls componentWillUpdate and _updateRenderedComponent, and enqueues the componentDidUpdate call (in that order)
- _updateRenderedComponent calls render and updates the rendered component appropriately
For DOM components (essentially unchanged):
- receiveComponent is called which does a short-circuit check for descriptor equality and delegates to super (which stores `this._pendingDescriptor` and calls performUpdateIfNecessary)
- performUpdateIfNecessary (not overridden) sets new values for `this.props`, etc. and calls updateComponent
- updateComponent does the DOM property and children updates (some synchronously, some queued for the transaction close)
For text and ART components (unchanged):
- receiveComponent updates the DOM or ART directly based on the new props
- updateComponent is never called
Notable changes:
- When shouldComponentUpdate returns false, refs are still updated
- ReactDefaultPerf now includes lifecycle methods in component timings
- updateComponent's signature changed (technically this is part of the public API, though we've never documented it)
Test Plan: jest
Same for <pre> and <listing>. Browsers are crazy.
Test Plan: jest, verify in Chrome that starting textareas with a value starting with two newlines renders both newlines instead of one newline, as it did before.
This lets you use any kind of iterable as a container of react child elements. It also preserves keys when possible if the iterable is keyed.
* Use an ES6 Map or Set to hold children.
* Use an Immutable-js collection to hold children.
* Use a function* which yields children.
Concretely, this removes the necessary conversion to JS objects if you're mapping over Immutable-js collections to get children, i.e.:
```
<div>
{myImmutable.map(val => <span>{val}</span>).toJS()
</div>
```
Now we can remove the `toJS()` and the intermediate allocation along with it.
This also cleans up the traverseAllChildrenImpl method.
I kept some places intact (search for @jsx) because they require other bigger changes:
- ref-01-top-level-api.md
- grunt/tasks/npm.js
- old blog posts (don't change those)
- examples/ folder, as they have their own package.json that rely on old dependencies (node-jsx, reactify) that haven't upgraded to 0.12
Add note about ReactTransitionGroup, that any additional, user-defined, properties will be become properties of the rendered component.
And example how to render a `<ul>` with css class.
Because the JS community's polyfilling infrastructure sucks and we'll
have to fix it for them before we require this.
JSX spread uses React.__spread
(which might get special behavior for key/ref, not sure yet)
This never uses the native implementation and throws for prototype chains.
Once the native implementations are faster, we'll start using them.
Hello,
I was just reading through your post and noticed a minor change. The sentence originally read, "It's scaled very well for us...". I thought it was a little unclear since it's can mean "it has" or "it is", which can make this sentence take on a whole different meaning.
The URL already made its way around so we can't just break it. We might
want to just live with it instead of even doing this redirect.
2b225446c0 (commitcomment-8176218)
People may have a bad time if they're depending on these but we can
delay that a little bit. Unless they're using directly and not
polyfilling Object.assign.
Because we're using innerHTML to generate DOM Elements, we need to make
sure that the tag is sane and doesn't try to do injection.
This wouldn't be an issue if we used document.createElement instead.
* ReactComponents aren't really the thing we need, ReactElements are
* Remove the deprecation notice that we've had in there for a long time
Test Plan: build, jest
This makes it easier to contribute without having to learn a bunch of
slightly different helpers and remember their slightly different
signatures and semantics.
We'll probably start using ES7 spread properties instead of merge in the
future when at least one more transpiler supports it.
React.DOM is becoming helper factories to generate ReactElements. They're not
classes. It will be ok to call them directly as functions, but not to use them
where a class is expected.
I grepped for uses of React.DOM. This is going to be a set of helper functions
to generate ReactElements without JSX.
They're not classes so they cannot be used where a React class is expected.
Since we always use JSX, we should have no internal use for these helpers.
We can use strings instead.
We're trying to move to a convention where lower-case variables on JSX are always HTML/SVG tags rather than variables in scope. See:
http://fb.me/react-jsx-lower-case
Therefore, this diff renames existing uses to upper case variables.
This throws an error on all these files, so I manually go rename all the variables. I then run lint to ensure that the rename doesn't leave any undeclared variables.
This makes ReactDOM a simple helper for creating ReactElements with the string tag as the type. The actual class is internal and created by instantiateReactComponent. Configurable using injection.
There's not a separate class for each tag. There's just a generic ReactDOMComponent which could take any tag name.
Invididual tags can be wrapped. When wrapping happens you can return the same tag again. If the wrapper returns the same string, then we fall back to the generic component. This avoids recursion in a single level wrapper.
This doesn't actually remove the pages, just the main content. Sidebar
items now link offsite. The pages doesn't automatically redirect, but we
could do that if we really wanted.
Fixes#2229
You have to instantiate a Dispatcher to use it, not just grab the prototype or it will fail when trying to grab instance properties like: this.$Dispatcher._callbacks.
IE9+ supports `window.getSelection()` but `SelectEventPlugin` gives precedence to `document.selection` instead. `document.selection` is still available in later versions of IE, but the modern Selection object is preferable. Swap the two.
The second argument of mockComponent was listed as tagName, but referred to in the description as mockTagName. I changed the first one to mockTagName to be consistent.
The first sentence had an unnecessary semicolon which made the whole thing difficult to read. The new syntax is not only easier to read but also more exciting.
The previous wording could be interpreted to mean sub-trees moving from
within one sibling to within another, rather than the shuffling of siblings on
a single level as intended
Edit the description of componentDidMount() to make clear that the function is called only once during the lifecycle of the component, after only the initial render() call. The description is now similar to that for componentWillMount(). The existing wording does not make it clear that the function is called only after the initial render. (Granted, it is possible to infer this from descriptions of the component lifecycle found elsewhere in the documentation, but I think explicit is better than implicit in this case).
The HTMLtoJSX file is really a part of the React-Magic project, and should belong there rather than here:
- It doesn't really follow the release cycle of React at all
- It is totally standalone with no dependency on React
- The only usage of this script is in React-Magic and on the HTML to JSX page on the React website (http://facebook.github.io/react/html-jsx.html)
I've hotlinked it from the Github site for that project since this was the easiest way to pull it in.
Due to the fact that Github Pages lacks redirects (among other basic web hosting functionality), I've replaced the `html-jsx-lib.js` file with a comment explaining where the file has moved to, just in case anyone was hotlinking it from the React site.
I traced the current logo in Illustrator to get a good version. And with
SVG we don't need any 2x magic because it's already vector. I should
probably care about IE8, but I don't.
We currently automatically render empty components in place of mocks. However,
we were accidentally transferring the props from the mocked descriptor to the
empty component placeholder. Even children.
This change just cleans that up and should only affect unit tests.
Trying to make the event a bit more performant for events.
Feel free to reject this because the API inevitably isn't great. It's good for perf though, and since we're only using `accumulate` in very restrained places, I think we're fine.
`accumulateInto` is `accumulate` that mutates more and allocates less. I kept `accumulate` in case we want that in the future.
The spec changed to allow null & undefined sources without throwing.
Now our code depends on this new behavior. The only browser that
implements Object.assign has also updated its native implementation to
this behavior (Firefox Nightly).
The biggest change: instead of calling functions directly, we now use
React.createElement to wrap.
The other big change: this removes the need for the @jsx pragma.
Instead we'll parse everything, assume React is in scope,
and only look for the actual XJS parts in the AST (as opposed to only
runing the transform when @jsx was specified in the docblock).
Note: this is actually a series of commits internally and should have
been syned out in pieces over the past several weeks.
This fixes some log spew since this pattern is deprecated. This doesn't use
the validator in the descriptor creation so there's no prop type checks here.
I guess that's fine because we still have the second prop type checks.
We need to use ReactLegacyDescriptor because the constructor here will be a
legacy factory that we need to unwrap.
constructAndRenderComponent should be deprecated.
Replace plain function calls to legacy factories with createFactory or
createElement. For ReactDOMComponents the type should be replaced with
strings.
Because we don't have easy access to ReactLegacyDescriptor from within
React, we need to use the .type property to extract the real class.
This will go away later and is covered by unit tests.
This moves all logic around legacy descriptors to ReactLegacyDescriptor. This
is responsible for the layer that knows that createClass exports a legacy
factory. When passed one of these classes, it unwraps it to be a real class.
If it is passed a non legacy factory, it is assumed to be a non-react component
that needs to be invoked as a plain function.
The semantic change is that a descriptor is now always returned if passed a
legacy factory. Even if that factory is a mock. A mock would previously return
undefined.
For mocks, I treat the factory as the authoritative function. I call it to extract
the instance or fill it with an empty component placeholder.
Additionally, I make the classes take props as the first argument to the
constructor. This is what the new class system will do.
We currently need to set up some internals by calling the internal construct
method. Instead of doing that automatically in the constructor, I now move that
to a second pass so that mocks can get the plain props.
This means that we can assert that a mock has been called once it's mounted
with it's final props. Instead of the descriptor factory being called.
The reason I chose to submit this is because it was initially unclear from the docs that the transition group needed to already be mounted in order for it to work properly.
I dropped the part of constants.js that we weren't using (namely the
part where we insert constants) but left it open to do that. It should
be trivial, we just aren't using it.
Fixes#1824
Added docs for `React.isValidClass` and `React.isValidComponent`.
Still missing top level api:
* `constructAndRenderComponent`
* `constructAndRenderComponentById`
* `withContext`
When I first read these docs, it was not immediately clear to me that I could
use `React.addons.CSSTransitionGroup` to animate a single item coming into view,
or an item replacing an item already there. This was partly due to the example
which rendered a list of items.
This PR adds a blurb about being able to use
`React.addons.CSSTransitionGroup` with one or zero items, provides a code
example, and adds a note blockquote that a `key` attribute must always be
provided on each child of `React.addons.CSSTransitionGroup`. The latter point
was not immediately obvious from the original `TodoList` code example, since it
renders a list which would normally require `key` attributes anyway.
Test Plan:
- Refreshed `http://localhost:4000/react/docs/animation.html`, saw that the
docs additions rendered correctly.
- Example code not tested (it was extracted from working code).
Depends on #1758.
Fixes#1698.
Previously, controlled components would update too soon when using something like ReactLayeredComponentMixin (i.e., before the layer's updates could propagate from the parent), causing the cursor to jump even when always updating the new model value to match the DOM state. With this change, we defer the update until after all nested updates have had a chance to finish, which prevents the cursor from misbehaving.
Also cleaned up the logic around updating a bit -- the .value and .checked updates in ReactDOMInput weren't being relied on at all so I removed them and opted for a simple forceUpdate instead. I also got rid of _isChanging which hasn't been necessary since the introduction of update batching.
Test Plan: Tested the example in http://jsfiddle.net/Bobris/ZZtXn/2/ and verified that the cursor didn't jump. Changed the code to filter out numbers and verified that the field prevents typing numbers (attempting to do so still causes the cursor to jump to the end). Also verified that controlled and uncontrolled radio buttons, textareas, and select boxes work.
Callbacks passed to this setImmediate function are called at the end of the current update cycle, which is guaranteed to be asynchronous but in the same event loop (with the default batching strategy).
This is useful for new-style refs (#1373, #1554) and for fixing #1698.
Test Plan: jest
This isn't a good final solution but it makes React actually usable on
its own.
This also makes tests runnable, though only via jest
(./node_modules/.bin/jest)
The `mockTagName` parameter was always optional, and so probably was not
used very often. If you tried to use it, it would be shadowed by the
`var mockTagName` declaration in the `render` method, so only
`module.mockTagName` or `"div"` were ever possible values.
Relax the argument type checks. Currently we throw for non-objects and terminals
but Object.assign does a coercion to Object instead. It also allows merging
Arrays as if they are objects.
This also relaxes the check for dependents such as ImmutableObject. This sucks
but it will allow us to use a fast code path to native Object.assign.
We always have the option of adding warnings to Object.assign or static type
checks.
I'm keeping the null check. Object.assign throws for null checks.
We'll also start returning the result of coercions just like Object.assign.
This detail is going to become more important once the idiom
`className={joinClasses(this.props.className, newClass)}` becomes more
common, as it will when we move away from `this.transferPropsTo`.
Breaking changes
- key/ref are no longer accessible on props but they are accessible on the
descriptors. This means that parents/owners can access it but not the
component itself.
- Descriptor factories are now plain functions and you can't rely on the
prototype or constructors of descriptors to identify the component type.
Existing descriptor factories are now wrapped in a legacy factory. Currently it
does nothing but it will give us a hook to track callers to factories that are
not using JSX but just invoking the function directly. It also proxies static
methods/properties to the underlying class. The newer factories don't have this
feature.
ReactTextComponent has it's own little factory because it's props is not an
object. This is a detail and will go away once ReactTextComponent no longer
needs descriptors.
Whilst this is intentional behaviour (see #1274), it is not documented anywhere, so it is worth mentioning.
It would also be nice if React issued a warning to console if a cloned component loses its key (as this will silently break reconciliation?)
This order should make more sense; it moves important functions like React.renderComponent up and deprecated/discouraged ones like transferPropsTo and setProps down. No content changes.
In a world where this component was server-rendered, we wouldn't want to call the data-fetching code there so it makes more sense to have it in componentDidMount.
If we don't error here, we end up with a confusing error later on in this.getDOMNode() where ReactMount doesn't have the proper container registered in its object.
This change adds an additional function to the exported object to support getting access to the transformed result as an object rather than just a string result - the separate function designed to maintain backwards compatibility.
This facilitates tools that want the code separate from the sourcemap or anything else as time goes by.
See modification to the test-file: Basically we add a small hint at the end
of the error warning for propType errors to help identify which instantiation
of the component at hand is faulty.
This isn't actually enabled yet for public projects, but this will help
us speed up builds when it does get enabled.
http://docs.travis-ci.com/user/caching/
We now forbid calling setState or forceUpdate if any component's render function is higher in the stack, not just the component you're trying to update. (We do this already now for React.renderComponent and React.unmountComponentAtNode.)
This also has the advantage that we can now remove CompositeLifeCycle.RECEIVING_STATE, making _compositeLifeCycleState easier to reason about (not to mention that RECEIVING_STATE was a confusing name) and making it possible to remove a try/finally from the render path which might help with perf.
Error should be thrown in the previous condition is "not" meet. And the href propType is described as optional in the comment, but the null check was missing.
This copies the propType and contextType validation to a wrapper around the
descriptor factory. By doing the validation early, we make it easier to track
down bugs. It also prepares for static type checking which should be done at the
usage site.
This validation is not yet active and is just logged using monitorCodeUse. This
will allow us to clean up callsites which would fail this new type of
validation.
I chose to copy the validation of abstracting it out since this is just an
intermediate step to avoid spamming consoles. This makes more a much cleaner
diff review/history. The original validation in the instance will be deleted as
soon as we can turn on the warnings.
Additionally, getDefaultProps are moved to become a static function which is
only executed once. It should be moved to statics but we don't have a
convenient way to merge mixins in statics right now. Deferring to ES6 classes.
This is still a breaking change since you can return an object or array from
getDefaultProps, which later gets mutated and now the shared instance is
mutated. Mutating an object that is passed into you from props is highly
discouraged and likely to lead to subtle bugs anyway. So I'm not too worried.
The defaultProps will later be resolved in the descriptor factory. This will
enable a perf optimizations where we don't create an unnecessary object
allocation when you use default props. It also means that ReactChildren.map
has access to resolved properties which gives them consistent behavior whether
or not the default prop is specified.
Add support for spread attributes. Transforms into an Object.assign just
like jstransform does for spread properties in object literals.
Depends on https://github.com/facebook/esprima/pull/22
Github doesn't let us handle 404s within a project repository, so we
handle them at the organization level. In order to handle graceully for
specific projects, we're setting up redirects to projects' own 404.html.
The patternUnits attribute defines how a pattern's coordinate system is
defined (x, y, width, height). This is particularly important when using
repeatable patterns in SVG. This commit adds this attribute to the lists
of known properties.
Closes#1548
Add harmony transform support in browser
Fixes#1420. Moved some code around in the merge to account for more
changes in the transform code.
Conflicts:
vendor/browser-transforms.js
binds static methods on the descriptor to the component's actual constructor, so that `foo.constructor.bar()` and `Foo.bar()` run with the same `this`.
The Ballmer Peak XKCD suggests that it's a graph of ability, rather than bug frequency, which should be inversely correlated with ability. A simple change of the wording fixes this terrible mishandling of Ballmer Peak data.
This one was an actual behavioral bug rather than a bug with the tests; our intention was that the first element from the `defaultValue` array would remain selected but IE seemed to be choosing the last one instead. Now we set the value for uncontrolled components in componentDidUpdate when switching from multiple to non-multiple to ensure that a consistent option gets selected.
Test Plan: Ran the ReactDOMSelect tests in jest, phantomjs, IE10, Chrome, and Firefox. Also tested an uncontrolled select manually to make sure that nothing crazy happened when switching between options.
Previously this was failing because iframeDocument.body wasn't properly initialized. Creating the document this way seems to work in all environments
Test Plan: Ran the test in jest, phantomjs, IE10, Chrome, and Firefox.
Fixes bug introduced in c62c2c5.
Test Plan: Tested that the onLoad event was properly triggered on an image. Didn't test onError but I can only assume that it works equally well.
Currently, an `onBlur` creates a new todo on `TodoTextInput`. This makes sense for existing items but not for new items. I.e consider the following:
1. cursor on new item ("What needs to be done?")
2. click 'x' on the first item.
This results in two actions being fired:
1. TODO_CREATE, with an empty string as 'text'
2. TODO_DESTROY
The proposed fix doesn't send a TODO_CREATE if `text.trim() === "")`
I ran into a really difficult-to-debug issue with a React app with SVG
elements. Christopher sat down with me for a while and we finally figured out
that the browser was moving non-SVG elements out of a parent `<svg>` node which
triggered the `processUpdates()` invariant. This updates the error message
thrown from there to include this scenario in the possible issues list.
Fixes#1169.
This is a more robust way of fixing what MobileSafariClickPlugin previously tried to. Now even if you don't want anything to do with touch events, click events still work properly.
Test Plan: Added a click handler to an `<img />` element and triggered it in the iOS simulator -- it didn't execute before.
Not removing them resulted in leaks as we would hold on to removed nodes forever.
This really showed up with images and the load event where we would unmount and create a new img with the same react id as the old one. We properly cleared and primed the caches but we would handle the load event for both nodes. We would eventually hit an invariant in that path as we tried to handle the event for the removed node, which no longer matched the node we had in the cache.
By forcefully removing the listener, we'll avoid this problem entirely and we should leak fewer DOM nodes.
This strategy avoids a runtime check for every set (as opposed to using a mutation method).
Test Plan: Verify that changing className works on a div and a rect in latest Chrome, latest Firefox, IE9. Verify that the div works in IE8.
If the event is on the window object, topScroll, for instance, the topLevelTarget will not have getAttribute defined. Restore the previous `|| !topLevelTarget.attributes` check to avoid an error on every scroll.
I find myself often using (modified) examples to test in IE and it's a pain to have to add the shims in every time. Might as well just add them in always.
Can be run with `node_modules/.bin/jest` for now; didn't want to disturb the grunt setup.
Right now one test fails with:
```
FAIL browser/ui/__tests__/ReactDOMComponent-test.js (1.423s)
● ReactDOMComponent › updateDOM › it should update styles when mutating style object
- Expected: '0' toEqual: '0.5'
at Spec.<anonymous> (src/browser/ui/__tests__/ReactDOMComponent-test.js:99:33)
```
which I can only assume is a jsdom problem -- no other asserts fail.
cf. #1376.
This is useful for SVG. Dynamically adding and removing `<title>` elements in SVG still won't work properly because of getMarkupWrap but this at least lets you include it in initial render and then unmount the entire `<svg>` without problems.
Allow tools like grunt-react to include inline source maps in the
generated JavaScript. Browserify can then combine these source maps when
bundling everything together.
Usage:
```
var transform = require('react-tools').transform;
var output = transform(jsxContent, {
sourceMap: true,
sourceFilename: 'source.jsx'
});
```
The `output` will have an inline source map comment appended.
The previous examples didn't properly work when 1) a Store callback does
waitFor on Stores that haven't been reached yet and 2) a Store callback
waits on another Store that is already waiting.
The updated example uses constructs Promises up front and then
asynchronously resolves them.
For boolean-like objects, I've added hasOwnProperty checks in addition to the existing truthiness check even though for most of these dicts, we leave out false keys instead of setting them explicitly to false.
In DOMPropertyOperations, we don't need to check hasOwnProperty if the property is in isStandardName because (with the exception of getPossibleStandardName) the dicts on DOMProperty will now be consistently populated with every valid attribute.
I implemented this by checking for `type="text/jsx;harmony"`, since this
has a bit of a cleaner implementation rather than parsing a JSON object
out of a data attribute. If in the future there are other options to
pass, it would make sense to move to a system like that.
Along with adding support, there is also a new example added that's
the basic-jsx example with Harmony syntax.
With this, multiple setState calls triggered by a componentDidUpdate handler (or similar) will be batched together, regardless of if the original setState call was in a batching context.
I also cleaned up some inconsistencies with the order of component updates and callbacks in situations where one component's update directly causes another to update.
Fixes#1147. Helps with #1353 and #1245 as well, though doesn't completely fix them yet.
Test Plan:
grunt test
Currently require('ReactDefaultPerf').printExclusive() shows render
time and aggregate componentMount time.
This makes it show exclusive mount time by tracking a stack.
Fixes#1505.
Confusingly, the uglify-js package provides the `uglifyjs` binary and `npm run-script build` didn't work if uglify-js wasn't installed globally; now it does.
This copies the propType and contextType validation to a wrapper around the
descriptor factory. By doing the validation early, we make it easier to track
down bugs. It also prepares for static type checking which should be done at the
usage site.
This validation is not yet active and is just logged using monitorCodeUse. This
will allow us to clean up callsites which would fail this new type of
validation.
I chose to copy the validation instead of abstracting it out to a common abstraction. This is just an
intermediate step to avoid spamming consoles. The original validation in the instance will be deleted as soon as we can turn on the warnings at the callsite. Copy+Delete makes this a more a much cleaner diff review/history.
Additionally, getDefaultProps are moved to become a static function which is
only executed once. It should be moved to statics but we don't have a
convenient way to merge mixins in statics right now. Deferring to ES6 classes.
This is still a breaking change since you can return an object or array from
getDefaultProps, which later gets mutated and now the shared instance is
mutated. Mutating an object that is passed into you from props is highly
discouraged and likely to lead to subtle bugs anyway. So I'm not too worried.
The defaultProps are now resolved in the descriptor factory. This will enable
a perf optimizations where we don't create an unnecessary object allocation
when you use default props. It also means that ReactChildren.map has access to
resolved properties which gives them consistent behavior whether or not the
default prop is specified.
This is a breaking change since it can affect how mapping over children and
transferPropsTo works together with defaultProps.
KeyboardEvent now normalizes "charCode", "keyCode", "which" across all browsers
KeyboardEvent has partial "key"-support for KeyDown/KeyUp and full "key"-support for KeyPress.
KeyboardEvent, MouseEvent and TouchEvent now has "getModifierState", polyfill when not implemented.
Previously we were escaping both in createMarkupForStyles and then in createMarkupForProperty; now we escape only in the latter (otherwise the hypothetical style name `b&ckground` would become `b&amp;ckground`).
Test Plan: grunt fasttest
Some Android versions have the "transition" and "animation" properties
set on element style objects despite not supporting un-prefxied animations
and transitions. This change adds an additional sanity check to make sure
the correct event handlers are added for transition groups.
In IE10/11, it is apparently possible to have a Selection or Range object that has the following properties:
- `anchorNode` === `focusNode` (Selection) or `startContainer` === `endContainer` (Range)
- `anchorOffset` === `focusOffset` (Selection) or `startOffset` === `endOffset` (Range)
- `isCollapsed` === `false` (Selection) or `collapsed` === `false` (Range)
As defined in http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html, this doesn't really make sense. Since the nodes and offsets are the same, the "collapsed" value should be `true`.
Moreover, when calling `selection.toString()` in this case, it appears that the entire text contents of `body` -- including `<script>` tag contents -- are considered within the selection. I thought maybe the selected nodes were missing from the DOM or something, but no, they're there.
Sidestep all of this in `ReactDOMSelection` by calculating the `collapsed` property manually and setting the selection length directly to zero if it is actually collapsed.
Side note: I think that for selection restoration on contenteditables, we shouldn't try to do this offset calculation. We should just use the structure provided natively (nodes and offsets) since we can restore using that structure as well.
Previous behavior: `transferPropsTo(<div style={{color: 'red'}} />)` would get `color` overriden if we transfer in a `style={{color: 'blue'}}`. This is inconsistent with how other props are transfered.
This simply reverses the order of arguments.
closes#1435
This makes it a little easier to add SVG properties. It also makes use of that injection that we claim is easy to use and will likely start playing a bigger part soon.
Closes#1009
We're now trying to access document directly at require time. Wrapping in a function prevented that before. But we can simply check what environment we're in first.
React components have _mountIndex, that looks like it is their order in DOM.
If you swap 2 elements in DOM, their order in children array isn't changed, but their _mountIndex is
There is no point in doing the feature detection on every call, unless there is an IE bug where it is not sure about which support for selection it has (totally plausible).
Adds a PropType that checks for proper use of the ReactLink API and optionally validates the type of value passed in via the link. Basically, it's a wrapper around PropTypes.shape that hides the implementation of ReactLink.
The `updatedChildren[j].parentNode.removeChild(updatedChildren[j]);` line below can fail if (1) we're moving/moving the same node twice or (2) the node we're looking for is gone completely. This makes it easier to distinguish between the two cases.
Perf shouldn't be a concern here because this is DOM code and invariants are fast in comparison.
Test Plan: grunt test
The report itself is more or less useful because it detects stuff like
big objects (e.g. CSSProperty) as being too complicated. Furthermore, afaik
nobody refactors the code based on what the report says =).
Fixes#1408.
Test Plan: Copy each code snippet into jsbin; type in the text box successfully; click the button and see the input clear (and in the second example, get focused).
In the future we could consider wrapping the entire public API (renderComponent, setProps, setState, etc) in this check but this should do for now.
Test Plan: grunt test
8855d6153e gave more accurate error messages for date and regexp by returning 'date' and 'regexp' respectively from `getPropType`.
However, for the object primitive check, which compares the instance passed with `getPropType's` return string, `object` !== 'date'.
This adds special hanlding for those.
This uses the return value (an Error or nothing) to indicate whether a prop passes validation or not. It used to be done through calling `console.warn` as a side-effect, except this didn't work well with and `oneOfType`, which calls each validator.
The solution was to insert a `.weak` prop to each validator to suppress the warning message. This is overkill and also doesn't work well in because it increases the potential API surface. Plus, letting the validators warn it can't be easily used for logging, especially for custom validators.
So `.weak` is no longer needed: fixes https://github.com/facebook/react/issues/863.
Backward compatibility for custom validators: since they didn't return anything and directly call `console.warn` or something, this doesn't break them.
Improvements:
- `arrayOf`, `oneOfType` and `oneOf` got better message now, since they can get hold of their validator's message and output that instead of a generic `warning: bla`.
- More complete tests, including testing custom types and `isRequired` on everything.
Bug fixes:
- oneOfType(...).isRequired didn't work. The workaround was to use `oneOfType(a.isRequired, b.isRequired, ...)`. This means `oneOfType(a.isRequired, b)` doesn't make sense. The new version simply makes `oneOfType(...).isRequired` possible.
- `oneOf([true])` worked for 'true' boolean because it converted everything to string before comparing. It no longer does.
- `oneOf([true]).isRequired` didn't work.
(see #1294)
The following steps also have an ajax function, but the 'error:' param
is gone after #13:
#14#17#19#20
This may be superfluous, but it helped me find an error with something I
was doing - Namely, in my .json file, I had single line javascript
comments ("//") that I copied from the tutorial. I couldn't find the
issue on later steps, but was able to see my issue when the error
handler complained about an unexpected "/" in my file in step #13.
Fixes#1227.
It seems rare that event handlers in two roots nested in the DOM will update the same component in the same tick, but if that happens, the updates should be batched together.
This was temporarily needed since clone on mount introduced a cyclic reference
in __DEV__. This reverts that change since we now have descriptors.
To avoid a problem where toJSON may collide.
Previously, this threw (in `__DEV__` only) in `ReactCurrentOwner.current.constructor.displayName` because `ReactCurrentOwner.current` is null:
```
React.renderComponent(<div>{{1: <div />, 2: <div />}}</div>, document.body);
```
Looks like while rewriting @petehunt forgot to remove this block.
See: 9ac27cb551
This block used to contain the only `runNextTick` ocurrences in the whole project.
No tests broken after removal, no documentation affected.
The other dispatch utils clear these out and I found a bug where they weren't being cleared out.
I'm thinking this should probably be done in the `SyntheticEvent` constructor but at least this way it's consistent. Also, I know no one else uses `executeDispatchesInOrderStopAtTrue` except the `ResponderEventPlugin`.
This mirrors the react-tools API; it doesn't include support (yet) for transforming `<script type="text/jsx">` blocks with the ES6 transforms, mostly because I don't have a good API in mind there.
Test Plan:
Ran
JSXTransformer.transform("var two = () => 2;", {harmony: true}).code
in Chrome's dev console and got back some ES5 code.
Add support for Opera <= 12 (Presto) in `BeforeInputEventPlugin`.
It turns out that Opera 12 has a `TextEvent` in `window`, but doesn't actually fire any input events. Even `input` apparently doesn't fire. Fall back to keypress handling in this case.
Browsers that natively support the `textInput` event appear to have a bug: when preventing default behavior for a `textInput` event occurring for a spacebar keypress, the character is prevented from being inserted **but the browser scrolls down**.
Minimal repro example: http://jsfiddle.net/salier/bX4fw/
This is ridiculous, since scrolling makes no sense when the user is focused in a textinput or contenteditable. Preventing default at the `textInput` stage should mean to prevent the character from being inserted, and should have no impact at all on scrolling behavior. I have filed this as a Chromium bug (https://code.google.com/p/chromium/issues/detail?id=355103) but I'm not going to hold out much hope that they'll fix it.
To resolve this, I'm special-casing the spacebar character at the plugin level, in `BeforeInputEventPlugin`. I looked for ways to do this at the component level, but it seems to me that this is simply a browser bug and it's cleaner to handle it there.
In browsers that can use the native `textInput` event, I'm checking the code of the pressed key. If it's the spacebar, we dispatch the synthetic event as if there were no native `textInput` event -- as if we were running Firefox. Then, if the synthetic event is not canceled and we make it through to the native `textInput` event, bail if the character data is a space character.
`renderComponent(<div style={invalidType}/>, container)` throws correctly,
but not when it's called a second time (i.e. updating rather than mounting).
It goes through `ReactDOMComponent.updateComponent` but there wasn't a
props assertion there.
(Removed the assertion in `receiveComponent`)
This diff introduces `TextInputEventPlugin` and `SyntheticTextInputEvent`, which are based on Webkit's native `textInput` event.
In Chrome, Safari, and Opera, the `textInput` event fires prior to the insertion of character data into the document. For normal typing, for example, thevent sequence is: `keydown`, `keypress`, `textInput`, `input`, `keyup`. The `textInput` event contains a `data` field corresponding to the character data that will actually be inserted.
There is also a `beforeinput` event described by http://www.w3.org/TR/DOM-Level-3-Events/#event-type-beforeinput, and this is essentially that event, so it may make sense to rename the plugin.
This event is especially useful because it solves a number of issues we can't currently handle with only keypress and composition events:
- **Windows Chrome: Trailing characters discarded in Korean IME.** For instance, `안녕하세요` becomes `안녕하세` with the final character discarded by the final `compositionend` event. The `textInput` event fires correctly with the final character.
- **Windows Chrome: Special characters discarded in IME.** Certain ideographs are discarded in IME mode. In Japanese, typing the ideographic space character is not represented by keypress but //is// represented by the subsequent `textInput`. This issue also applies to punctuation characters in Chinese.
- **OSX Chrome: Characters from palette discarded.** Inserting characters from the OSX character palette fails, since no keypress is fired.
The plugin is useful for Firefox and IE. For these, we record inserted characters via keypress and compositionend events and dispatch the synthetic event with these characters as the `data` field to match the native `textInput` event.
- Firefox has no corresponding `textInput` event and has not yet implemented `beforeinput`.
- IE has a native `textinput` event, but it fires after the DOM mutation has already occurred, so it isn't very useful as an analog to the Webkit version. I'm just not going to bother with it.
mapObject fits better with other module names ("flattenChildren", "traverseAllChildren" etc.) and highlights that it only works with objects - which is going to be more important once we'll have an ES6 Map polyfill.
This way it doesn't end when some random element elsewhere on the page has an ending transition.
It must be noted that this is not a complete fix. If you have multiple transitions on the element, it still ends when the first ends.
I ran into this not working (the transition ends almost immediately, because some unrelated transition ends). This fixes it for me, but I was wondering whether this cornercase was considered, and whether the other cornercase (multiple transitions) was considered.
I think it's very hard to get this correct, and think it might be better to make the timeout explicit, or at least allow to set it explicit, and fall back to this behaviour. But I'm really interested in feedback on this one.
These tests can still be run in the browser using `grunt test --debug`.
This is a repeat of 42f8d155f8. For posterity, we
do this because Phantom has a problem with Object.freeze and the test runner
can't do __DEV__ right (because we get rid of that in the build step).
Let's start logging objects as maps for children. We may want to deprecate this
and replace it with ImmutableMap and Map data structures instead.
This should ideally be logged in the recursive function but since that loses the
scope of where these children are passed it's easier to start tracking them
here to get an idea of how frequently and where it's used.
While looking up a detail of how `transferPropsTo()` works I noticed that we never check `TransferStrategies.hasOwnProperty(thisKey)` when merging props, just `newProps.hasOwnProperty(thisKey)` and a truthy test for `TransferStrategies[thisKey]`. This means that if our `newProps` has keys like `toString`, `valueOf`, or `constructor` etc. set, we will pull these functions off `TransferStrategies` and invoke them when merging props. In most cases this will just result in a failure to merge and some code without side effects being run but in the case of `valueOf` it will actually generate an exception.
I'm thinking that setting up `this.refs` in `mountComponent` is better than `construct`. Followed the same pattern as `ReactComponent.Mixin` and nulling out
the value in `construct` and setting it to its initial value in `mountComponent`.
This bites people all of the time. Until we have a better solution, let's just make the error message more actionable (most people don't know how the DOM
gets unexpectedly mutated).
The component that gets passed into renderComponent isn't guaranteed to be the
instance that gets mounted. We want to clone the instance.
Unit tests need to reason about the mounted instance. The first code mod changes:
ReactTestUtils.renderIntoDocument(<identifier>)
into
<identifier> = ReactTestUtils.renderIntoDocument(<identifier>)
Using this scripts:
scripts/bin/codemod -m -d ~/www --extensions js \
'^(\s*)ReactTestUtils\.renderIntoDocument\(\s*([$a-zA-Z0-9_]+)\s*\)' \
'\1\2 = ReactTestUtils.renderIntoDocument(\2)'
In the second case I do the same for React.renderComponent. However, there are
alot more unnecessary matches so I only codemod if the same identifier occurs
later in the file.
scripts/bin/codemod -m -d ~/www --extensions js \
'^(\s*)React.renderComponent\(\s*([$a-zA-Z0-9_]+)\s*?,(.*?\n?.*?\s\2\b)' \
'\1\2 = React.renderComponent(\2,\3'
And one more for ReactMount.renderComponent used by internals.
scripts/bin/codemod -m -d ~/www --extensions js \
'^(\s*)ReactMount.renderComponent\(\s*([$a-zA-Z0-9_]+)\s*?,(.*?\n?.*?\s\2\b)' \
'\1\2 = ReactMount.renderComponent(\2,\3'
This still matches many unnecessary cases where the second occurance of the
identifier is a redeclaration or comment. But this code mod doesn't hurt in
those cases.
Finally I have to do the same for:
this.<identifier> = React.renderComponent(this.<identifier>,
This is a common pattern for production code but not tests. Some of these call
sites will likely break when we move to true descriptors.
scripts/bin/codemod -m -d ~/www --extensions js \
'^(\s*)React.renderComponent\((\s*)this\.([$a-zA-Z0-9\_\.]+)\s*?,' \
'\1this.\3 = React.renderComponent(\2this.\3,'
We have unexpectedly had to shut Shirtstarter down, so it won't serve as a good React.js example any more unfortunately -- sorry for the documentation churn.
This is the first step towards descriptors. This will start cloning the
component when it's mounted instead of mounting the first instance.
This avoids an issue where a reference to the first instance can hang around
in props. Since a mounted component gets mutated, the descriptor changes.
We don't need to clone the props object itself. Mutating the shallow props
object of a child that's passed into you is already flawed. Those cases need to
use cloneWithProps. A props object is considered shallow frozen after it leaves
the render it was created in.
Optimizations and fix for JSXTransformer build.
Dropped dependency on emulation of Node.js native modules.
Added deamdify step for JSXTransformer build.
We found that the component would break if we set any statics with the
value 0. It turns out @chenglou already ran into this with
d71736b3ed but the statics code was copied
earlier, and still has this falsy check. Made the same change, updated
the unittest.
After we run `require('mock-modules').dumpCache()`, the object exported by
the `emptyObject` module will no longer be identical to previously
exported objects, so tests like `expect(component.refs).toBe(emptyObject)`
will fail.
Note that this behavior only manifests itself in tests, because of course
we do not call `dumpCache` in production code.
We could consider storing the `emptyObject` globally to thwart the effects
of `dumpCache`, but it's more idiomatic simply to re-`require` the latest
version of `emptyObject`.
I don't think this particular codepath was exercised at all (because all the callers call deleteValueForProperty) but this fixes a bug here nonetheless.
If no refs are rendered, `this.refs` is undefined. This is bad since it deopts & is hard to look for. Instead we should make `this.refs` an immutable empty object.
This adds an instrumentation hook for logging so that we can monitor invalid API
usage before we're ready to issue a warning.
I took the opportunity to update some console.warns to use the warning module
instead. The remaining console.warns
will be replaced by the warning module after we've cleaned up the callsites.
When IE8 focuses a disabled item, it throws
This makes sure the we're not focusing the item during selection restoration/autofocus when the element's disabled.
There were these two lists of JSX tools at Complimentary Tools
and Tooling Integration, that were a bit out of sync with each other.
Bring them together and add a link to the former from the latter.
Dealing with immutable data is hard. This provides a simple helper (ported from the IG codebase) that makes dealing with immutable JSON data easier. Designed to be familiar for people who use MongoDB.
This is part of what Sebastian suggested. We require it into every component that explicitly needs it and inject it as a default mixin for composite components in
the browser environment. This change frees us up to inject everything in ReactComponent.
Most of the time this is what you want to do, so I've renamed what was Simulate to be SimulateNative.
Now Simulate.change does what you expect, so this fixes#517 and fixes#519.
grep -rl 'Copyright 2013 Facebook' static_upstream | xargs perl -pi -w -e s/Copyright 2013 Facebook/Copyright 2013-2014 Facebook/g;'
Not going to check in a script to do this since it will just change every year.
Closes#1006
Fixes#1124.
I didn't add `volume` because it requires more complicated logic to control properly and I didn't add `paused` because to set it we need to call play() or pause() -- perhaps a mutation method is appropriate.
Two improvements: make sure we set `done = true` when an error message is
received, so that the test output contains the error message instead of
eventually timing out and displaying nothing useful; and increase the
timeout for this particular test from 5000ms (the default) to 20000ms.
reverts 23ab30ff87 because the issue it fixed doesn't seem to be a problem
anymore. textContent should be better for more things anyway, as the
original 309a88bcf6 indicates. It should be faster because innerText
requires layout.
This also allows us to use strings with newlines in our rendered output
and have confidence that they will render the same on subsequent
re-renders. This is especially useful for es6-style backtick multi-line
strings. This will be more consistent as textContent is supported almost
everwhere so we won't have differing behavior between webkit and
firefox.
see https://github.com/facebook/react/issues/1080
ReactDefaultPerf:
* Show times as float instead of string. This means they're sortable.
* Add count columns to all types and average to exclusive time.
* Include mountComponent where updateComponent time is measured.
* Increment count on _renderValidatedComponent instead of update.
ReactDefaultPerfAnalysis:
* Return counts with all summaries.
Split the summary functions into a separate module, and add the ability to view a lot of all DOM operations. Removed DOM timing since it was incorrect. Will potentially replace with a
dropped frame counter in the future.
This logs DOM ops for a given reconcile. Based on which components rendered and which ones *actually* caused DOM updates we can find
opportunities to add shouldComponentUpdate() methods.
Inclusive time is still not that helpful w/o looking at what actually resulted in DOM ops. However, this is better than what we have today and will serve as a building block.
I blacklisted everything but composite components -- hopefully that's OK.
The key idea here is that you're always rendering `this.state.children`, not
`this.props.children`. When combined with `cloneWithProps()` this means we can
keep them in the DOM as long as we want. We add new children and reactively
update existing ones using `setState()` inside of `componentWillReceiveProps()`
so `this.state.children` always has the latest versions of components. Since we
may be keeping old components around that are no longer in
`this.props.children` we need a way to figure out where they should be inside
of the combined `this.state.children` list. `ReactTransitionChildMapping` does
this for us.
Based on that infrastructure we can build the interface we always wanted: enter
and leave lifecycle hooks.
When a component is added to the DOM, `componentWillEnter(callback)` gets
called. Call the callback when you're done animating and `componentDidEnter()`
will be called.
When a component is about to be removed from the DOM,
`componentWillLeave(callback)` gets called. Call the callback when you're done
animating and `componentDidLeave()` will be called and the component will
*actually* be removed from the DOM. It won't be removed until you call the
callback.
These also handle "concurrent" changes. If you "stack" enter/leaves of a single
component before the animation has completed, it will block out all of those
animations until the current animation completes, and then finally it will
animate 0 or 1 times to get itself into the desired current state. This is what
differentiates `componentWillEnter()` from `componentDidMount()`.
The next step would be to build `componentDidReorder()`.
I've built `ReactCSSTransitionGroup` which is identical to the old
`ReactTransitionGroup` and codemodded the callsites.
With #1021 and #1022, I believe this makes it so React never wraps user code in a try/catch. I left in the calls to ReactErrorUtils.guard because it sounds like FB code finds them useful.
This creates a membrane around the React component prototype. It warns if you
try to access properties on the component before it's unmounted. Before it's
mounted, it should be considered a descriptor and not an actual instance.
The workaround, for unknown types, is to access the constructor using
component.type which has static methods on it.
All of this is provided by the react package now, so there's no point in having
it available in multiple places. We *may* go back on that in the future for
shipping test utils, but for the time being, this is better for all.
Also added tests for PooledClass.
Noticed that some places use `ReactReconcileTransaction.release(transaction)`, when `transaction` might be of another class, say `ReactServerRenderingTransaction` (still a Github PR). This catches that.
If a transaction wrapper's closer throws (such as flushBatchedUpdates in ReactDefaultBatchingStrategy) then we still want to properly deinitialize the transaction by setting isInTransaction to false. Without this, we can't reuse the transaction object (in this case, all future batched updates would fail because nested transactions aren't allowed).
Removed uglification for separate files since it significantly slowed down build (browserify:min became 26 sec instead of 110, same for :addonsMin) while gave economy in ~70 bytes for min+gz version.
The documentation states that React.renderComponentToString
'uses a callback API to keep the API async', but the
implementation is actually synchronous. In order to maintain
this contract the callback should always be called
asynchronously or be change to a synchronous API.
As per the discussion of pull request 982, the API should
be changed to a synchronous one.
Recently learned that components passed into `React.renderComponent` may not be the ones actually mounted. Also learned that it returns the mounted component. Added some documentation describing this.
Number('.1') === 0.1, and react uses dot-prefixed keys
for children. Whoops. Nuke the non-numeric requirement, and just
check a regex. This seems performant enough in micro-benchmarks:
http://jsperf.com/numericlike
We've been able to use `querySelectorAll` in all the browsers that we
support for some time now, but we haven't been able to test code that uses
it in the older version of `jsdom` that we were using, until recently.
Besides the general goal of modernizing our code, the impetus for this
specific change is that I'm trying to support testing without having to
render nodes into an actual document. The `.getElementsByName` method is
only defined on `document` and only works if the nodes you care about are
contained by the document.
On the other hand, `querySelectorAll` works on any DOM node, and allows a
more precise selection of just the `<input type="radio">` elements that
have the appropriate name.
IE8's implementation of `querySelectorAll` supports attribute-based
selectors, which is all we need here.
Little-known fact: instead of writing copies of compiled module files to
build/modules/, the bin/jsx-internal script actually just makes hard links
to the master versions of files in the .module-cache/, so re-populating
build/modules/ is very inexpensive.
Closes#856.
Rethrowing errors makes debugging harder. This makes it so that an exception in a render method can be caught using the purple stop sign (or the blue one, of course) in Chrome.
This codemods to shim any old-style JSX whitespace so that it renders the same as before.
Basically it sticks explicit `{' '}` spaces in where spaces are no longer implicit.
`cloneWithProps` uses `ReactPropTransferer`, which ignores the `key`
prop. See https://github.com/facebook/react/pull/713
However, this is not the case with `cloneWithProps` because when someone
is cloning a component and provides a key, they mean for the clone to
take it.
We've talked about this perf optimization for a while now. This prevents us from re-reconciling components that are above the component being
reconciled in the owner hierarchy.
See [Commoner's README.md](
https://github.com/benjamn/commoner#generating-multiple-files-from-one-source-module)
for further explanation of the new functionality.
Among other potential benefits, this upgrade allows us to generate source
maps as standalone files rather than appending them inline to every
compiled module file under `build/modules/` (see #833).
When React moved to attaching top-level event listeners on-demand, not all of the dependencies for `ChangeEventPlugin` were set. This led to `onChange` events not firing under certain circumstances. For example, listening to `onChange` on a checkbox will not work because it relies on `onClick` (unless something else on the page was listening to `onClick`).
The intention of the `npm-react/**/*` rule was to copy recursively but it would have flattened any nested directory structure. I changed the `build/modules` rule to copy recursively as well, which is necessary for `ReactTestUtils` to be able to require `test/mock-modules.js` successfully. (`ReactTestUtils` isn't included in a clean `npm-react` build currently but it will be in the future.)
This also makes running ART tests more practical.
It's only used here, so let's just inline this and get rid of the additional module.
Also it will make people like this guy happy: https://github.com/facebook/react/issues/900
(of course he might be even more happy if he wasn't using MS TFS....but that's a much bigger diff, and not one I can write...)
This diff introduces PropType.shape which lets you type an object. PropType.object was already defined and since it isn't a function I couldn't really overload the meaning to also accept a type list. Instead of doing hackery, I decided to name it `shape`.
An example where this could be used is style:
```
propTypes: {
style: PropTypes.shape({
color: PropStyle.string,
fontSize: PropTypes.number
})
}
```
Fixes#208. If you attempt a state update with a bad state then the render will fail (and the DOM won't change) but if you switch back to a valid state later then it'll rerender properly.
This is an alternative, less-invasive, fix for #891.
Test Plan:
On http://jsbin.com/OqOJidIQ/2/edit, got timings like
[75, 56, 30, 36, 27, 27, 28, 32, 27, 27, 28, 31]
instead of the old
[75, 729, 46, 32, 28, 34, 26, 27, 27, 30, 26, 26].
I also added a counter to getID and saw it was called 3014 times instead of the old 636264. (3014 is the number of nodes (3000) plus 3 calls that happen for the initial render and 1 for each of the 11 renders after that.)
add the ability for React propTypes to accept an `any` type: `someProp: React.PropTypes.any`.
This is more useful when combined with `.isRequired`, to enforce that _something_ is passed:
`someProp: React.PropTypes.any.isRequired`
Input elements of type `checkbox`, `hidden`, or `radio` can have a `value` without `onChange`. Also, if the input is `disabled`, who cares that it doesn't have an `onChange`?
This is a follow-up to #803.
In jsdom (used for internal testing), `<iframe>` does not properly create a default document. This makes the `EnterLeaveEventPlugin` tests work for jsdom, too.
Open source does not need this because it uses PhantomJS.
In b0431a5 I added the check in the wrong place which could cause the warning to be shown because of key changes rather than owner changes like the warning suggests.
This test is expected to throw but because of ReactErrorUtils.guard
which uses console.error in __DEV__ it also logged the invariant error
to the console. This change fixes it by temporarily stubbing out
console.error.
Fixes#531
Final part of server rendering cleanup. We should only support full-page rendering when server rendering is involved since
otherwise it's slow and can crash browsers when you start adding and removing document roots. This diff removes the magic
innerHTML code (since that will be handled by the server rendering piece) and adds the right assertions and errors.
Because there's no longer a dangerous of accidentally nuking the whole page, I removed allowFullPageRender which is yet another
internal we no longer need to expose.
These are dangerous from a cross-browser perspective. I think supporting efficient reactive updates will be prohibitively
expensive and we'll never prioritize it. Instead of killing this capability entirely, let's just throw on the dangerous cases.
There will be a few follow-up diffs
This ensures we don't add displayName in the transform if it's already been
defined. This is especially important when in strict mode, where duplicate
properties in an object is an exception.
Use the `clipboardData` object available on `window`, if it's not available on the event object. This allows us to support including the `clipboardData` in cut/copy/paste events in IE.
If you're writing a test that involves a mocked component that normally
returns a `<li>` tag from its `render` method as the root element, mocking
it with a dummy `<div>` probably won't work, so you'll want to set
MyListItemComponent.mockTagName = 'li';
The change to the `.mockImplementation` line makes sense because
`ConvenienceConstructor` is more or less synonymous (for these purposes)
with the wrapper that was previously used:
function() {
// This `this` used to be `null`, technically, but
// ConvenienceConstructor doesn't pay attention to `this` anyway.
return ConvenienceConstructor.apply(this, arguments);
}
This had a higher probability of collision than originally thought (bad math). This makes the strategy injectable and provies a
no-collision version on the client and an unlikely-to-collide version on the server.
what if you want to change the props of a child? This is my first attempt which lets you clone a child and transfer some custom props to it.
There is a fundamental issue with refs here. Since the component is cloned the ref will be broken. And since we can clone multiple times, it might not make sense to support repairing refs.
Fixes#767. This essentially reverts 738de8c.
We could store some sort of flag to silence the console error here but since we've made significant improvements in markup wrapping, this error is fairly rare now. We'll also have validation of node structure soon in #735.
- Add html5shiv so that HTML5 elements like header, footer, etc can be styled
- Remove a couple uses of :first-child/:last-child which IE8 doesn't support
Fixes#708.
Test Plan:
In IE9, tested a controlled text input with the event handler on a containing element, as in the fiddle linked in the original issue. Also tested a controlled radio button as the logic there differs within ReactDOMInput. In both cases, I was able to interact with the controls.
Now when a `key` prop appears, its value is always honored. This means that in the root component or as an only child, changing key will cause remounting; in a `children` object, the `key` prop will be joined with the object key to form a two-part key.
Fixes#590.
It changed React Playground to add a required props but unfortunately didn't update the call sites of the front-page. I don't think it should be required so I'm just making it optional and providing the correct default value.
Test Plan:
- Open the front page and make sure examples are working
- Open /react/jsx-compiler.html and make sure it is working
- Open /react/html-jsx.html and make sure it is working
Since we can use props to pass React Components, we should have a better way of validating these props than just `object`. Having a prop type `component` will allow us to safely assume that the passed prop IS a component.
This is a follow-up the to previous commit and does two things:
- Moves `ReactMount.ATTR_NAME` to `DOMProperty.ID_ATTRIBUTE_NAME`.
- Adds `DOMPropertyOperations.createMarkupForID` and uses it.
We have this really nice method for safely creating markup for an HTML
attribute, `DOMPropertyOperations.createMarkupForProperty(...)`. Let's
use it to create the ID attribute markup, too.
These should be included so that anybody can build and update the docs
with as little confusion as possible.
I've left the directory in .gitignore so additions need to be
intentional as part of a release.
This reduces the time taken by `grunt populist:test` from 7s to 550ms,
which should make @spicyj especially happy.
Relevant commits from the `populist` and `ast-types` repositories:
9863ad16c0dabef2a4ac
This fixes merging of `propTypes`, `contextTypes`, and `childContextTypes` so that we actually merge (instead of only taking the component or last mixin).
Using props to initialize state is completely fine; the issue is using state as a "cache" for values calculated based off of props. This title makes it more clear.
Chrome gives the warnings
```
body.scrollLeft is deprecated in strict mode. Please use 'documentElement.scrollLeft' if in strict mode and 'body.scrollLeft' only if in quirks mode.
body.scrollTop is deprecated in strict mode. Please use 'documentElement.scrollTop' if in strict mode and 'body.scrollTop' only if in quirks mode.
```
the first time getUnboundedScrollPosition is invoked. This fixes it. (All modern browsers support `pageYOffset`; IE 8 doesn't but works properly with `document.documentElement.scrollTop` except in quirks mode which React doesn't support.)
In the case of having an animated node which is, after the leave-transition has been activated, then re-added in a render call causes React to 'break'. This is especially noticeable if you spam to removal and re-addition of an item in a ReactTransitionGroup.
This fix simply stops the leave transition and restarts the enter transition.
This reverts https://github.com/facebook/react/pull/576
This approach mutates the default props for the instance on each update,
which causes incorrect behavior. discussed with @balpert. can look into
cloning but this unbreaks.
This leaves statics as a way to define static methods and properties
that will be accessible on the return value of `React.createClass`
without changing the current spec.
It is valuable to know when the number of children in a TransitionGroup is going
to increase or decrease, since we might want to apply extra animations.
For instance, when used with overflow:auto, we might want to apply different css
based on it overflowing or not - to do this we need to calculate this after new
nodes has entered and after nodes has been removed.
This moves the static properties off of the root object and into
a 'statics' property. Then they are made available on the constructor so
they can be used directly and in mixins.
Pull request #526 updated the behavior of vendor/constants.js without
changing any source files or the bin/jsx-internal script, so files that
should have been rebuilt (like utils/__tests__/ImmutableObject-test.js)
were not automatically rebuilt (unless you knew to do `grunt clean` or
`rm -rf .module-cache` manually).
This commit allows us to bump a version number when we know the transform
toolchain has been altered in a way that will not be visible to
commoner/jsx.
With this convention, if we reset to an older revision (e.g. during a git
bisect) and the appropriate cached module files are still in the
.module-cache/, they can be used without rebuilding. That's why I prefer
this approach to just deleting the .module-cache/.
Closes#104.
Closes#496.
Closes#530.
Summary:
e.g.
propTypes: {
foo: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.number
]);
}
to do this, I exposed a `.weak` chainable validator that returns instead of throws, e.g.
React.PropTypes.string.isRequired.weak
React.PropTypes.string.weak
which returns true or false. Technically, `React.PropTypes.string.weak.isRequired` also exists, but `oneOfType` will never call it. Might be useful to people creating custom validators though.
Since we use keyMirror() and invariant() messages are only shown in __DEV__, we don't have to do manual constant->string translation. Also fixes a few
undefined keys that just happened to work before.
It doesn’t make much sense to generate a random key for each todo render, because it will re-draw all todo’s DOM nodes on each model change. I changed it to the unique identifier ``todo.cid`` already supplied by the backbone model.
benjamn/commoner#44 fixed commoner to work on Windows when module path relativization isn't used; with this, the `jsx` binary should work properly on Windows (though `jsx-internal` still won't).
Fixes#316, fixes#391, fixes#567.
As an added bonus, the jasmine web interface now groups tests by file.
Test Plan:
grunt test passes on b2507066, the parent of 566f8b2e (which committed a workaround for buggy module mocking).
We can already access the DOM node using `this.getDOMNode()`. Passing it as an argument was a bad decision.
Previous API:
```
componentDidMount(DOMElement rootNode)
componentDidUpdate(object prevProps, object prevState, object prevContext, DOMElement rootNode)
```
Next API:
```
componentDidMount()
componentDidUpdate(object prevProps, object prevState, object prevContext)
```
callbacks like shouldComponentUpdate, componentDidUpdate, etc. were getting the full, unsanitized context, instead of the one that's been filtered down to only the fields allowed to be visible by contextTypes.
Context is adding another argument that shifts all of them by one. Since we can already use this.getDOMNode(), it doesn't really make sense to pass it as an argument to that function.
Depends on #575; fixes#570. Now we'll be in trouble if someone tries to share objects between calls to getDefaultProps but that was already true of getInitialState and I haven't heard any complaints there.
This is the same number of allocations as before; we're just copying props in the other direction. (In any case, the copy happens only on mount and there are a couple dozen costlier things we're doing already at that time.)
This module-level mock() seems to have been interfering with other tests (26 specs failing). We don't have any other tests that do a module-level mock() so I'm going to assume it isn't supported in the open-source test runner right now. I changed it so only ReactEventEmitter.handleTopLevel is mocked; doing so made ReactEventEmitter complain that TopLevelCallbackCreator wasn't defined so I switched the ReactMount references to use React directly so that ReactDefaultInjection would kick in properly.
With this, all the tests pass.
...without preventing clicks on other things.
Just use an `<a name="...">` tag that doesn't take up any space to make sure that we're not covering up something else.
For whatever reason, doing `position: relative; top: -$navHeight;` doesn't work and causes the anchor target not to be moved up. This solution works in both Chrome and Firefox.
When events are captured, the nearest React-rendered ancestor is found and events are propagated to its tree. This causes issues when components are nested as only the innermost component receives the events.
This change modifies this behaviour so events propagate all the way up the DOM hierarchy. To reduce the performance cost, this DOM traversal is only done if the component is actually nested (determined by the `containerIsNested` map which is lazily initialised).
Summary:
adds `this.context` which you can think of as implicit props, which are passed automatically down the //ownership// hierarchy.
Contexts should be used sparingly, since they essentially allow components to communicate with descendants (in the ownership sense, not parenthood sense), which is not usually a good idea. You probably would only use contexts in places where you'd normally use a global, but contexts allow you to override them for certain view subtrees which you can't do with globals.
The context starts out `null`:
var RootComponent = React.createClass({
render: function() {
// this.context === null
}
});
You should **never** mutate the context directly, just like props and state.
You can change the context of your children (the ones you own, not `this.props.children` or via other props) using the new `withContext` method on `React`:
var RootComponent = React.createClass({
render: function() {
// this.context === null
var children = React.withContext({foo: 'a', bar: 'b'}, () => (
// In ChildComponent#render, this.context === {foo: 'a', bar: 'b'}
<ChildComponent />
));
// this.context === null
}
});
Contexts are merged, so a component can override its owner's context **for its children**:
var ChildComponent = React.createClass({
render: function() {
// this.context === {foo: 'a', bar: 'b'} (for the caller above)
var children = React.withContext({foo: 'c'},() => (
// In GrandchildComponent#render,
// this.context === {foo: 'c', bar: 'b'}
<GrandchildComponent />
));
// this.context === {foo: 'a', bar: 'b'}
}
});
Reported on Twitter by AirBnb (who are integrating React into their open-source JS framework). They made a mistake and passed a string in as the
component. We should have a better error message for that.
This renames receiveProps and changes it to take the next component to copy props from instead of just the props. That is,
component.receiveComponent(nextComponent, transaction)
instead of
component.receiveProps(nextComponent.props, transaction)
This is a precursor to adding contexts, which will also need to get propagated just like props. This change allows ReactCompositeComponent to override `receiveProps` and do something like
this._pendingContext = nextComponent.context;
Most notably, this new style of transformation gives us access to
this.parent.node, which allows us to avoid replacing identifiers that are
not actually free variables, such as member expression properties.
Closes#496.
Two of your tests were failing because of commit
1e71df5399
I fixed them by:
1) Using jasmine's spyOn in ReactCompositeComponentError-test.js
2) Inverting the function wrapping in the above commit.
Godspeed.
- Overview of add-ons for the add-ons page.
- Better title for `ReactLink`.
- Nicer code format for classSet example.
- Better explanation for `classSet`.
When we determine whether a React component should be updated (as opposed to destroyed or replaced), we currently only look at whether they share the same constructor. This adds a check for whether they share the same owner component.
I've also consolidated this logic (I cannot believe this was not already done).
dataType was unnecessary; mimeType was both unnecessary and wrong in this case. Also removed an unnecessary bind and changed pollInterval to 2000 ms for consistency with https://github.com/petehunt/react-tutorial (faster is nicer if you actually try it out!).
IE 11 no longer supports the legacy document.selection API.
Their implementation of window.getSelection() doesn't support
the extend() method, which we were relying on.
If the selection is RTL and selection extend is missing, then just
flip the selection.
The initial thought was that an opacity animation from 0.01 to 1 causes trouble on some browser. But after testing on opera 12.15, ff 23, ie 10, chrome 30, desktop/mobile safari 7 and chrome android I confirm this works.
Newer versions of WebKit and Blink will support both `document.body.scrollTop` and `document.documentElement.scrollTop`. Therefore, implementing cross-browser compatibility by summing the two will no longer work.
This changes React to use `getUnboundedScrollPosition` so we get the fix and consistency in one change!
See: https://rniwa.com/2013-10-29/web-compatibility-story-of-scrolltop-and-scrollleft/
- No need to mention React, you know you're working with it =).
- Wrap code elements in back ticks, so that they get the "box" styling for md.
- You'd want the snippet to work inside the live editor, so you need to `renderComponent`. As per wiki specification, the DOM element on which to mount is `mountNode`, just like on the front page.
- Don't forget the JSX pragma, or else your `render` fails.
- Nitpick: empty line after the end of md.
- No need for jQuery reference since
1. The general mood around React is that you don't need jQuery.
2. The syntax' still clear without jQuery.
3. We're doing a jQuery integration entry =).
- `getInitialState` was absent.
- You don't need `componentWillMount` here. fetch them in `getInitialState`.
- The non-spoken convention seems to call the event handler `"handle" + eventName`. So `handleResize` clearly indicates it's a `resize` handler while `updateDimensions` might do something else. This latter name might actually be better under circumstances where you use call the method directly somewhere, but since we removed the only direct usage in `componentWillMount` this is fine.
- Went OCD again and tried to keep the code short. `width` is enough of a demo. Removed `height`.
- Distinguish between DOM events and React events. Wish we go full React events in a near future.
When a ReactDOMComponent is created with the property `disabled: true` subsequently setting the property to `disabled: false` the HTML attribute `disabled="true"` was being left in the DOM.
If we are to unmount a component mounted into a document element we should
unmount it from document.documentElement and not from document.firstChild which
is a doctype element in this specific case.
Fixes#447.
We do this by moving the actual anchored element up in the page without moving the actual text. (Apple uses a similar trick in their framed docs.) Now this looks a bit sillier on smaller screens but it's better overall.
Currently, default props as defined by `getDefaultProps` are only used if a prop is not specified (using `X in Y` check).
However, this makes it difficult for composing components to pass along the state of not being defined, for example:
render: function() {
// If `this.props.someProp` is not set, `InnerThing` should use the default value.
return <InnerThing someProp={this.props.someProp} />;
}
This changes the requirement for falling back to the default value to an undefined check (using `typeof X === 'undefined'`).
Remember that one time I wrote release notes and said:
> This is a breaking change - if you were using class, you must change
> this to className or your components will be visually broken.
Good thing I didn't listen to myself!
* Improved warnings for deprecated methods in plain JS classes
#### Bug Fixes
* Loosened `dangerouslySetInnerHTML` restrictions so `{__html: undefined}` will no longer throw
* Fixed extraneous context warning with non-pure `getChildContext`
* Ensure `replaceState(obj)` retains prototype of `obj`
### React with Add-ons
### Bug Fixes
* Test Utils: Ensure that shallow rendering works when components define `contextTypes`
## 0.13.2 (April 18, 2015)
### React Core
#### New Features
* Added `strokeDashoffset`, `flexPositive`, `flexNegative` to the list of unitless CSS properties
* Added support for more DOM properties:
*`scoped` - for `<style>` elements
*`high`, `low`, `optimum` - for `<meter>` elements
*`unselectable` - IE-specific property to prevent user selection
#### Bug Fixes
* Fixed a case where re-rendering after rendering null didn't properly pass context
* Fixed a case where re-rendering after rendering with `style={null}` didn't properly update `style`
* Update `uglify` dependency to prevent a bug in IE8
* Improved warnings
### React with Add-Ons
#### Bug Fixes
* Immutabilty Helpers: Ensure it supports `hasOwnProperty` as an object key
### React Tools
* Improve documentation for new options
## 0.13.1 (March 16, 2015)
### React Core
#### Bug Fixes
* Don't throw when rendering empty `<select>` elements
* Ensure updating `style` works when transitioning from `null`
### React with Add-Ons
#### Bug Fixes
* TestUtils: Don't warn about `getDOMNode` for ES6 classes
* TestUtils: Ensure wrapped full page components (`<html>`, `<head>`, `<body>`) are treated as DOM components
* Perf: Stop double-counting DOM components
### React Tools
#### Bug Fixes
* Fix option parsing for `--non-strict-es6module`
## 0.13.0 (March 10, 2015)
### React Core
#### Breaking Changes
* Deprecated patterns that warned in 0.12 no longer work: most prominently, calling component classes without using JSX or React.createElement and using non-component functions with JSX or createElement
* Mutating `props` after an element is created is deprecated and will cause warnings in development mode; future versions of React will incorporate performance optimizations assuming that props aren't mutated
* Static methods (defined in `statics`) are no longer autobound to the component class
*`ref` resolution order has changed slightly such that a ref to a component is available immediately after its `componentDidMount` method is called; this change should be observable only if your component calls a parent component's callback within your `componentDidMount`, which is an anti-pattern and should be avoided regardless
* Calls to `setState` in life-cycle methods are now always batched and therefore asynchronous. Previously the first call on the first mount was synchronous.
*`setState` and `forceUpdate` on an unmounted component now warns instead of throwing. That avoids a possible race condition with Promises.
* Access to most internal properties has been completely removed, including `this._pendingState` and `this._rootNodeID`.
#### New Features
* Support for using ES6 classes to build React components; see the [v0.13.0 beta 1 notes](https://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html) for details.
* Added new top-level API `React.findDOMNode(component)`, which should be used in place of `component.getDOMNode()`. The base class for ES6-based components will not have `getDOMNode`. This change will enable some more patterns moving forward.
* Added a new top-level API `React.cloneElement(el, props)` for making copies of React elements – see the [v0.13 RC2 notes](/react/blog/2015/03/03/react-v0.13-rc2.html#react.cloneelement) for more details.
* New `ref` style, allowing a callback to be used in place of a name: `<Photo ref={(c) => this._photo = c} />` allows you to reference the component with `this._photo` (as opposed to `ref="photo"` which gives `this.refs.photo`).
*`this.setState()` can now take a function as the first argument for transactional state updates, such as `this.setState((state, props) => ({count: state.count + 1}));`– this means that you no longer need to use `this._pendingState`, which is now gone.
* Support for iterators and immutable-js sequences as children.
#### Deprecations
*`ComponentClass.type` is deprecated. Just use `ComponentClass` (usually as `element.type === ComponentClass`).
* Some methods that are available on `createClass`-based components are removed or deprecated from ES6 classes (`getDOMNode`, `replaceState`, `isMounted`, `setProps`, `replaceProps`).
### React with Add-Ons
#### New Features
* [`React.addons.createFragment` was added](/react/docs/create-fragment.html) for adding keys to entire sets of children.
#### Deprecations
*`React.addons.classSet` is now deprecated. This functionality can be replaced with several freely available modules. [classnames](https://www.npmjs.com/package/classnames) is one such module.
* Calls to `React.addons.cloneWithProps` can be migrated to use `React.cloneElement` instead – make sure to merge `style` and `className` manually if desired.
### React Tools
#### Breaking Changes
* When transforming ES6 syntax, `class` methods are no longer enumerable by default, which requires `Object.defineProperty`; if you support browsers such as IE8, you can pass `--target es3` to mirror the old behavior
#### New Features
*`--target` option is available on the jsx command, allowing users to specify and ECMAScript version to target.
*`es5` is the default.
*`es3` restores the previous default behavior. An additional transform is added here to ensure the use of reserved words as properties is safe (eg `this.static` will become `this['static']` for IE8 compatibility).
* The transform for the call spread operator has also been enabled.
### JSXTransformer
#### Breaking Changes
* The return value of `transform` now contains `sourceMap` as a JS object already, not an instance of `SourceMapGenerator`.
### JSX
#### Breaking Changes
* A change was made to how some JSX was parsed, specifically around the use of `>` or `}` when inside an element. Previously it would be treated as a string but now it will be treated as a parse error. The [`jsx_orphaned_brackets_transformer`](https://www.npmjs.com/package/jsx_orphaned_brackets_transformer) package on npm can be used to find and fix potential issues in your JSX code.
## 0.12.2 (December 18, 2014)
### React Core
* Added support for more HTML attributes: `formAction`, `formEncType`, `formMethod`, `formTarget`, `marginHeight`, `marginWidth`
* Added `strokeOpacity` to the list of unitless CSS properties
* Removed trailing commas (allows npm module to be bundled and used in IE8)
* Fixed bug resulting in error when passing `undefined` to `React.createElement` - now there is a useful warning
### React Tools
* JSX-related transforms now always use double quotes for props and `displayName`
## 0.12.1 (November 18, 2014)
### React Tools
* Types transform updated with latest support
* jstransform version updated with improved ES6 transforms
* Explicit Esprima dependency removed in favor of using Esprima information exported by jstransform
## 0.12.0 (October 28, 2014)
### React Core
#### Breaking Changes
*`key` and `ref` moved off props object, now accessible on the element directly
* React is now BSD licensed with accompanying Patents grant
* Default prop resolution has moved to Element creation time instead of mount time, making them effectively static
*`React.__internals` is removed - it was exposed for DevTools which no longer needs access
* Composite Component functions can no longer be called directly - they must be wrapped with `React.createFactory` first. This is handled for you when using JSX.
#### New Features
* Spread operator (`{...}`) introduced to deprecate `this.transferPropsTo`
* Added support for more HTML attributes: `acceptCharset`, `classID`, `manifest`
* **DEPRECATED** Returning `false` from event handlers to preventDefault
* **DEPRECATED** Convenience Constructor usage as function, instead wrap with `React.createFactory`
* **DEPRECATED** use of `key={null}` to assign implicit keys
#### Bug Fixes
* Better handling of events and updates in nested results, fixing value restoration in "layered" controlled components
* Correctly treat `event.getModifierState` as case sensitive
* Improved normalization of `event.charCode`
* Better error stacks when involving autobound methods
* Removed DevTools message when the DevTools are installed
* Correctly detect required language features across browsers
* Fixed support for some HTML attributes:
*`list` updates correctly now
*`scrollLeft`, `scrollTop` removed, these should not be specified as props
* Improved error messages
### React With Addons
#### New Features
*`React.addons.batchedUpdates` added to API for hooking into update cycle
#### Breaking Changes
*`React.addons.update` uses `assign` instead of `copyProperties` which does `hasOwnProperty` checks. Properties on prototypes will no longer be updated correctly.
#### Bug Fixes
* Fixed some issues with CSS Transitions
### JSX
#### Breaking Changes
* Enforced convention: lower case tag names are always treated as HTML tags, upper case tag names are always treated as composite components
* JSX no longer transforms to simple function calls
#### New Features
*`@jsx React.DOM` no longer required
* spread (`{...}`) operator introduced to allow easier use of props
#### Bug Fixes
* JSXTransformer: Make sourcemaps an option when using APIs directly (eg, for react-rails)
## 0.11.2 (September 16, 2014)
### React Core
#### New Features
* Added support for `<dialog>` element and associated `open` attribute
* Added support for `<picture>` element and associated `media` and `sizes` attributes
* Added `React.createElement` API in preparation for React v0.12
*`React.createDescriptor` has been deprecated as a result
### JSX
*`<picture>` is now parsed into `React.DOM.picture`
### React Tools
* Update `esprima` and `jstransform` for correctness fixes
* The `jsx` executable now exposes a `--strip-types` flag which can be used to remove TypeScript-like type annotations
* This option is also exposed to `require('react-tools').transform` as `stripTypes`
## 0.11.1 (July 24, 2014)
### React Core
#### Bug Fixes
*`setState` can be called inside `componentWillMount` in non-DOM environments
*`SyntheticMouseEvent.getEventModifierState` correctly renamed to `getModifierState`
*`getModifierState` correctly returns a `boolean`
*`getModifierState` is now correctly case sensitive
* Empty Text node used in IE8 `innerHTML` workaround is now removed, fixing rerendering in certain cases
### JSX
* Fix duplicate variable declaration in JSXTransformer (caused issues in some browsers)
## 0.11.0 (July 17, 2014)
### React Core
#### Breaking Changes
*`getDefaultProps()` is now called once per class and shared across all instances
*`MyComponent()` now returns a descriptor, not an instance
*`React.isValidComponent` and `React.PropTypes.component` validate *descriptors*, not component instances
* Custom `propType` validators should return an `Error` instead of logging directly
#### New Features
* Rendering to `null`
* Keyboard events include normalized `e.key` and `e.getModifierState()` properties
* New normalized `onBeforeInput` event
*`React.Children.count` has been added as a helper for counting the number of children
#### Bug Fixes
* Re-renders are batched in more cases
* Events: `e.view` properly normalized
* Added Support for more HTML attributes (`coords`, `crossOrigin`, `download`, `hrefLang`, `mediaGroup`, `muted`, `scrolling`, `shape`, `srcSet`, `start`, `useMap`)
* Improved SVG support
* Changing `className` on a mounted SVG component now works correctly
* Added support for elements `mask` and `tspan`
* Added support for attributes `dx`, `dy`, `fillOpacity`, `fontFamily`, `fontSize`, `markerEnd`, `markerMid`, `markerStart`, `opacity`, `patternContentUnits`, `patternUnits`, `preserveAspectRatio`, `strokeDasharray`, `strokeOpacity`
* CSS property names with vendor prefixes (`Webkit`, `ms`, `Moz`, `O`) are now handled properly
* Duplicate keys no longer cause a hard error; now a warning is logged (and only one of the children with the same key is shown)
*`img` event listeners are now unbound properly, preventing the error "Two valid but unequal nodes with the same `data-reactid`"
* Added explicit warning when missing polyfills
### React With Addons
* PureRenderMixin: a mixin which helps optimize "pure" components
* Perf: a new set of tools to help with performance analysis
* Update: New `$apply` command to transform values
* TransitionGroup bug fixes with null elements, Android
### React NPM Module
* Now includes the pre-built packages under `dist/`.
*`envify` is properly listed as a dependency instead of a peer dependency
### JSX
* Added support for namespaces, eg `<Components.Checkbox />`
* JSXTransformer
* Enable the same `harmony` features available in the command line with `<script type="text/jsx;harmony=true">`
* Scripts are downloaded in parallel for more speed. They are still executed in order (as you would expect with normal script tags)
* Fixed a bug preventing sourcemaps from working in Firefox
### React Tools Module
* Improved readme with usage and API information
* Improved ES6 transforms available with `--harmony` option
* Added `--source-map-inline` option to the `jsx` executable
* New `transformWithDetails` API which gives access to the raw sourcemap data
## 0.10.0 (March 21, 2014)
### React Core
#### New Features
* Added warnings to help migrate towards descriptors
* Made it possible to server render without React-related markup (`data-reactid`, `data-react-checksum`). This DOM will not be mountable by React. [Read the docs for `React.renderComponentToStaticMarkup`](https://facebook.github.io/react/docs/top-level-api.html#react.rendercomponenttostaticmarkup)
* Added support for more attributes:
*`srcSet` for `<img>` to specify images at different pixel ratios
*`textAnchor` for SVG
#### Bug Fixes
* Ensure all void elements don’t insert a closing tag into the markup.
* Ensure `className={false}` behaves consistently
* Ensure `this.refs` is defined, even if no refs are specified.
### Addons
*`update` function to deal with immutable data. [Read the docs](https://facebook.github.io/react/docs/update.html)
### react-tools
* Added an option argument to `transform` function. The only option supported is `harmony`, which behaves the same as `jsx --harmony` on the command line. This uses the ES6 transforms from [jstransform](https://github.com/facebook/jstransform).
## 0.9.0 (February 20, 2014)
### React Core
#### Breaking Changes
- The lifecycle methods `componentDidMount` and `componentDidUpdate` no longer receive the root node as a parameter; use `this.getDOMNode()` instead
- Whenever a prop is equal to `undefined`, the default value returned by `getDefaultProps` will now be used instead
-`React.unmountAndReleaseReactRootNode` was previously deprecated and has now been removed
-`React.renderComponentToString` is now synchronous and returns the generated HTML string
- Full-page rendering (that is, rendering the `<html>` tag using React) is now supported only when starting with server-rendered markup
- On mouse wheel events, `deltaY` is no longer negated
- When prop types validation fails, a warning is logged instead of an error thrown (with the production build of React, type checks are now skipped for performance)
- On `input`, `select`, and `textarea` elements, `.getValue()` is no longer supported; use `.getDOMNode().value` instead
-`this.context` on components is now reserved for internal use by React
#### New Features
- React now never rethrows errors, so stack traces are more accurate and Chrome's purple break-on-error stop sign now works properly
- Added support for SVG tags `defs`, `linearGradient`, `polygon`, `radialGradient`, `stop`
- Added support for more attributes:
-`crossOrigin` for CORS requests
-`download` and `hrefLang` for `<a>` tags
-`mediaGroup` and `muted` for `<audio>` and `<video>` tags
-`noValidate` and `formNoValidate` for forms
-`property` for Open Graph `<meta>` tags
-`sandbox`, `seamless`, and `srcDoc` for `<iframe>` tags
-`scope` for screen readers
-`span` for `<colgroup>` tags
- Added support for defining `propTypes` in mixins
- Added `any`, `arrayOf`, `component`, `oneOfType`, `renderable`, `shape` to `React.PropTypes`
- Added support for `statics` on component spec for static component methods
- On all events, `.currentTarget` is now properly set
- On keyboard events, `.key` is now polyfilled in all browsers for special (non-printable) keys
- On clipboard events, `.clipboardData` is now polyfilled in IE
- On drag events, `.dragTransfer` is now present
- Added support for `onMouseOver` and `onMouseOut` in addition to the existing `onMouseEnter` and `onMouseLeave` events
- Added support for `onLoad` and `onError` on `<img>` elements
- Added support for `onReset` on `<form>` elements
- The `autoFocus` attribute is now polyfilled consistently on `input`, `select`, and `textarea`
#### Bug Fixes
- React no longer adds an `__owner__` property to each component's `props` object; passed-in props are now never mutated
- When nesting top-level components (e.g., calling `React.renderComponent` within `componentDidMount`), events now properly bubble to the parent component
- Fixed a case where nesting top-level components would throw an error when updating
- Passing an invalid or misspelled propTypes type now throws an error
- On mouse enter/leave events, `.target`, `.relatedTarget`, and `.type` are now set properly
- On composition events, `.data` is now properly normalized in IE9 and IE10
- CSS property values no longer have `px` appended for the unitless properties `columnCount`, `flex`, `flexGrow`, `flexShrink`, `lineClamp`, `order`, `widows`
- Fixed a memory leak when unmounting children with a `componentWillUnmount` handler
- Fixed a memory leak when `renderComponentToString` would store event handlers
- Fixed an error that could be thrown when removing form elements during a click handler
- Boolean attributes such as `disabled` are rendered without a value (previously `disabled="true"`, now simply `disabled`)
-`key` values containing `.` are now supported
- Shortened `data-reactid` values for performance
- Components now always remount when the `key` property changes
- Event handlers are attached to `document` only when necessary, improving performance in some cases
- Events no longer use `.returnValue` in modern browsers, eliminating a warning in Chrome
-`scrollLeft` and `scrollTop` are no longer accessed on document.body, eliminating a warning in Chrome
- General performance fixes, memory optimizations, improvements to warnings and error messages
### React with Addons
-`React.addons.TestUtils` was added to help write unit tests
-`React.addons.TransitionGroup` was renamed to `React.addons.CSSTransitionGroup`
-`React.addons.TransitionGroup` was added as a more general animation wrapper
-`React.addons.cloneWithProps` was added for cloning components and modifying their props
- Bug fix for adding back nodes during an exit transition for CSSTransitionGroup
- Bug fix for changing `transitionLeave` in CSSTransitionGroup
- Performance optimizations for CSSTransitionGroup
- On checkbox `<input>` elements, `checkedLink` is now supported for two-way binding
### JSX Compiler and react-tools Package
- Whitespace normalization has changed; now space between two tags on the same line will be preserved, while newlines between two tags will be removed
- The `react-tools` npm package no longer includes the React core libraries; use the `react` package instead.
-`displayName` is now added in more cases, improving error messages and names in the React Dev Tools
- Fixed an issue where an invalid token error was thrown after a JSX closing tag
-`JSXTransformer` now uses source maps automatically in modern browsers
-`JSXTransformer` error messages now include the filename and problematic line contents when a file fails to parse
## 0.8.0 (December 19, 2013)
### React
* Added support for more attributes:
*`rows` & `cols` for `<textarea>`
*`defer` & `async` for `<script>`
*`loop` for `<audio>` & `<video>`
*`autoCorrect` for form fields (a non-standard attribute only supported by mobile WebKit)
* Improved error messages
* Fixed Selection events in IE11
* Added `onContextMenu` events
### React with Addons
* Fixed bugs with TransitionGroup when children were undefined
* Added support for `onTransition`
### react-tools
* Upgraded `jstransform` and `esprima-fb`
### JSXTransformer
* Added support for use in IE8
* Upgraded browserify, which reduced file size by ~65KB (16KB gzipped)
## 0.5.2, 0.4.2 (December 18, 2013)
### React
* Fixed a potential XSS vulnerability when using user content as a `key`: [CVE-2013-7035](https://groups.google.com/forum/#!topic/reactjs/OIqxlB2aGfU)
## 0.5.1 (October 29, 2013)
### React
@@ -37,7 +506,7 @@
### React with Addons (New!)
* Introduced a separate build with several "addons" which we think can help improve the React experience. We plan to deprecate this in the long-term, instead shipping each as standalone pieces. [Read more in the docs](http://facebook.github.io/react/docs/addons.html).
* Introduced a separate build with several "addons" which we think can help improve the React experience. We plan to deprecate this in the long-term, instead shipping each as standalone pieces. [Read more in the docs](https://facebook.github.io/react/docs/addons.html).
### JSX
@@ -70,10 +539,10 @@
* Switch from using `id` attribute to `data-reactid` to track DOM nodes. This allows you to integrate with other JS and CSS libraries more easily.
* Support for more DOM elements and attributes (e.g., `<canvas>`)
* Improved server-side rendering APIs. `React.renderComponentToString(<component>, callback)` allows you to use React on the server and generate markup which can be sent down to the browser.
*`prop` improvements: validation and default values. [Read our blog post for details...](http://facebook.github.io/react/blog/2013/07/11/react-v0-4-prop-validation-and-default-values.html)
* Support for the `key` prop, which allows for finer control over reconciliation. [Read the docs for details...](http://facebook.github.io/react/docs/multiple-components.html)
* Removed `React.autoBind`. [Read our blog post for details...](http://facebook.github.io/react/blog/2013/07/02/react-v0-4-autobind-by-default.html)
* Improvements to forms. We've written wrappers around `<input>`, `<textarea>`, `<option>`, and `<select>` in order to standardize many inconsistencies in browser implementations. This includes support for `defaultValue`, and improved implementation of the `onChange` event, and circuit completion. [Read the docs for details...](http://facebook.github.io/react/docs/forms.html)
*`prop` improvements: validation and default values. [Read our blog post for details...](https://facebook.github.io/react/blog/2013/07/11/react-v0-4-prop-validation-and-default-values.html)
* Support for the `key` prop, which allows for finer control over reconciliation. [Read the docs for details...](https://facebook.github.io/react/docs/multiple-components.html)
* Removed `React.autoBind`. [Read our blog post for details...](https://facebook.github.io/react/blog/2013/07/02/react-v0-4-autobind-by-default.html)
* Improvements to forms. We've written wrappers around `<input>`, `<textarea>`, `<option>`, and `<select>` in order to standardize many inconsistencies in browser implementations. This includes support for `defaultValue`, and improved implementation of the `onChange` event, and circuit completion. [Read the docs for details...](https://facebook.github.io/react/docs/forms.html)
* We've implemented an improved synthetic event system that conforms to the W3C spec.
* Updates to your component are batched now, which may result in a significantly faster re-render of components. `this.setState` now takes an optional callback as it's second parameter. If you were using `onClick={this.setState.bind(this, state)}` previously, you'll want to make sure you add a third parameter so that the event is not treated as the callback.
React is one of Facebook's first open source projects that is both under very active development and is also being used to ship code to everybody on facebook.com. We're still working out the kinks to make contributing to this project as easy and transparent as possible, but we're not quite there yet. Hopefully this document makes the process for contributing clear and preempts some questions you may have.
React is one of Facebook's first open source projects that is both under very active development and is also being used to ship code to everybody on [facebook.com](https://www.facebook.com). We're still working out the kinks to make contributing to this project as easy and transparent as possible, but we're not quite there yet. Hopefully this document makes the process for contributing clear and answers some questions that you may have.
## [Code of Conduct](https://code.facebook.com/codeofconduct)
Facebook has adopted a Code of Conduct that we expect project participants to adhere to. Please read [the full text](https://code.facebook.com/codeofconduct) so that you can understand what actions will and will not be tolerated.
## Our Development Process
@@ -23,11 +27,11 @@ The core team will be monitoring for pull requests. When we get one, we'll run s
5. Make sure your code lints (`grunt lint`) - we've done our best to make sure these rules match our internal linting guidelines.
6. If you haven't already, complete the CLA.
### Contributor License Agreement ("CLA")
### Contributor License Agreement (CLA)
In order to accept your pull request, we need you to submit a CLA. You only need to do this once, so if you've done this for another Facebook open source project, you're good to go. If you are submitting a pull request for the first time, just let us know that you have completed the CLA and we can cross-check with your GitHub username.
Complete your CLA here: <https://developers.facebook.com/opensource/cla>
[Complete your CLA here.](https://code.facebook.com/cla)
## Bugs
@@ -41,23 +45,35 @@ The best way to get your bug fixed is to provide a reduced test case. jsFiddle,
### Security Bugs
Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe disclosure of security bugs. With that in mind, please do not file public issues and go through the process outlined on that page.
Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe disclosure of security bugs. With that in mind, please do not file public issues; go through the process outlined on that page.
## How to Get in Touch
* IRC - [#reactjs on freenode](http://webchat.freenode.net/?channels=reactjs)
*Mailing list - [reactjs on Google Groups](http://groups.google.com/group/reactjs)
* IRC - [#reactjs on freenode](https://webchat.freenode.net/?channels=reactjs)
*Discussion forum - [discuss.reactjs.org](https://discuss.reactjs.org/)
## Coding Style
## Style Guide
* Use semicolons;
* Commas last,
Our linter will catch most styling issues that may exist in your code.
You can check the status of your code styling by simply running: `grunt lint`
However, there are still some styles that the linter cannot pick up. If you are unsure about something, looking at [Airbnb's Style Guide](https://github.com/airbnb/javascript) will guide you in the right direction.
### Code Conventions
* Use semicolons `;`
* Commas last `,`
* 2 spaces for indentation (no tabs)
* Prefer `'` over `"`
*`"use strict";`
*`'use strict';`
* 80 character line length
*"Attractive"
*Write "attractive" code
* Do not use the optional parameters of `setTimeout` and `setInterval`
### Documentation
* Do not wrap lines at 80 characters
## License
By contributing to React, you agree that your contributions will be licensed under the [Apache License Version 2.0 (APLv2)](LICENSE).
By contributing to React, you agree that your contributions will be licensed under its BSD license.
React is a JavaScript library for building user interfaces.
* **Declarative:** React uses a declarative paradigm that makes it easier to reason about your application.
* **Efficient:** React computes the minimal set of changes necessary to keep your DOM up-to-date.
* **Flexible:** React works with the libraries and frameworks that you already know.
* **Just the UI:** Lots of people use React as the V in MVC. Since React makes no assumptions about the rest of your technology stack, it's easy to try it out on a small feature in an existing project.
* **Virtual DOM:** React abstracts away the DOM from you, giving a simpler programming model and better performance. React can also render on the server using Node, and it can power native apps using [React Native](https://facebook.github.io/react-native/).
* **Data flow:** React implements one-way reactive data flow which reduces boilerplate and is easier to reason about than traditional data binding.
[Learn how to use React in your own project.](http://facebook.github.io/react/docs/getting-started.html)
**NEW**! Check out our newest project [React Native](https://github.com/facebook/react-native), which uses React and JavaScript to create native mobile apps.
[Learn how to use React in your own project](https://facebook.github.io/react/docs/getting-started.html).
## Examples
We have several examples [on the website](http://facebook.github.io/react). Here is the first one to get you started:
We have several examples [on the website](https://facebook.github.io/react/). Here is the first one to get you started:
```js
/** @jsx React.DOM */
varHelloMessage=React.createClass({
render:function(){
return<div>{'Hello '+this.props.name}</div>;
return<div>Hello{this.props.name}</div>;
}
});
React.renderComponent(
React.render(
<HelloMessagename="John"/>,
document.getElementById('container')
);
@@ -28,20 +29,20 @@ React.renderComponent(
This example will render "Hello John" into a container on the page.
You'll notice that we used an XML-like syntax; [we call it JSX](http://facebook.github.io/react/docs/jsx-in-depth.html). JSX is not required to use React, but it makes code more readable, and writing it feels like writing HTML. A simple transform is included with React that allows converting JSX into native JavaScript for browsers to digest.
You'll notice that we used an HTML-like syntax; [we call it JSX](https://facebook.github.io/react/docs/jsx-in-depth.html). JSX is not required to use React, but it makes code more readable, and writing it feels like writing HTML. A simple transform is included with React that allows converting JSX into native JavaScript for browsers to digest.
## Installation
The fastest way to get started is to serve JavaScript from the CDN (also available on [CDNJS](http://cdnjs.com/#react)):
The fastest way to get started is to serve JavaScript from the CDN (also available on [cdnjs](https://cdnjs.com/libraries/react) and [jsdelivr](http://www.jsdelivr.com/#!react)):
We've also built a [starter kit](http://facebook.github.io/react/downloads/react-0.5.1.zip) which might be useful if this is your first time using React. It includes a webpage with an example of using React with live code.
We've also built a [starter kit](https://facebook.github.io/react/downloads/react-0.13.3.zip) which might be useful if this is your first time using React. It includes a webpage with an example of using React with live code.
If you'd like to use [bower](http://bower.io), it's as easy as:
@@ -51,7 +52,7 @@ bower install --save react
## Contribute
The main purpose of this repository is to continue to evolve React core, making it faster and easier to use. If you're interested in helping with that, then keep reading. If you're not interested in helping right now that's ok too :) Any feedback you have about using React would be greatly appreciated.
The main purpose of this repository is to continue to evolve React core, making it faster and easier to use. If you're interested in helping with that, then keep reading. If you're not interested in helping right now that's ok too. :) Any feedback you have about using React would be greatly appreciated.
### Building Your Copy of React
@@ -59,7 +60,7 @@ The process to build `react.js` is built entirely on top of node.js, using many
#### Prerequisites
* You have `node` installed at v0.10.0+ (it might work at lower versions, we just haven't tested).
* You have `node` installed at v0.10.0+ (it might work at lower versions, we just haven't tested) and `npm` at v2.0.0+.
* You are familiar with `npm` and know whether or not you need to use `sudo` when installing packages globally.
* You are familiar with `git`.
@@ -81,16 +82,29 @@ At this point, you should now have a `build/` directory populated with everythin
We use grunt to automate many tasks. Run `grunt -h` to see a mostly complete listing. The important ones to know:
```sh
# Create test build & run tests with PhantomJS
# Build and run tests with PhantomJS
grunt test
# Lint the core library code with JSHint
# Build and run tests in your browser
grunt test --debug
# For speed, you can use fasttest and add --filter to only run one test
grunt fasttest --filter=ReactIdentity
# Lint the code with ESLint
grunt lint
# Lint package code
grunt lint:package
# Wipe out build directory
grunt clean
```
### License
React is [BSD licensed](./LICENSE). We also provide an additional [patent grant](./PATENTS).
React documentation is [Creative Commons licensed](./LICENSE-docs).
Examples provided in this repository and in the documentation are [separately licensed](./LICENSE-examples).
### More…
There's only so much we can cram in here. To read more about the community and guidelines for submitting pull requests, please read the [Contributing document](CONTRIBUTING.md).
## Troubleshooting
See the [Troubleshooting Guide](https://github.com/facebook/react/wiki/Troubleshooting)
@@ -21,6 +21,7 @@ Once you have RubyGems and installed Bundler (via `gem install bundler`), use it
```sh
$ cd react/docs
$ bundle install # Might need sudo.
$ npm install
```
### Instructions
@@ -31,8 +32,8 @@ Use Jekyll to serve the website locally (by default, at `http://localhost:4000`)
```sh
$ cd react/docs
$ rake
$ jekyll serve -w
$ bundle exec rake
$ bundle exec jekyll serve -w
$ open http://localhost:4000/react/
```
@@ -42,19 +43,24 @@ If you want to modify the CSS or JS, use [Rake](http://rake.rubyforge.org/) to c
```sh
$ cd react/docs
$ rake watch # Automatically compiles as needed.
# rake Manually compile CSS and JS.
# rake css Manually compile CSS, only.
# rake js Manually compile JS, only.
$ bundle exec rake watch # Automatically compiles as needed.
# bundle exec rake Manually compile CSS and JS.
# bundle exec rake js Manually compile JS, only.
```
## Afterthoughts
### Updating `facebook.github.io/react`
The easiest way to do this is to have a separate clone of this repository, checked out to the `gh-pages` branch. We have a build step that expects this to be in a directory named `react-gh-pages` at the same depth as `react`. Then it's just a matter of running `grunt docs`, which will compile the site and copy it out to this repository. From there you can check it in.
The easiest way to do this is to have a separate clone of this repository, checked out to the `gh-pages` branch. We have a build step that expects this to be in a directory named `react-gh-pages` at the same depth as `react`. Then it's just a matter of running `grunt docs`, which will compile the site and copy it out to this repository. From there, you can check it in.
**Note:** This should only be done for new releases. You should create a tag corresponding to the relase tag in the main repository.
**Note:** This should only be done for new releases. You should create a tag corresponding to the release tag in the main repository.
We also have a rake task that does the same thing (without creating commits). It expects the directory structure mentioned above.
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.