$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.
(cherry picked from commit accb4f6047)
$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.
(cherry picked from commit 08b1515f7f)
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.
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
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.
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!
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.
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.
I don't think this particular codepath was exercised at all (because all the callers call deleteValueForProperty) but this fixes a bug here nonetheless.
2014-03-03 17:43:03 -08:00
807 changed files with 80656 additions and 19657 deletions
* 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](http://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.
### 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`](http://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](http://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).
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://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.
## Our Development Process
@@ -27,7 +27,7 @@ The core team will be monitoring for pull requests. When we get one, we'll run s
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,24 +41,30 @@ 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)
## Coding Style
## Style Guide
### Code
* Use semicolons;
* Commas last,
* 2 spaces for indentation (no tabs)
* Prefer `'` over `"`
*`"use strict";`
*`'use strict';`
* 80 character line length
* "Attractive"
* 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.
@@ -8,23 +8,18 @@ React is a JavaScript library for building user interfaces.
[Learn how to use React in your own project.](http://facebook.github.io/react/docs/getting-started.html)
## The `react` npm package has recently changed!
If you're looking for jeffbski's [React.js](https://github.com/jeffbski/autoflow) project, it's now in `npm` as `autoflow` rather than `react`.
## Examples
We have several examples [on the website](http://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>;
}
});
React.renderComponent(
React.render(
<HelloMessagename="John"/>,
document.getElementById('container')
);
@@ -36,16 +31,16 @@ You'll notice that we used an HTML-like syntax; [we call it JSX](http://facebook
## 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.9.0.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](http://facebook.github.io/react/downloads/react-0.13.2.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:
@@ -89,12 +84,22 @@ We use grunt to automate many tasks. Run `grunt -h` to see a mostly complete lis
grunt test
# Build and run tests in your browser
grunt test --debug
# Lint the code with JSHint
# 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
# 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).
@@ -32,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/
```
@@ -43,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.