Compare commits

...

266 Commits

Author SHA1 Message Date
Paul O’Shannessy
f3db0006e8 Update everything for v0.5.1 2013-10-29 11:46:46 -07:00
Paul O’Shannessy
ef4d7a37f0 npm shrinkwrap
We should be doing this in the stable branch to ensure fuzzy
dependencies are met identically on subsequent releases.

In this case, browserify had a change in 2.34.3 which resulted in
JSXTransformer to be a different size. While it was a change for the
better, it was unexpected and not a change we were calling out in the
release.

This shrinkwraps to the same versions of packages we had when we shipped
0.5.0.
2013-10-29 11:46:46 -07:00
Laurence Rowe
64016811d3 Make 'disabled' MUST_USE_ATTRIBUTE for compatibility with CSS [disabled] selectors.
When a ReactDOMComponent is created with the property `disabled: true` subsequently setting the property to `disabled: false` the HTML attribute `disabled="true"` was being left in the DOM.
2013-10-29 10:16:04 -07:00
Andrey Popp
7b957c880c Fix unmounting components mounted into doc element
If we are to unmount a component mounted into a document element we should
unmount it from document.documentElement and not from document.firstChild which
is a doctype element in this specific case.
2013-10-29 10:16:04 -07:00
Ian Obermiller
1b835fb5cf Fix ReactTransitionEvents detectEvents 2013-10-29 10:16:04 -07:00
Cat Chen
9f0bbce797 fixed %d in invariant call 2013-10-29 10:16:04 -07:00
Josh Duck
c9d20e56d3 Don't reset mouseDown in focus handlers
Focus fires after mouse down on initial click, so we lost the
flag when the user initially began dragging on the input.
2013-10-29 10:16:04 -07:00
Ben Alpert
ce612904ef Make SelectEventPlugin not throw for range inputs
Accessing .selectionStart on a non-text input will throw (see http://www.w3.org/TR/2009/WD-html5-20090423/editing.html#textFieldSelection), so check that the input has selection capabilities before accessing the property.

Fixes #437.
2013-10-29 10:16:04 -07:00
Paul O’Shannessy
ea1ab5501d Update API docs for unmountAndReleaseReactRootNode 2013-10-26 17:45:03 -07:00
Brian Rue
2c35ed8068 ReactTransitionGroup example: fix typo and logic bug in handleRemove 2013-10-25 18:25:14 -07:00
Keito Uchiyama
c994cc24c3 docs: Delete Mutation Events (onCharacterDOMModified) 2013-10-25 18:24:37 -07:00
Paul O’Shannessy
24da1c0023 docs: remove OUTLINE 2013-10-21 15:20:46 -07:00
Cheng Lou
d82181e4b9 Add clickable anchors to docs headers
Closes #434
2013-10-21 14:38:57 -07:00
Paul O’Shannessy
ba166b9652 Fix live editor examples on home page.
Remember that one time I wrote release notes and said:

> This is a breaking change - if you were using class, you must change
> this to className or your components will be visually broken.

Good thing I didn't listen to myself!
2013-10-16 18:11:10 -07:00
Paul O’Shannessy
f756cb3d9c 0.5.0 release
Updated README, CHANGELOG, blog post
2013-10-16 11:44:37 -07:00
Paul O’Shannessy
cadf8b786c Fix grunt npm:test 2013-10-16 11:44:37 -07:00
Paul O’Shannessy
953947a617 bump version for 0.5 2013-10-15 22:32:20 -07:00
Paul O’Shannessy
d8c949e4d8 Update browserify 2013-10-15 21:27:26 -07:00
JeffMo
243a2b816e bump baseline jstransform and esprima dependency versions 2013-10-15 18:54:01 -07:00
Paul O’Shannessy
451176665c Update docs with supported tags and attributes 2013-10-15 18:15:24 -07:00
Paul O’Shannessy
cff62f8d72 Enable linting for bitwise operators 2013-10-15 18:02:28 -07:00
Paul O'Shannessy
3f2ba221ef Use getActiveElement module
We had something that did the same sort of protection. The module
differs slightly (returns document.body instead of undefined) but
looking at the callers, that should be ok.
2013-10-15 18:00:05 -07:00
Paul O'Shannessy
46713c3d7d Fix Lint
Enabling bitwise linting caught another user. Also fixed a semicolon
misuse.
2013-10-15 17:59:14 -07:00
Paul O’Shannessy
b015204938 Updated AUTHORS for 0.5
closes #414
2013-10-15 15:01:14 -07:00
petehunt
24f6bed855 new addons docs
closes #403
2013-10-15 14:09:21 -07:00
Paul O’Shannessy
5325e944e9 Merge pull request #426 from SanderSpies/sspi-fix-jsx-doc-link
In-browser JSX warning linked to wrong anchor (should be lowercase)
2013-10-15 12:04:59 -07:00
Paul O’Shannessy
b488cb3d4b Merge branch 'SanderSpies-sspi-dom-attribute-process' 2013-10-15 12:00:52 -07:00
Paul O’Shannessy
087c2afed1 Make sure DOM components work in JSDOM 2013-10-15 11:38:26 -07:00
Paul O’Shannessy
b0645bd5d3 Be consistent with object naming in tests
This also fixes line length issues our linter was complaining about.
2013-10-15 11:38:26 -07:00
SanderSpies
5a13dd090d Standardize prop -> DOM attribute process
Allow more than strings and numbers to be used as attributes for DOM
nodes. This removes the special casing for `0` and `false` that was
being used in ReactDOMInput and ReactDOMTextarea.

Now we will just `toString` any object we try to insert into a DOM.

Closes #422, #372, #302
2013-10-15 11:38:25 -07:00
Paul O'Shannessy
b0455f4670 Ensure attribute values are strings
`jsdom` behavers differently than browsers here and we should ensure
that we are consistent. Browsers should be (and are) converting to
a string first, while `jsdom` doesn't.
2013-10-15 10:39:51 -07:00
Tim Yung
287f5b578c Add bitwise lint escape to DefaultDOMPropertyConfig 2013-10-15 10:38:31 -07:00
SanderSpies
6839704c4b #JSX => #jsx 2013-10-15 19:11:19 +02:00
Martin Konicek
5332422239 [docs] Fix a broken link to JSX syntax in README. 2013-10-14 17:10:26 -07:00
Ben Alpert
7909c3e71b Forcibly wrap SVG nodes with <svg> on creation
Forcing wrapping seems necessary here: I compared a <circle> created within a <div> with a <circle> created inside an <svg> and they appear to have exactly the same properties with the exception of .parentNode (and .parentElement), yet the former refuses to show up when appended to an <svg> element. As such, I can't find any useful way to write a unit test (testing getMarkupWrap's output doesn't seem particularly useful to me).

Fixes #311.

Test Plan:
With a component that adds a <circle> after mounting (such as http://jsfiddle.net/spicyj/hxFVe/), verify that the circle appears in both Chrome and IE9.
2013-10-14 13:44:36 -07:00
Paul O’Shannessy
b45c82c256 Merge pull request #419 from piranha/svg-attrs
svg properties -> attributes

Fixes #190
2013-10-14 11:24:36 -07:00
Alexander Solovyov
3a5a82fd18 DefaultDOMPropertyConfig: sort properties alphabetically 2013-10-14 20:45:00 +03:00
Josh Duck
1238f5f23a Remove DOM mutation listeners
Mutation listeners are known to be slow. Rough benchmarks show text
changes are now 50% faster.
2013-10-11 17:33:47 -07:00
Owen Coutts
ac9f5e9da4 Better click behavior for ff
Firefox created onClick events for right mouse clicks. This diff brings behavior on firefox inline with other browsers.
2013-10-11 15:42:22 -07:00
Josh Duck
58c392ae3b Check for null selection
getRangeAt(0) will throw on null selection. Add guard in
ReactDOMSelection and DocumentSelection.
2013-10-11 12:52:19 -07:00
Alexander Solovyov
aa38ffc22d svg attributes properly cased when assigned by react 2013-10-11 15:48:17 +03:00
Alexander Solovyov
6d300527c8 svg: rx/ry for rounded corners 2013-10-11 13:42:10 +03:00
Alexander Solovyov
a601c5cc81 svg properties -> attributes 2013-10-11 13:32:22 +03:00
Alexander Solovyov
4549fd7510 fix namesToPlugins for gcc advanced mode 2013-10-09 22:08:03 +03:00
Keito Uchiyama
ef60eee57a Make transferPropsTo() message easier to debug
Summary:
Made the transferPropsTo() error introduced in
325322898c easier to use to debug.
2013-10-09 11:28:35 -07:00
Sebastian Markbage
7a9c13dee8 Set _renderedComponent before it's fully mounted
For debugging so that we can inspect the currently rendering tree. I think this
should be safe and makes sense since it tried to mount.
2013-10-09 11:28:22 -07:00
Tim Yung
d652dd928a Add displayName for DOM Components 2013-10-09 11:28:12 -07:00
Jan Kassens
c99d6a8013 Make the injection of ReactPerf work
The injection was only evaluated when ReactCompositeComponent was first loaded.
This made it impossible to inject a custom measure and the injection pointless.
2013-10-09 11:27:40 -07:00
Ben Newman
f8c5752472 Merge pull request #374 from spicyj/workers
Test that React loads properly in a web worker.

Most of this code is open source-only, so I think it's safe to merge without figuring out how to translate it upstream first.
2013-10-09 08:50:41 -07:00
Paul O’Shannessy
44352a2861 Merge pull request #370 from zpao/addons
react-with-addons build
2013-10-08 16:54:31 -07:00
Paul O’Shannessy
7da874d835 Add TransitionGroup example 2013-10-08 16:49:11 -07:00
Paul O’Shannessy
de9e94de5f Make sure react-with-addons ends up in react-source gem 2013-10-08 16:49:11 -07:00
Paul O’Shannessy
a151133161 Make sure react-with-addons ends up in bower 2013-10-08 16:49:11 -07:00
Paul O’Shannessy
042a2723ff Make sure addons builds are sent to build server 2013-10-08 16:49:11 -07:00
Paul O’Shannessy
2e6092b217 react-with-addons build
This creates a new standalone build which should have everything the
default build has, plus a little extra. This is not a sustainable long
term solution (we shouldn't make people choose like this) but it fixes
the problem we have in the short term.

This also removes the terrible react-transitions build. This is better
anway.

Fixes #369
2013-10-08 16:49:11 -07:00
Ben Alpert
f658c32df1 Tweak verbiage about required polyfills
I found it weird how the es5-shim comment came after the list of functions; now it's before.
2013-10-08 16:25:29 -07:00
Paul O’Shannessy
b16874c5a8 Merge pull request #407 from Samangan/master
renamed ReactOnDOMReady module to ReactMountReady
2013-10-08 15:12:29 -07:00
Connor McSheffrey
b9a657db2c fixed broken link on Community Round-up #9 blog post
closes #409
2013-10-08 11:09:33 -07:00
Josh Duck
dbc613199b Fix SelectEventPlugin
There were 2 issues:

I was reusing event outside the original event handler (activeNativeEvent).
This is a bad idea. I've changed deferred dispatch to have an empty object
as the nativeEvent.

I didn't handle inputs without .selectionStart (e.g. file inputs). I extracted
a input type check from ChangeEventPlugin and reuse it here.
2013-10-08 10:28:43 -07:00
Paul O’Shannessy
920c4206f4 Sync getActiveElement module from FB. 2013-10-07 15:32:47 -07:00
Paul O’Shannessy
fdb10c0679 React.__internals
We need access to internal modules in order to provide a single way for some
projects to work internally with @providesModule and externally.
2013-10-07 15:07:20 -07:00
Pete Hunt
325322898c Throw when calling transferPropsTo() on a component you don't own
This is dangerous because it means that data is flowing into the component from two components, only one of which is the actual "owner". While we may be able to figure out how to
support this someday, let's be strict and prevent it for now.
2013-10-07 15:07:04 -07:00
Sebastian Markbage
27669c09ca Move flattenChildren into MultiChild 2013-10-07 15:06:44 -07:00
Tim Yung
0c59c57d66 Speed Key Validation (by over 9000)
Use a valid identifier (and non-string) to reduce chance of de-optimizing in V8 and Nitro.
2013-10-07 15:05:56 -07:00
Christopher Chedeau
26d7c4275a Add warning when using componentShouldUpdate 2013-10-07 15:05:44 -07:00
Josh Duck
2b7a7599bb Add select event plugin
Polyfill 'onSelect' behavior for React.

Use non-standard 'selectionchange' event rather than 'select' event.
This allows us to fire the event when user moves the cursor via arrow
keys, and not just when they select multiple chars.

Add methods to ReactDOMSelection to make getting current selection
easier, so we can do a fast check for change without having to
calculate char offsets for selection start and end.
2013-10-07 15:02:57 -07:00
Sebastian Markbage
ed9c0ca87c Expose bound function, context and arguments
Exposes the bound context, original method and bound arguments for any
auto-bound methods, for debugging purposes.
2013-10-07 15:02:47 -07:00
Sebastian Markbage
68abbacc39 Expose the rendered children before they're actually mounted
Exposing the _renderedChildren property before all the children are fully
mounted. This allows us to debug a partially mounted tree when the debugger
has a breakpoint in the one of the mounting children.

This only has a functional difference in the case where mounting throws. This
will end up not mounting the component anyway. Any remounting shouldn't be
affected by this change.
2013-10-07 15:02:27 -07:00
Samangan
84d8e1841a renamed ReactOnDOMReady module to ReactMountReady
fix

renamed ReactOnDOMReady module to ReactMountReady
2013-10-05 01:35:56 -05:00
Vjeux
a9b3139ff8 Community round-up #9
http://fooo.fr:4000/react/blog/2013/10/03/community-roundup-9.html
2013-10-03 15:18:21 -07:00
Vjeux
582b720183 Add app id for comments moderation
This way we can be notified when any new comment appear in the docs/blog and add moderators
2013-10-03 22:32:20 +02:00
Ben Newman
0a02b55d95 Use nodeContains where appropriate. 2013-10-01 17:55:13 -07:00
Tim Yung
20af6a7ce8 Speed Owner Access (by over 9000)
Use a valid identifier (and non-string) to reduce chance of de-optimizing in V8 and Nitro.
2013-10-01 16:32:06 -07:00
Ben Newman
7c0f5c3237 Fix isEventSupported in recent versions of jsdom.
Setting the `eventName` attribute of an element to the empty string is not
enough to cause `typeof element[eventName] === 'function'` in jsdom. The
attribute value actually has to look like a function body.
2013-10-01 16:31:46 -07:00
Paul O'Shannessy
f43449d333 ReactNativeComponent -> ReactDOMComponent
In an effort to break the DOMy parts of React away from the non-DOMy parts, I'm renaming this.
2013-10-01 16:31:32 -07:00
Ben Newman
e66287f92e Copy the nodeContains module from static_upstream. 2013-10-01 19:18:09 -04:00
Paul O’Shannessy
f20626f17a Merge pull request #378 from spicyj/html-reconciliation
Fix reconciling when switching to/from innerHTML
2013-10-01 13:38:08 -07:00
Andrew Zich
ab00f8d15c Removed "ajaxify" from DefaultDOMPropertyConfig
The `"ajaxify"` attribute is Facebook-specific and does not belong in this repo.
2013-10-01 13:34:26 -07:00
Pete Hunt
58de758a32 Sort batched updates by owner depth
If we reconcile components higher in the hierarchy they will likely reconcile components lower in the
hierarchy. If we sort by depth then when we reach those components there will be no more pending state or
props and it will no op.
2013-10-01 13:33:12 -07:00
Paul O’Shannessy
8beaa211fb Merge pull request #387 from spicyj/exec-fix
Actually make exec work
2013-10-01 13:14:56 -07:00
Paul O’Shannessy
7c217324a6 Merge pull request #384 from chenglou/doc-link
Add doc link to DOM differences from JSX gotchas
2013-10-01 11:25:34 -07:00
Paul O’Shannessy
15c1358aaf Merge pull request #386 from chenglou/unitless-line-height
add line-height to unitless css props, test cases
2013-10-01 10:35:21 -07:00
Ben Alpert
0a45325621 Actually make exec work
The spec for eval (http://es5.github.io/x15.1.html#x15.1.2.1) says "If Type(x) is not String, return x." and that's exactly what's happening here -- it gets {code: ...} and does nothing.
2013-09-30 18:51:39 -07:00
Cheng Lou
607eeaed4b Add doc link to DOM differences from JSX gotchas 2013-09-30 20:46:41 -04:00
Paul O’Shannessy
c764adc256 Merge pull request #376 from spicyj/noglobal
Fix lint errors including use of `global`
2013-09-30 14:21:12 -07:00
Cheng Lou
27ee9c6eb0 add line-height to unitless css props, test cases 2013-09-30 13:56:56 -04:00
Pete Hunt
8835e9d99f Update README.md 2013-09-28 19:57:18 -07:00
Ben Alpert
3ca507d73f Fix reconciling when switching to/from innerHTML
There's no way that this can work if _updateDOMChildren doesn't know about dangerouslySetInnerHTML, so tell it.

Fixes #377.
2013-09-27 16:22:46 -07:00
Ben Alpert
3dc1074908 Test that React loads properly in a web worker
This should catch top-level uses of `window` and `document`, while lint rules catch `global`.
2013-09-27 14:38:11 -07:00
Ben Alpert
94d2bbb221 Fix lint errors including use of global 2013-09-26 16:55:26 -07:00
Pete Hunt
84dea7e971 Fix server rendering 2013-09-26 15:49:19 -07:00
Pete Hunt
781bbe2916 Merge pull request #375 from danielmiladinov/master
Change spec policy for getDefaultProps to SpecPolicy.DEFINE_MANY_MERGED
2013-09-26 13:45:34 -07:00
Daniel Miladinov
b0ae800d64 Change spec policy for getDefaultProps to SpecPolicy.DEFINE_MANY_MERGED
This will allow multiple mixins for a component to define
getDefaultProps and their values will be merged.

See also:
https://groups.google.com/d/msg/reactjs/UzSiXw2Vo5s/FxK7AHWOzLMJ
2013-09-25 23:52:29 -04:00
Paul O’Shannessy
848a8e1180 Remove animation "example"
It was never a real example and shouldn't have been checked in.
2013-09-25 11:08:24 -07:00
Paul O’Shannessy
fc0b68af28 Fix 404s to non-existent API docs 2013-09-24 16:00:52 -07:00
Paul O’Shannessy
c6f831e85f Redirect docs/reference.html 2013-09-24 15:47:17 -07:00
Vjeux
58173edb16 Community round-up #8 2013-09-24 14:18:11 -07:00
Pete Hunt
fc73bf0a0a ReactLink: two-way binding for React
This introduces `ReactLink` which is a super lightweight way to do two-way binding for React.

If you want to use a controlled form input today, it's a lot of lines of code:

http://jsfiddle.net/T3z3v/

Look how many times `name` is repeated in there. And you have to remember to wire up event handles and pass the right state and
right event handler for *each* form field. It's really annoying.

With ReactLink, you can "link" a form value to a state field. It's just some simple sugar around the value prop/onChange
convention:

https://gist.github.com/petehunt/6689857

Ah, much nicer! And requires very little core changes or extra bytes. `ReactLink` just wraps the current value and "request
change" handler into a little object and provides some sugar to create some from composite component state.
2013-09-24 12:14:25 -07:00
Marshall Roch
458836abd3 Fix use of 'window' in CompositionEventPlugin
access to `window` needs to be guarded by `ExecutionEnvironment.canUseDOM`.
2013-09-23 23:01:14 -07:00
Josh Duck
5d7633d74c Move composition event to plugin with polyfill
Move compositionstart/compositionend to a new event plugin.

Add a polyfill that listens to key and mouse events and uses selection to
determine which text has changed.
2013-09-23 16:27:01 -07:00
Josh Duck
8f15eea910 Add ReactDOMSelection module
Add a DOM based selection module. This can both be used on its own and
in ReactInputSelection where our current implementation is lacking.

There is still some inconsistency with how IE and modern browsers
handle block nodes. Should be OK if we are just getting and setting
and not trying to set selection based on character offsets.
2013-09-23 16:23:35 -07:00
Paul O’Shannessy
d27746ee0b Docs: Give headers ids for easy linking
This gives markdown headers an id so that we can link directly to
sections of our docs. This is better than the alternative of adding them
all ourselves.
2013-09-23 10:30:51 -07:00
Keito Uchiyama
d13ce702a8 Fix typo in doc 2013-09-22 15:09:36 -07:00
Keito Uchiyama
d262285827 Fix use of "it's" in docs 2013-09-22 13:24:25 -07:00
Jeff Morrison
b5a11a431e Merge pull request #336 from spicyj/jsx-spacing
JSX: Respect original spacing and newlines better
2013-09-20 10:59:21 -07:00
Pete Hunt
832d9de037 Rename unmountAndReleaseReactRootNode() -> unmountComponentAtNode()
This is just a better name; we may revisit the name later.
2013-09-19 14:46:49 -07:00
Josh Duck
578863881f Add composition events to React.
Composition events make it possible to detect IME entry/exit.
https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
2013-09-19 14:30:21 -07:00
Paul O’Shannessy
8875e1dc3b Merge pull request #359 from SanderSpies/master
Give the user a warning when using unoptimized JSX code
2013-09-19 13:14:12 -07:00
SanderSpies
cd79ed32cb - removed creation of the id within the tooling integration doc (expect this to be done by @zpao's pull request)
- removed the if statement and now always provide a warning message (as proposed by @spicyj)
- improved the warning message
2013-09-19 06:48:38 +02:00
SanderSpies
1924b7c945 Correcting the markdown anchor 2013-09-19 00:58:37 +02:00
SanderSpies
d2bf50c63d Give the user a warning when using unoptimized JSX code and send the user to the correct location in the documentation to optimize. 2013-09-19 00:55:10 +02:00
Ben Newman
b1dd4149a0 Merge pull request #343 from benjamn/fix-if-statement-pruning
Make constant propagation smarter about pruning if statements
2013-09-18 11:10:56 -07:00
Paul O’Shannessy
208ebd35b7 Don't update the docs version by default
This was leading to a lot of unnecessary churn in the config file since
different YAML versions were serializing differently.
2013-09-18 10:40:12 -07:00
Ben Newman
adda400602 Make constant propagation smarter about pruning if statements. 2013-09-18 13:33:45 -04:00
Pete Hunt
a9d53dae72 Merge pull request #351 from spicyj/api-docs
Flesh out reference documentation, more API info
2013-09-17 16:12:16 -07:00
Tim Yung
ea0cde2cf4 Fix PropTypes Documentation 2013-09-17 16:09:23 -07:00
Sebastian Markbage
e5ba82a44b Fix DOM node warning
bdf2a9bb12 broke the warning that children aren't suppose to be real DOM nodes.
2013-09-17 16:04:44 -07:00
Ben Alpert
364d6029b6 Flesh out reference documentation, more API info 2013-09-17 16:01:57 -07:00
Pete Hunt
735223fc9f Merge pull request #356 from yungsters/master
Add link to third-party `JavaScript (JSX).tmLanguage` in docs.
2013-09-17 13:35:59 -07:00
yungsters
be9ac236fd Add link to third-party JavaScript (JSX).tmLanguage in docs. 2013-09-17 13:30:53 -07:00
Josh Duck
ed7fa0ed22 Stop ReactInputSelection breaking in IE8
In the IE code path the method assumed that the input.value property
was non-null. A quick fix is to use either value or innerText; which means
the same code can be shared for textarea and contentEditable components.

The code is slightly buggy because the range.parentElement() !== input check
will fail for contentEditable components when the focus within a deep DOM tree.
2013-09-14 06:18:03 -07:00
Tim Yung
3e4302e6ae Fix lint errors in tests 2013-09-14 06:17:50 -07:00
Josh Duck
1a38cb9e07 Ensure selection range exists
The selection object doesn't always have ranges. In Chrome the
selection is not updated before 'focus' event handlers are fired. See
http://jsfiddle.net/t4DYA/ for example.

The selection will have rangeCount of 0 and calling getRangeAt(0) will
throw error "Uncaught IndexSizeError: Index or size was negative, or greater
than the allowed value."
2013-09-14 06:16:15 -07:00
Paul O’Shannessy
71ad5cb37a Update wording 2013-09-14 13:48:17 +02:00
Paul O’Shannessy
8a7c977942 Merge pull request #338 from spicyj/fullpage-tests
Fix ReactRenderDocument tests
2013-09-11 16:54:48 -07:00
Paul O’Shannessy
63bacfacfd Merge pull request #339 from spicyj/doc-rendering
Fix full-page rendering
2013-09-11 16:54:31 -07:00
Paul O’Shannessy
c8ec4595bb Merge pull request #344 from benjamn/fix-silent-test-failure-due-to-requiring-React
Use a regular expression to parse out React.version
2013-09-11 16:03:59 -07:00
Ben Newman
133ea3df09 Use a regular expression to parse out React.version.
This fixes a silent failure of the test suite that appears to be due to
the call require('./build/modules/React').
2013-09-11 18:41:56 -04:00
Paul O’Shannessy
f729a28f3c Delete version.js
This file is an artifact of a build process long abandoned.
2013-09-11 14:20:26 -07:00
Paul O’Shannessy
7ff11c3c88 Merge pull request #332 from spicyj/radio-test
Fix radio input test in Chrome
2013-09-11 13:45:47 -07:00
Paul O’Shannessy
5ab68d9a0d Hard code version instead of doing constant replacement
This isn't really ideal, but it makes it so that people managing to
build with @providesModule still get a consistent experience (since this
is what gets packed client-side with react-page-middleware anyway).
2013-09-11 09:51:43 -07:00
Ben Alpert
58fae896fe Fix full-page rendering
Closes #337.

Test Plan:
Opened react-page sample without any JS errors. Also ran grunt test after cherry-picking this changeset on top of #338.
2013-09-11 01:26:49 -07:00
Ben Alpert
fea4fec0bc Fix ReactRenderDocument tests
I am unsure how this was ever supposed to work, as testDocument is guaranteed to be undefined at that point since beforeEach doesn't run synchronously. (I don't think there's any way to have beforeEach halt the tests.)
2013-09-10 22:42:05 -07:00
Paul O’Shannessy
d853bbcf77 Merge pull request #205 from spicyj/version
Add React.version
2013-09-10 18:35:12 -07:00
Paul O’Shannessy
f82f2a0fe2 Merge pull request #274 from chenglou/textarea-patch
fix textarea `value` of number 0
2013-09-10 18:01:33 -07:00
Ben Alpert
f69112cb3f JSX: Respect original spacing and newlines better
Fixes #335.

Now this JSX:

```
/** @jsx React.DOM */
var HelloMessage = React.createClass({
  render: function() {
    return <div>
      Look!
      <a href=
        "http://www.facebook.com/">Facebook
      </a>
    </div>;
  }
});
```

produces

```
/** @jsx React.DOM */
var HelloMessage = React.createClass({displayName: 'HelloMessage',
  render: function() {
    return React.DOM.div(null,
      " Look! ",
      React.DOM.a( {href:
        "http://www.facebook.com/"}, "Facebook "
      )
    );
  }
});
```

rather than the less-desirable

```
/** @jsx React.DOM */
var HelloMessage = React.createClass({displayName: 'HelloMessage',
  render: function() {
    return React.DOM.div(null,
" Look! ",      React.DOM.a( {href:"http://www.facebook.com/"}, "Facebook "      ),
    );
  }
});
```
2013-09-10 17:14:36 -07:00
Paul O’Shannessy
6d77ad4be3 Merge pull request #330 from spicyj/warn-class-for
Warn for 'class' and 'for' property names
2013-09-10 16:21:33 -07:00
Jeff Morrison
7a6a508066 Merge pull request #328 from zpao/no-transform-class
Stop transforming class -> className
2013-09-10 08:23:08 -07:00
Cheng Lou
cd019871e3 Fix input/textarea value of number 0 and false
Previously, setting textarea `value` to number 0 is treated as if `value` wasn't set at all (thus the textarea is cleared from 0 to '' upon `onChange`). `false` also renders as `"false"` instead of `""` for both `defaultValue` and `value`, on textarea _and_ input.
2013-09-10 10:40:53 -04:00
Paul O’Shannessy
63b58cf6b5 AUTHORS
Created a .mailmap file with all of the associations, then used
git + perl to create the AUTHORS file. In theory these should all get
picked up by npm.

I used ABC order so it would remain unbiased and automatable. I wish we
could go back and fill out the history or at least fix the commits we
have from CommitSyncScript, but oh well.

This also includes the script I used to automate this process in the
future.
2013-09-09 23:42:54 -07:00
Ben Alpert
3bbd966a82 Fix radio input test in Chrome
It seems like the `form="pluto"` was throwing it off and making the input live outside the form it should have been contained in, causing it to uncheck A. I added it intending to test the form attribute but ended up not needing it so removing it should be fine. (The tests were passing in phantomjs since it doesn't support the `form` attribute and simply ignored it.)

Test Plan:
grunt test; grunt test --debug
2013-09-09 23:38:05 -07:00
Isaac Salier-Hellendag
5388d70bb1 Add cut, copy, paste
Add clipboard events to React.

For forms, these shouldn't really be necessary -- the onChange event should handle deletions and insertions. For contenteditables, however, we need to be able to access clipboard data.
2013-09-09 23:33:05 -07:00
Ben Alpert
5fd4467bf7 Add React.version
getConfig needs to be a function because grunt.config.data.pkg.version isn't available at the time that grunt/config/jsx/jsx.js is required.

Test Plan:
grunt build, grunt lint, grunt test all work. After building, both react.js and react.min.js contain the version number.
2013-09-09 17:01:06 -07:00
Timothy Yung
aa765e8fa3 Merge pull request #287 from spicyj/noglobal
Remove all uses of ExecutionEnvironment.global
2013-09-09 16:23:20 -07:00
Ben Alpert
232b61044c Warn for 'class' and 'for' property names
Also stroke-linecap, stroke-width, stop-color, stop-opacity.

Test Plan:
grunt test
2013-09-09 15:59:42 -07:00
Ben Alpert
426cdbb3ae Remove all uses of ExecutionEnvironment.global
Closes #271.

All three of these files are DOM-specific so it should be fine to use window. (ReactEventTopLevelCallback isn't obviously DOM-specific but it calls getEventTarget which is so I think we're fine here.)

Test Plan:
grunt test, tried events in a real browser and they seemed to work still.
2013-09-09 15:51:06 -07:00
Paul O’Shannessy
d83fe785c5 Stop transforming class -> className
Update the broken examples too (`git grep class=`)
2013-09-09 15:37:43 -07:00
Ben Newman
888cc309e0 Stop using comments as boundary markers in dangerouslyRenderMarkup.
Jordan warned (and StackOverflow confirmed) that IE8 doesn't respect HTML
comment nodes when setting `.innerHTML`:
http://stackoverflow.com/questions/15006001/inserting-a-comment-in-innerhtml

The virtue of the comment strategy was that the parser did all the work of
maintaining the boundaries between markup chunks, using comments as the
boundary markers.  The new strategy (of tagging the first node with a
special attribute) has a similar virtue, since the parser should preserve
that attribute only for the nodes we care about, and any rendered nodes
that do not have the attribute can be ignored (and complained about by
`console.error`).
2013-09-09 14:59:55 -07:00
Paul O'Shannessy
4ed7b85ed8 Log unknown props only when we have a match
Logging every unknown property got very noisy when combined with use of `transferPropsTo`. I knew this would be a potential issue initially but decided it was worth it. Others disagreed and it's resulting in some confusion.

This changes the logging to ensure that we have a potential correction, so only DOMish properties should result in warnings.
2013-09-09 14:57:56 -07:00
Pete Hunt
647731e399 Supporting mounting into iframes
Sencha says that separating big components into their own iframes was important for performance:
http://www.sencha.com/blog/the-making-of-fastbook-an-html5-love-story.

Today the only thing stopping us is that events don't bubble to our events system from an iframe. This diff
looks at the owning document of the container and adds top-level listeners to it. It should not change
existing behavior and should improve our support for this.
2013-09-09 14:57:33 -07:00
Ben Newman
cd7d863f20 Avoid unnecessary array allocations in dangerouslyRenderMarkup. 2013-09-09 14:56:27 -07:00
Paul O'Shannessy
9d0f3623c3 Cache length of NodeList when updating radios 2013-09-09 11:53:13 -07:00
Pete Hunt
e010a2d90b Fix bugs with CSS3 animation event in webkit
We were incorrectly sniffing the animationend event.
2013-09-09 11:52:59 -07:00
Paul O’Shannessy
d704bc24f4 Initial build of ReactTransitionGroup
This builds `ReactTransitionGroup` with it's own copy of `React`, which
it total clownshoes. This should be technically usable, but definitely
should not be used in any production environment.
2013-09-07 16:18:14 -07:00
Paul O’Shannessy
ff2fc586d5 Merge pull request #324 from chenglou/backbone-todo-ex
Fix backbone todo example bugs.
2013-09-07 14:53:01 -07:00
Cheng Lou
78d305eb16 Fix backbone todo example bugs.
Fixed:
- New todo not submitting correctly (page refreshes. `preventDefault`
wasn't there.
- Old checked todo being removed will leave the checkmark on the next
todo replacing its position.
- Cannot change todo (`value`'s now a controlled field).
- `autofocus` (should be `autoFocus`, how ironic given the current
situation) on new todo input isn't working. Switched to manual
`focus()` in `componentDidMount` for now.
- More consistent breathing space between lines.
- Gutter at 80.

Added:
- Use todomvc-common base.css. The old one had to change ids to
classes. No longer necessary.
- Give `cx` a better name and move it in `Utils`.
- Trim input upon finishing edit.
- Remove todo if the new edited value is empty.
- Submit edited todo value on input blur.
- README to explain the existence of this example. Being able to
maintain a non-compilant version allows nice deviations from the
todomvc specs, such as animations, in the future.
2013-09-07 17:44:05 -04:00
Paul O’Shannessy
6b5c1810c0 Merge pull request #323 from benjamn/simplify-bin/jsx
Simplify bin/jsx to perform just the JSX transform
2013-09-07 14:41:55 -07:00
Paul O’Shannessy
e41912d6d4 Merge pull request #325 from spicyj/elseifdev
Move else if (__DEV__) into two statements
2013-09-07 14:08:03 -07:00
Ben Alpert
97e0926696 Move else if (__DEV__) into two statements
The minification stage doesn't like `else if (__DEV__)`.
2013-09-07 14:03:48 -07:00
Paul O’Shannessy
8df407deb8 Merge pull request #281 from spicyj/radio
Fix controlled radio button behavior
2013-09-07 13:54:57 -07:00
Paul O’Shannessy
2ba405d5f8 Merge pull request #267 from spicyj/warn-props
Warn about unknown property values
2013-09-07 13:06:41 -07:00
Ben Newman
658f41cb30 Simplify bin/jsx to perform just the JSX transform.
We will continue using `bin/jsx-internal`, well, internally.

Note that this version no longer respects `@providesModule`, and it
doesn't do anything special with constants like `__DEV__`, so we can no
longer get to claim that `bin/jsx` can be used to build the core.

I'm happy about this, personally, because it demonstrates the flexibility
of Commoner.
2013-09-06 16:20:25 -04:00
Ben Newman
ebc0d09595 Merge pull request #322 from petehunt/build-animations
Add ReactTransitionGroup to the build
2013-09-06 10:49:30 -07:00
petehunt
f7ea031dac Add ReactTransitionGroup to the build 2013-09-06 10:47:18 -07:00
Ben Alpert
b56b5885d0 Fix controlled radio button behavior
Fixes #242.
2013-09-06 00:57:51 -07:00
Ben Alpert
a4c23d328c Warn about unknown property values
Fixes #255.
2013-09-06 00:33:01 -07:00
Paul O'Shannessy
3cf14e8f9b Remove ReactChildren methods from React object
These are not terribly useful on this object and the naming of
`React.forEachChildren` sucked anyway.
2013-09-05 18:35:59 -07:00
Pete Hunt
c8886a0424 Make mounting on the root of the page work correctly
This was apparently only partially supported. We had issues initially mounting if there was no HTML present and
also had issues if we had to update HTML that was already there. This diff fixes all of these cases and has
tests to prove it. NOTE: I removed a test that was actually erroneous. My bad.
2013-09-05 13:50:18 -07:00
Paul O’Shannessy
4f0dea3e7e Merge pull request #294 from clayallsopp/better_update_msg
More helpful message if you update an unrendered component
2013-09-05 11:54:07 -07:00
Clay Allsopp
9dd8ef4777 fix formatting and test for correct error 2013-09-04 18:13:33 -07:00
Paul O’Shannessy
65c4ef91c7 Sync CSSCore from upstream 2013-09-04 16:47:16 -07:00
Pete Hunt
32d3d7774a Use dumpCache() rather than manual reset
I forgot this module existed until @benjamn reminded we had a way to do it.
2013-09-04 15:54:27 -07:00
Pete Hunt
8664c8ac57 Test cases covering rendering onto document
There were some bug reports here, I couldn't reproduce but wrote tests anyway. We should definitely have these.
2013-09-04 15:54:11 -07:00
Ben Newman
dea0cc01cf Improve error behavior of Danger.dangerouslyRenderMarkup.
HTML comment nodes are now interspersed in the original markup list so
that we can tell which chunks of markup rendered as more or less than one
node, and give a more helpful error message in that case.

Regardless of how many nodes were rendered, we only take the first one. If
zero nodes were rendered, then `resultList` will contain `null` at the
corresponding position.

If we decide to revisit the idea of using document fragments, it will be
very easy to handle the `!== 1` case by returning a document fragment.
2013-09-04 15:54:09 -07:00
Pete Hunt
80f1590265 Add ReactTransitionGroup
This introduces <ReactTransitionGroup>, a component that works a lot
like Angular's ng-animate.

The problem we're currently facing is twofold:
1. We don't really have a great convention surrounding CSS transitions
   in React
2. (harder) we can't animate nodes that are leaving the DOM, as their
   nodes are instantly destroyed.

To solve the first issue I've adopted Angular's convention. It's
implemented in ReactTransitionableChild.

The second part is what's tricky. To do this I've implemented three modules:
- ReactTransitionableChild, which can keep its old children around if they
  change to null
- ReactTransitionKeySet, which can look at a prev and next set of child
  keys and merge them in a reasonable way
- ReactTransitionGroup, which combines ReactTransitionableChild and
  ReactTransitionKeySet to keep nodes that are leaving the DOM in the
  DOM until their animations are complete
2013-09-04 15:54:06 -07:00
Paul O’Shannessy
c25c5b543b Update wording 2013-09-04 15:26:31 -07:00
Cheng Lou
8852b86ad8 Add Stack Overflow link for doc support page. 2013-09-04 16:01:48 -04:00
Paul O'Shannessy
a42fd30fc2 Remove React.autoBind for real
This has been deprecated for a long while now, we should actually remove it.
2013-09-03 14:27:00 -07:00
Pete Hunt
406dcbd8da Fix a few GC leaks in events system
Summary:
    - Weren't pooling the Transaction in the batching strategy
    - Creating a new closure for every event tick due to batchedUpdates()
    - EnterLeaveEventPlugin creates a new array on each event.

I wonder if there is more optimization opportunity in accumulate(). Squinting at the fps graph this seems to be faster and waste less memory but it's hard to conclusively tell. I did verify that these were all hotspots though.
2013-09-03 14:27:00 -07:00
Paul O’Shannessy
de61f9fd81 Merge pull request #298 from vjeux/pagination
Add pagination to blog
2013-09-03 13:35:12 -07:00
Paul O’Shannessy
57fe412619 Merge pull request #305 from brianr/tutorial-explain-showdown
Tutorial: show how to add showdown.js
2013-09-03 13:33:05 -07:00
Pete Hunt
b4ff29ac78 Merge pull request #312 from zpao/docs-redirect
Redirect /docs to the right page
2013-09-03 13:30:16 -07:00
Paul O’Shannessy
ba460de7ed Redirect /docs to the right page
I've hit this a few times where I want to get to docs so I take whatever
my urlbar gives me and strip out the actual page so I can get to the
root, however that's a 404.

This introduces a super easy way to redirect, which could be handy in
the future as docs get rewritten.

I would much rather do this with a real htaccess file or even just
handle 404s gracefully, but that's not currently an option with GitHub
pages (since we generate our own and don't use a custom domain).
2013-09-03 13:25:23 -07:00
Pete Hunt
c7768fde5d Merge pull request #307 from chenglou/todomvc-director
sync with tastejs todomvc
2013-09-02 10:22:58 -07:00
Clay Allsopp
15f84a391d move lifecycle check into replaceProps instead of updateComponent 2013-09-01 18:42:01 -07:00
Cheng Lou
2b9c34b5c7 sync with tastejs todomvc 2013-08-31 21:54:37 -04:00
Brian Rue
403b087e97 Tutorial: show how to add showdown.js 2013-08-30 16:29:01 -07:00
Sebastian Markbage
75aee1714b Expose the instance cache
We need access to the instance cache for debugging tools. Ideally we want to
expose a more stable and supported interface but this seems like a quick win,
for now.
2013-08-30 13:21:04 -07:00
Pete Hunt
c41e86c990 Make ReactDefaultPerf work server-side
We were reading from window which was throwing when ReactDefaultPerf was injected.
2013-08-30 13:20:53 -07:00
Paul O'Shannessy
4d8f0449d9 React.isValidClass
Sometimes you may need to detect if a value is a valid React class constructor. This enables that and prevents future consumers from getting caught in the trap of depending on an internal implementation detail we might change.

Currently this works for classes created with `React.createClass` as well as `React.DOM.*`.
2013-08-30 13:20:51 -07:00
Pete Hunt
0db4077c3a Make React batching strategy injectable 2013-08-30 13:20:48 -07:00
Tim Yung
f88aa35187 Change vendored module isDOMNode -> isNode 2013-08-30 13:20:45 -07:00
Andrew Zich
7d34c09e17 Don't trigger mouse events on native button elements that are disabled
This adds a `ReactDOMButton` module that shims the native `<button>` React component so it doesn't receive mouseup, mousemove, mousedown, click, or double-click events when its disabled property is truthy.
2013-08-30 13:20:40 -07:00
Paul O’Shannessy
e11c4ecbaf [docs] Small tweaks as reported in comments
* highlight `</form>`
* use correct id in `getElementById` call
2013-08-28 14:42:07 -07:00
Paul O’Shannessy
553ed1416c Update package dependencies
Sometimes I look at https://david-dm.org/facebook/react
2013-08-27 14:46:06 -07:00
Paul O’Shannessy
688f5051e6 Sync objMap from upstream 2013-08-27 14:43:46 -07:00
Pete Hunt
adb666e67f Allow getInitialState() for mixins
Today mixins can't easily be stateful because they can't provide getInitialState(). This allows multiple getInitialState() methods as long as they don't return objects that have conflicting keys. In that case, we throw.
2013-08-27 14:17:26 -07:00
Paul O’Shannessy
07e2072692 Support props for <meta> elements.
`content`, `httpEquiv`, `charSet` are all needed. We're currently
working around this in `react-page`.

`content` is the risky one here since we previously supporting using
`content` to set the text content. We removed support for that in
e998041229 so the risk is minimal, there
just might be some lingering old code.

Fixes #292

Test Plan: Visit `data:text/html,<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" charset="utf-8"></head>`

```
var m = document.querySelector('meta');
m.httpEquiv; // Content-Type
m.httpEquiv = 'foo';
m.httpEquiv; // foo

m.charset; // undefined
m.charSet; // undefined
m.getAttribute('charset'); // utf-8
m.setAttribute('charset', 'bar');
m.getAttribute('charset'); // bar

m.content; // text/html; charset=utf-8
m.content = 'baz';
m.content; // baz
```
2013-08-27 11:45:59 -07:00
Vjeux
1c14cd6c8b Add pagination to blog
- Add pagination
- Display full content in /blog
- Truncate Recent posts
- Add permalink that lists all the blog posts
- Add spacing and bullet around recent posts to make it more readable
2013-08-27 02:14:17 +02:00
Paul O’Shannessy
744b54a829 Fix capitalization of Tooling Integration page 2013-08-26 14:53:56 -07:00
Vjeux
a90c463abe Update the tooling page to include pyReact, react-rails and react-page 2013-08-26 14:49:31 -07:00
Vjeux
6bf21f1610 Community round-up #7
http://fooo.fr:4000/react/blog/2013/08/26/community-roundup-7.html
2013-08-26 14:22:16 -07:00
Ben Alpert
364ee1ffae Add missing "use strict" statement to pass lint
Test Plan:
grunt lint; grunt test
2013-08-26 13:46:11 -07:00
Clay Allsopp
88faef3ba9 Add more helpful invariant if you're updating an unrendered component 2013-08-26 10:42:53 -07:00
Eric Clemmons
bcc6b524fb Add rowSpan DOM property 2013-08-25 13:32:38 -05:00
Sebastian Markbage
61b38b9f05 Explicit and Implicit Keys Need Separate Namespaces
There are certain cases where you can end up with a collision with an implicit
key (array index) if your explicit key prop is a number. They should use
different namespaces. Therefore I wrap explicit keys in curlies and implicit
array indices in brackets.

I added a simple test case, but another case came up on the mailing list. Where
undefined entries in an array actually results in an entry and therefore an
implicit key.
2013-08-23 14:05:18 -07:00
Danny Ben-David
fce57abeca Benchmarking tool for React application performance
ReactAppPerf wraps core methods and logs info from them; there's no real
UI at this point
2013-08-23 14:05:11 -07:00
Paul O’Shannessy
946e9b0c80 Merge pull request #289 from jordwalke/ServerRenderingFixes3
Server rendering: rendering of entire document using React.
2013-08-23 13:14:06 -07:00
Jordan Walke
748ed6cd81 adding better test - moving execution env module. 2013-08-23 12:32:35 -07:00
Jordan Walke
49f174cdad Server rendering: rendering of entire document using React.
Summary: Allows rendering of React into the "document" as opposed to into a
particular node. To recap some basics:

document: One level above the <html> tag - like the browser.
document.documentElement: <body>

To support full-page server side rendering, we need to be able to render
*everything* including the HTML/BODY tags. This allows that.
2013-08-23 02:04:07 -07:00
Paul O’Shannessy
6ca8d31c83 [react-tools] Add src/ to files
This is so it's possible to use the original @providesModule source
files in a toolchain that understands those.
2013-08-22 22:35:50 -07:00
Paul O’Shannessy
aa1fa7468b Merge pull request #280 from jeffmo/jstransform_npm
Move to using `jstransform` and `esprima-fb` npm modules
2013-08-22 15:43:59 -07:00
JeffMo
2d048f1f34 Move to using jstransform and esprima-fb npm modules 2013-08-22 15:28:41 -07:00
Clay Allsopp
3d1cc16a9b Add CDNJS to docs. Fixes #244 2013-08-22 11:07:50 -07:00
Paul O’Shannessy
cbe86e04b3 Docs: fix header 2013-08-22 11:02:09 -07:00
Paul O’Shannessy
a558e560bd Use script to find remaining 404s. Fix them. 2013-08-22 10:59:22 -07:00
Clay Allsopp
cfe4152b1d Fix broken tutorial link and change wording 2013-08-21 22:38:44 -07:00
Kunal Mehta
91c2a8d90b Added PyReact blog post. 2013-08-19 14:48:28 -07:00
Christopher Chedeau
2c8f907b2c Merge pull request #277 from stoyan/patch-1
typo fix
2013-08-19 11:45:51 -07:00
Tim Yung
669f4b867f Allow DOM Nodes in ImmutableObject
Currently, `ImmutableObject` will stack overflow while it tries to recurse and deep freeze all the properties of a DOM node.
2013-08-19 11:37:08 -07:00
Stoyan
5fae286cf4 typo fix 2013-08-19 11:35:46 -07:00
Timothy Yung
a2c90aad86 Merge pull request #275 from spicyj/input-private
Make getChecked, getValue, handleChange private
2013-08-19 11:20:52 -07:00
Ben Alpert
898621d0a1 Make getChecked, getValue, handleChange private
Test Plan: grunt test, enter text in ballmer-peak example without any JS errors.
2013-08-17 22:29:41 -07:00
Timothy Yung
e1c1d869de Merge pull request #251 from spicyj/select-value
Fix behavior of ReactDOMSelect with `defaultValue`
2013-08-17 21:50:13 -07:00
Ben Alpert
25e2cd0db6 Fix behavior of ReactDOMSelect
Closes #250.

Test Plan:
With multiple and not, verified: With defaultValue, the correct option is picked initially, user changes change the selection, and changes to defaultValue have no effect. With value, the correct option is picked initially, user changes do nothing, and changes to value change the selection.

Also ran the tests.
2013-08-17 16:57:49 -07:00
Paul O’Shannessy
1f8ef4c903 Sync modules to vendor/core
We haven't done this recently. Nothing has changed significantly, though
this does remove some files we weren't using.
2013-08-16 15:40:23 -07:00
James Ide
d9511d817a Move utils out of React that aren't being used
Many of React's util functions are non-redundant with Facebook's core
libraries, so move them out of React into a central location (out of
this repo).

These files were not getting used by any part of React core, so didn't
actually belong here anyway.
2013-08-16 15:40:11 -07:00
Cheng Lou
2fda70fb4a fix test case for rendering text node number 0 2013-08-16 13:51:17 -07:00
Sebastian Markbåge
02f618d52c Merge pull request #268 from spicyj/bind-null
Make .bind(null, ...) work on autobound methods
2013-08-16 12:06:49 -07:00
Jordan Walke
61c47e4cae Refactor ReactComponent to have no dependency on the DOM.
React is more than just a DOM app library, it is a component
abstraction library. This enforces that.
2013-08-15 10:56:39 -07:00
Jordan Walke
e6b216bdbb Extract out core ReactEmitter functionality.
Other environments can make use of some of the logic in ReactEventEmitter.
2013-08-15 10:56:30 -07:00
Ben Alpert
192727e152 Make .bind(null, ...) work on autobound methods
Fixes #266.
2013-08-15 09:58:38 -07:00
Paul O’Shannessy
cb00d3e66c Upgrade phantomjs to 1.9.1-4
This fixes the install and permissions issues we've been seeing with
other 1.9.1-x versions.
2013-08-13 15:37:26 -07:00
Paul O’Shannessy
987e5e8f13 Merge pull request #258 from chenglou/patch-3
defaultValue of 0 now displayed
2013-08-12 18:20:32 -07:00
Paul O’Shannessy
df0bc8c3af Merge pull request #261 from benjamn/phantomjs-1.9.0-1
Hold PhantomJS version at 1.9.0-1.
2013-08-12 15:21:50 -07:00
Ben Newman
983120102c Hold PhantomJS version at 1.9.0-1.
And don't attempt any chmod magic, either.
2013-08-12 17:47:31 -04:00
Cheng Lou
86c0b69390 separate new tests into respective file 2013-08-12 17:03:10 -04:00
Cheng Lou
d5989a0de4 tests for displaying defaultValue of 0 2013-08-12 16:08:16 -04:00
Cheng Lou
1b747c526c defaultValue of 0 now displayed
previously treated as empty string when passed to input text/textarea
2013-08-09 23:13:44 -04:00
Paul O'Shannessy
5cbabdf4c9 Support autocapitalize DOM Property
It's non-standard, but potentially useful on mobile.

See some discussion in google group: https://groups.google.com/forum/#!topic/reactjs/MBcCFohHHHA

Closes #247
2013-08-06 14:19:49 -07:00
Paul Shen
9ef4e74ba2 ReactChildren
Instead of changing `traverseAllChildren`, keep that around for perf
reasons (for the hot code path `flattenChildren`)

Introduce `ReactChildren.map` and `ReactChildren.forEach`
which mirrors `Array.prototype.map` and `Array.prototype.forEach`. This
involves a rename of `mapAllChildren`
2013-08-06 14:17:33 -07:00
Vjeux
0321171113 Community Round-up #6 2013-08-06 01:31:23 +02:00
Christopher Chedeau
d542621155 Fix 404 in Getting Started 2013-08-04 21:09:15 -07:00
Pete Hunt
4bbf8acc9b Merge pull request #249 from pcottle/fixLinks
Fix Github links in examples
2013-08-04 17:40:00 -07:00
Peter Cottle
a21556314d Fix Github links in examples
Looks like we link to github.com/facebook/react/ instead of react-js. This just fixes the links

`grep -r "facebook/react.js" .` comes up clean now
2013-08-04 16:40:12 -07:00
Paul O'Shannessy
99d3d7f914 Get rid of remaining ReactID references
It's gone. Also compacted a bit of code to match the other usage.
2013-08-01 13:58:28 -07:00
Paul O’Shannessy
86d9e0a97a Merge pull request #245 from chenglou/patch-3
Change ref from ReactID to ReactInstanceHandles
2013-08-01 13:41:10 -07:00
Cheng Lou
db0ff96200 Change ref from ReactID to ReactInstanceHandles 2013-08-01 14:52:08 -04:00
Tim Yung
808e625d9d Use createNodesFromMarkup
Pulled out markup rendering logic for better reuse.
2013-07-31 21:21:06 -07:00
Paul O’Shannessy
dc06704ec7 react-rails blog post 2013-07-30 15:25:44 -07:00
Tim Yung
5ef3c1b09b Fix Reconciling Components to Content
This fixes a reconciliation bug introduced by adffa9b0f4.

The new unit test case exhibits the bug. When a component that has rendered child components is updated to render inline text, we usually:

 # Unmount and remove all child components.
 # Set the new inline text content.

However, with batched child operations, we do not **remove all child components** until later. The current implementation will set the inline text content and blow away those nodes, causing a fatal when `ReactMultiChild` later tries to find and remove those nodes.

This fixes the bug by ensuring that text content changes are also enqueued.
2013-07-29 16:15:30 -07:00
Paul O’Shannessy
fe451c30f8 Merge pull request #241 from gasi/master
Fix incorrect port of standard Python server
2013-07-29 11:09:37 -07:00
Daniel Gasienica
6f2848f4a6 Fix incorrect port of standard Python server
/ht @zpao
2013-07-29 10:59:43 -07:00
Paul O’Shannessy
d63ce62916 Merge pull request #207 from thisishugo/patch-1
update dead jsx link to point to an extant page
2013-07-29 09:11:37 -07:00
Ben Newman
c7d6a5ae4d Merge pull request #237 from yungsters/master
Fix Test Failures
2013-07-28 07:02:17 -07:00
yungsters
d5e970b93f Fix Danger test failures.
The original tests were flawed because the `Danger` module exploits the fact that all React-generated markup has at least one attribute. This allows the module to extract node names from markup strings faster.

However, the tests were passing in strings of markup with no attributes.

Also, this fixes a test failure due to the test trying to set text content into a `<tr>` which is typically disallowed by browsers (and PhantomJS). This changes it to use `<td>` instead.
2013-07-28 01:05:13 -07:00
yungsters
4cb49f5561 Change ReactMultiChild test to check for innerHTML descriptor.
Not all testing environments will support setting the `innerHTML` descriptor. For example, PhantomJS initializes the `innerHTML` property as not configurable.
2013-07-28 01:04:24 -07:00
Paul O’Shannessy
c347b720a9 Updated Readme for 0.4.1 2013-07-26 15:57:37 -07:00
Paul O’Shannessy
27a1729f6d Blog post for v0.4.1 2013-07-26 15:56:52 -07:00
Paul O’Shannessy
a1f5c1dee7 Updated Changelog for 0.4.1 2013-07-26 15:56:22 -07:00
Paul O’Shannessy
20179b7991 Send branch info from travis for continuous builds 2013-07-26 14:28:33 -07:00
Tim Yung
adffa9b0f4 Batch Child Markup Generation
Setting `innerHTML` is slow: http://jsperf.com/react-child-creation/2

This reduces the number of times we set `innerHTML` by batching markup generation in a component tree.

As usual, I cleaned up the `ReactMultiChild` module significantly.

== Children Reconciliation ==

When a `ReactNativeComponent` reconciles, it compares currently rendered children, `prevChildren`, with the new children, `nextChildren`. It figures out the shortest series of updates required to render `nextChildren` where each update is one of:

 - Create nodes for a new child and insert it at an index.
 - Update an existing node and, if necessary, move it to an index.
 - Remove an existing node.

This serializable series of updates is sent to `ReactDOMIDOperations` where the actions are actually acted on.

== Problem ==

There are two problems:

 # When a `ReactNativeComponent` renders new children, it sets `innerHTML` once for each contiguous set of children.
 # Each `ReactNativeComponent` renders its children in isolation, so two components that both render new children will do so separately.

For example, consider the following update:

  React.renderComponent(<div><p><span /></p><p><span /></p></div>, ...);
  React.renderComponent(<div><p><img /><span /><img /></p><p><img /><span /><img /></p></div>, ...);

This will trigger setting `innerHTML` four times.

== Solution ==

Instead of enqueuing the series of updates per component, this diff changes `ReactMultiChild` to enqueue updates per component tree (which works by counting recursive calls to `updateChildren`). Once all updates in the tree are accounted for, we render all markup using a single `innerHTML` set.
2013-07-26 12:48:07 -07:00
Tim Yung
2e37f65bdc Delete throwIf
Deletes `throwIf()` in favor of having one way to throw errors: `invariant()`
2013-07-26 12:48:07 -07:00
Hugo Jobling
4ab62a6bd2 remove dead link
the event handling doc page no longer exists
2013-07-18 11:05:39 +01:00
Hugo Jobling
07427ae9d0 put closing paren in correct place 2013-07-18 10:44:22 +01:00
Hugo Jobling
8f55d94d40 update dead jsx link to point to an extant page
syntax.html no longer exists, so point people at the in depth article instead.
2013-07-18 10:36:54 +01:00
248 changed files with 11536 additions and 4394 deletions

21
.mailmap Normal file
View File

@@ -0,0 +1,21 @@
Ben Newman <bn@cs.stanford.edu> <benjamn@fb.com>
Dan Schafer <dschafer@fb.com>
Harry Hull <harry.hull1@gmail.com>
Jeff Morrison <jeff@anafx.com> <Jeff@anafx.com>
Jeff Morrison <jeff@anafx.com> JeffMo <jeffmo@fb.com>
Jeffrey Lin <lin.jeffrey@gmail.com> <jeffreylin@fb.com>
Jordan Walke <jordojw@gmail.com>
Jordan Walke <jordojw@gmail.com> <jordanjcw@fb.com>
Laurence Rowe <l@lrowe.co.uk> <laurence@lrowe.co.uk>
Nick Gavalas <njg57@cornell.edu>
Paul OShannessy <paul@oshannessy.com> <poshannessy@fb.com>
Paul Shen <paul@mnml0.com> <paulshen@fb.com>
Pete Hunt <floydophone@gmail.com>
Pete Hunt <floydophone@gmail.com> <pete.hunt@fb.com>
Pete Hunt <floydophone@gmail.com> <pete@instagram.com>
Sander Spies <sandermail@gmail.com>
Sebastian Markbåge <sebastian@calyptus.eu> <sema@fb.com>
Stoyan Stefanov <ssttoo@ymail.com>
Timothy Yung <yungsters@gmail.com> <yungsters@fb.com>
Vjeux <vjeuxx@gmail.com>
Vjeux <vjeuxx@gmail.com> <vjeux@fb.com>

View File

@@ -4,8 +4,9 @@ node_js:
- '0.10'
after_script:
- curl -F "react=@build/react.js" -F "react.min=@build/react.min.js" -F "transformer=@build/JSXTransformer.js"
-F "react-with-addons=@build/react-with-addons.js" -F "react-with-addons.min=@build/react-with-addons.min.js"
-F "commit=$TRAVIS_COMMIT" -F "date=`git log --format='%ct' -1`" -F "pull_request=$TRAVIS_PULL_REQUEST"
-F "token=$SECRET_TOKEN" $SERVER
-F "token=$SECRET_TOKEN" -F "branch=$TRAVIS_BRANCH" $SERVER
env:
global:
# SERVER

50
AUTHORS Normal file
View File

@@ -0,0 +1,50 @@
Alexander Solovyov <alexander@solovyov.net>
Andrew Zich <azich@fb.com>
Andrey Popp <8mayday@gmail.com>
Ben Alpert <spicyjalapeno@gmail.com>
Ben Newman <bn@cs.stanford.edu>
Brian Rue <brian@rollbar.com>
Cam Spiers <camspiers@gmail.com>
Cat Chen <catchen@fb.com>
Cheng Lou <chenglou92@gmail.com>
Christian Roman <chroman16@gmail.com>
Clay Allsopp <clay.allsopp@gmail.com>
Connor McSheffrey <connor.mcsheffrey@gmail.com>
Dan Schafer <dschafer@fb.com>
Daniel Gasienica <dgasienica@zynga.com>
Daniel Miladinov <dmiladinov@wingspan.com>
Danny Ben-David <dannybd@fb.com>
David Hu <davidhu91@gmail.com>
Eric Clemmons <eric@smarterspam.com>
Greg Roodt <groodt@gmail.com>
Harry Hull <harry.hull1@gmail.com>
Hugo Jobling <me@thisishugo.com>
Ian Obermiller <iano@fb.com>
Isaac Salier-Hellendag <isaac@fb.com>
Jakub Malinowski <jakubmal@gmail.com>
James Ide <ide@fb.com>
Jamie Wong <jamie.lf.wong@gmail.com>
Jan Kassens <jkassens@fb.com>
Jeff Morrison <jeff@anafx.com>
Jeffrey Lin <lin.jeffrey@gmail.com>
Jordan Walke <jordojw@gmail.com>
Josh Duck <josh@fb.com>
Keito Uchiyama <keito@fb.com>
Kunal Mehta <k.mehta@berkeley.edu>
Laurence Rowe <l@lrowe.co.uk>
Marshall Roch <mroch@fb.com>
Martin Konicek <mkonicek@fb.com>
Mathieu M-Gosselin <mathieumg@gmail.com>
Nick Gavalas <njg57@cornell.edu>
Owen Coutts <owenc@fb.com>
Paul OShannessy <paul@oshannessy.com>
Paul Seiffert <paul.seiffert@gmail.com>
Paul Shen <paul@mnml0.com>
Pete Hunt <floydophone@gmail.com>
Peter Cottle <pcottle@fb.com>
Sander Spies <sandermail@gmail.com>
Sebastian Markbåge <sebastian@calyptus.eu>
Stoyan Stefanov <ssttoo@ymail.com>
Timothy Yung <yungsters@gmail.com>
Vjeux <vjeuxx@gmail.com>
Zach Bruggeman <zbruggeman@me.com>

View File

@@ -1,3 +1,68 @@
## 0.5.1 (October 29, 2013)
### React
* Fixed bug with `<input type="range">` and selection events.
* Fixed bug with selection and focus.
* Made it possible to unmount components from the document root.
* Fixed bug for `disabled` attribute handling on non-`<input>` elements.
### React with Addons
* Fixed bug with transition and animation event detection.
## 0.5.0 (October 16, 2013)
### React
* Memory usage improvements - reduced allocations in core which will help with GC pauses
* Performance improvements - in addition to speeding things up, we made some tweaks to stay out of slow path code in V8 and Nitro.
* Standardized prop -> DOM attribute process. This previously resulting in additional type checking and overhead as well as confusing cases for users. Now we will always convert your value to a string before inserting it into the DOM.
* Support for Selection events.
* Support for [Composition events](https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent).
* Support for additional DOM properties (`charSet`, `content`, `form`, `httpEquiv`, `rowSpan`, `autoCapitalize`).
* Support for additional SVG properties (`rx`, `ry`).
* Support for using `getInitialState` and `getDefaultProps` in mixins.
* Support mounting into iframes.
* Bug fixes for controlled form components.
* Bug fixes for SVG element creation.
* Added `React.version`.
* Added `React.isValidClass` - Used to determine if a value is a valid component constructor.
* Removed `React.autoBind` - This was deprecated in v0.4 and now properly removed.
* Renamed `React.unmountAndReleaseReactRootNode` to `React.unmountComponentAtNode`.
* Began laying down work for refined performance analysis.
* Better support for server-side rendering - [react-page](https://github.com/facebook/react-page) has helped improve the stability for server-side rendering.
* Made it possible to use React in environments enforcing a strict [Content Security Policy](https://developer.mozilla.org/en-US/docs/Security/CSP/Introducing_Content_Security_Policy). This also makes it possible to use React to build Chrome extensions.
### React with Addons (New!)
* Introduced a separate build with several "addons" which we think can help improve the React experience. We plan to deprecate this in the long-term, instead shipping each as standalone pieces. [Read more in the docs](http://facebook.github.io/react/docs/addons.html).
### JSX
* No longer transform `class` to `className` as part of the transform! This is a breaking change - if you were using `class`, you *must* change this to `className` or your components will be visually broken.
* Added warnings to the in-browser transformer to make it clear it is not intended for production use.
* Improved compatibility for Windows
* Improved support for maintaining line numbers when transforming.
## 0.4.1 (July 26, 2013)
### React
* `setState` callbacks are now executed in the scope of your component.
* `click` events now work on Mobile Safari.
* Prevent a potential error in event handling if `Object.prototype` is extended.
* Don't set DOM attributes to the string `"undefined"` on update when previously defined.
* Improved support for `<iframe>` attributes.
* Added checksums to detect and correct cases where server-side rendering markup mismatches what React expects client-side.
### JSXTransformer
* Improved environment detection so it can be run in a non-browser environment.
## 0.4.0 (July 17, 2013)
### React

View File

@@ -52,27 +52,48 @@ module.exports = function(grunt) {
grunt.registerMultiTask('npm', npmTask);
grunt.registerTask('build:basic', ['jsx:debug', 'browserify:basic']);
// Check that the version we're exporting is the same one we expect in the
// package. This is not an ideal way to do this, but makes sure that we keep
// them in sync.
var reactVersionExp = /\bReact\.version\s*=\s*['"]([^'"]+)['"];/;
grunt.registerTask('version-check', function() {
var version = reactVersionExp.exec(
grunt.file.read('./build/modules/React.js')
)[1];
var expectedVersion = grunt.config.data.pkg.version;
if (version !== expectedVersion) {
grunt.log.error('Versions do not match. Expected %s, saw %s', expectedVersion, version);
return false;
}
});
grunt.registerTask('build:basic', ['jsx:debug', 'version-check', 'browserify:basic']);
grunt.registerTask('build:addons', ['jsx:debug', 'browserify:addons']);
grunt.registerTask('build:transformer', ['jsx:debug', 'browserify:transformer']);
grunt.registerTask('build:min', ['jsx:release', 'browserify:min']);
grunt.registerTask('build:min', ['jsx:release', 'version-check', 'browserify:min']);
grunt.registerTask('build:addons-min', ['jsx:debug', 'browserify:addonsMin']);
grunt.registerTask('build:test', [
'jsx:jasmine',
'jsx:test',
'version-check',
'populist:jasmine',
'populist:test'
]);
grunt.registerTask('test', ['build:test', 'phantom:run']);
grunt.registerTask('test', ['build:test', 'build:basic', 'phantom:run']);
grunt.registerTask('npm:test', ['build', 'npm:pack']);
// Optimized build task that does all of our builds. The subtasks will be run
// in order so we can take advantage of that and only run jsx:debug once.
grunt.registerTask('build', [
'jsx:debug',
'version-check',
'browserify:basic',
'browserify:transformer',
'browserify:addons',
'jsx:release',
'browserify:min',
'browserify:addonsMin',
'copy:react_docs',
'compare_size'
]);

View File

@@ -28,20 +28,20 @@ React.renderComponent(
This example will render "Hello John" into a container on the page.
You'll notice that we used an XML-like syntax; [we call it JSX](http://facebook.github.io/react/docs/syntax.html). JSX is not required to use React, but it makes code more readable, and writing it feels like writing HTML. A simple transform is included with React that allows converting JSX into native JavaScript for browsers to digest.
You'll notice that we used an XML-like syntax; [we call it JSX](http://facebook.github.io/react/docs/jsx-in-depth.html). JSX is not required to use React, but it makes code more readable, and writing it feels like writing HTML. A simple transform is included with React that allows converting JSX into native JavaScript for browsers to digest.
## Installation
The fastest way to get started is to serve JavaScript from the CDN:
The fastest way to get started is to serve JavaScript from the CDN (also available on [CDNJS](http://cdnjs.com/#react)):
```html
<!-- The core React library -->
<script src="http://fb.me/react-0.4.0.min.js"></script>
<script src="http://fb.me/react-0.5.1.js"></script>
<!-- In-browser JSX transformer, remove when pre-compiling JSX. -->
<script src="http://fb.me/JSXTransformer-0.4.0.js"></script>
<script src="http://fb.me/JSXTransformer-0.5.1.js"></script>
```
We've also built a [starter kit](http://facebook.github.io/react/downloads/react-0.4.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.5.1.zip) which might be useful if this is your first time using React. It includes a webpage with an example of using React with live code.
If you'd like to use [bower](http://bower.io), it's as easy as:

49
bin/jsx
View File

@@ -2,54 +2,11 @@
"use strict";
var visitors = require('../vendor/fbtransform/visitors').transformVisitors;
var transform = require('../vendor/fbtransform/lib/transform').transform;
var propagate = require("../vendor/constants").propagate;
var transform = require('jstransform').transform;
require("commoner").resolve(function(id) {
var context = this;
// Note that the result of context.getProvidedP() is cached for the
// duration of the build, so it is both consistent and cheap to
// evaluate multiple times.
return context.getProvidedP().then(function(idToPath) {
// If a module declares its own identifier using @providesModule
// then that identifier will be a key in the idToPath object.
if (idToPath.hasOwnProperty(id)) {
return context.readFileP(idToPath[id]);
}
// Otherwise assume the identifier maps directly to a path in the
// filesystem.
return context.readModuleP(id);
});
return this.readModuleP(id);
}).process(function(id, source) {
var context = this;
var constants = context.config.constants || {};
// This is where JSX, ES6, etc. desugaring happens.
source = transform(visitors.react, source).code;
// Constant propagation means removing any obviously dead code after
// replacing constant expressions with literal (boolean) values.
source = propagate(constants, source);
if (context.config.mocking) {
// Make sure there is exactly one newline at the end of the module.
source = source.replace(/\s+$/m, "\n");
return context.getProvidedP().then(function(idToPath) {
if (id !== "mock-modules" &&
id !== "mocks" &&
id !== "test/all" &&
idToPath.hasOwnProperty("mock-modules")) {
return source + '\nrequire("mock-modules").register(' +
JSON.stringify(id) + ', module);\n';
}
return source;
});
}
return source;
return transform(visitors.react, source).code;
});

55
bin/jsx-internal Executable file
View File

@@ -0,0 +1,55 @@
#!/usr/bin/env node
"use strict";
var visitors = require('../vendor/fbtransform/visitors').transformVisitors;
var transform = require('jstransform').transform;
var propagate = require("../vendor/constants").propagate;
require("commoner").resolve(function(id) {
var context = this;
// Note that the result of context.getProvidedP() is cached for the
// duration of the build, so it is both consistent and cheap to
// evaluate multiple times.
return context.getProvidedP().then(function(idToPath) {
// If a module declares its own identifier using @providesModule
// then that identifier will be a key in the idToPath object.
if (idToPath.hasOwnProperty(id)) {
return context.readFileP(idToPath[id]);
}
// Otherwise assume the identifier maps directly to a path in the
// filesystem.
return context.readModuleP(id);
});
}).process(function(id, source) {
var context = this;
var constants = context.config.constants || {};
// This is where JSX, ES6, etc. desugaring happens.
source = transform(visitors.react, source).code;
// Constant propagation means removing any obviously dead code after
// replacing constant expressions with literal (boolean) values.
source = propagate(constants, source);
if (context.config.mocking) {
// Make sure there is exactly one newline at the end of the module.
source = source.replace(/\s+$/m, "\n");
return context.getProvidedP().then(function(idToPath) {
if (id !== "mock-modules" &&
id !== "mocks" &&
id !== "test/all" &&
idToPath.hasOwnProperty("mock-modules")) {
return source + '\nrequire("mock-modules").register(' +
JSON.stringify(id) + ', module);\n';
}
return source;
});
}
return source;
});

View File

@@ -1,5 +1,7 @@
source 'https://rubygems.org'
gem 'rake'
# jekyll, which builds it all
gem 'jekyll', '~>1.0'
@@ -14,3 +16,6 @@ gem 'rb-fsevent'
# Redcarpet for Markdown
gem 'redcarpet'
# For markdown header cleanup
gem 'sanitize'

View File

@@ -24,13 +24,19 @@ GEM
liquid (2.5.0)
maruku (0.6.1)
syntax (>= 1.0.0)
mini_portile (0.5.1)
nokogiri (1.6.0)
mini_portile (~> 0.5.0)
posix-spawn (0.3.6)
pygments.rb (0.5.0)
posix-spawn (~> 0.3.6)
yajl-ruby (~> 1.1.0)
rake (10.0.4)
rb-fsevent (0.9.3)
redcarpet (2.2.2)
safe_yaml (0.7.1)
sanitize (2.0.6)
nokogiri (>= 1.4.4)
sass (3.2.9)
syntax (1.0.0)
yajl-ruby (1.1.0)
@@ -41,6 +47,8 @@ PLATFORMS
DEPENDENCIES
jekyll (~> 1.0)
json
rake
rb-fsevent
redcarpet
sanitize
sass

View File

@@ -13,7 +13,7 @@ task :js do
end
desc "watch css & js"
task :watch => [:update_version] do
task :watch do
Process.spawn "sass --style=compressed --watch _css/react.scss:css/react.css"
Process.spawn "../bin/jsx --watch _js js"
Process.waitall
@@ -30,8 +30,8 @@ task :update_version do
end
desc "build into ../../react-gh-pages"
task :release => [:default] do
task :release => [:update_version, :default] do
system "jekyll build -d ../../react-gh-pages"
end
task :default => [:update_version, :css, :js]
task :default => [:css, :js]

View File

@@ -13,9 +13,11 @@ redcarpet:
pygments: true
name: React
markdown: redcarpet
react_version: 0.4.0
react_version: 0.5.1
description: A JavaScript library for building user interfaces
relative_permalinks: true
paginate: 5
paginate_path: /blog/page:num
nav_docs_sections:
- title: Quick Start
items:
@@ -48,6 +50,22 @@ nav_docs_sections:
- id: more-about-refs
title: More About Refs
- id: tooling-integration
title: Tooling integration
- id: reference
title: Reference
title: Tooling Integration
- id: addons
title: Add-ons
- id: examples
title: Examples
- title: Reference
items:
- id: top-level-api
title: Top-Level API
- id: component-api
title: Component API
- id: component-specs
title: Component Specs and Lifecycle
- id: tags-and-attributes
title: Supported Tags and Attributes
- id: events
title: Event System
- id: dom-differences
title: DOM Differences

View File

@@ -199,8 +199,7 @@ li {
font-size: 14px;
// position: fixed;
float: left;
top: 100px;
width: 180px;
width: 210px;
ul {
list-style: none;
@@ -248,6 +247,12 @@ li {
}
.nav-blog {
li {
margin-bottom: 5px;
}
}
// Home Page specifics
.home-section {
@@ -285,14 +290,14 @@ li {
margin-right: 0;
}
#examples {
h3 {
color: $darkColor;
font-size: 24px;
font-weight: normal;
margin-bottom: 5px;
}
#examples h3, .home-presentation h3 {
color: $darkColor;
font-size: 24px;
font-weight: normal;
margin-bottom: 5px;
}
#examples {
p {
margin: 0 0 25px 0;
max-width: $twoColumnWidth;
@@ -386,6 +391,16 @@ section.black content {
font-size: 24px;
}
h1, h2, h3, h4, h5, h6 {
a {
color: $darkTextColor;
&:hover {
text-decoration: underline;
}
}
}
// H2s form documentation topic dividers. Extra space helps.
h2 {
margin-top: 30px;
@@ -685,3 +700,15 @@ p code {
.post {
margin-bottom: 30px;
}
.pagination {
margin-bottom: 30px;
/* Trick to get the wrapper to expand to fit floating elements */
width: 100%;
overflow: hidden;
.next {
float: right;
}
}

View File

@@ -1,10 +1,11 @@
<div class="nav-docs">
<div class="nav-docs nav-blog">
<div class="nav-docs-section">
<h3>Recent posts</h3>
<ul>
{% for post in site.posts %}
<li><a href="/react{{ post.url }}"{% if page.title == post.title %} class="active"{% endif %}>{{ post.title }}</a></li>
{% endfor %}
{% for post in site.posts limit:10 %}
<li><a href="/react{{ post.url }}"{% if page.title == post.title %} class="active"{% endif %}>{{ post.title }}</a></li>
{% endfor %}
<li><a href="/react/blog/all.html">All posts ...</a></li>
</ul>
</div>
</div>

View File

@@ -44,7 +44,7 @@ var CodeMirrorEditor = React.createClass({
}
return (
<div class={this.props.className}>
<div className={this.props.className}>
{editor}
</div>
);
@@ -76,22 +76,22 @@ var ReactPlayground = React.createClass({
content =
<CodeMirrorEditor
onChange={this.bindState('code')}
class="playgroundStage"
className="playgroundStage"
codeText={this.state.code}
/>;
} else if (this.state.mode === this.MODES.JS) {
content =
<div class="playgroundJS playgroundStage">
<div className="playgroundJS playgroundStage">
{this.getDesugaredCode()}
</div>;
}
return (
<div class="playground">
<div class="playgroundCode">
<div className="playground">
<div className="playgroundCode">
{content}
</div>
<div class="playgroundPreview">
<div className="playgroundPreview">
<div ref="mount" />
</div>
</div>
@@ -121,7 +121,7 @@ var ReactPlayground = React.createClass({
}
} catch (e) {
React.renderComponent(
<div content={e.toString()} class="playgroundError" />,
<div content={e.toString()} className="playgroundError" />,
mountNode
);
}

View File

@@ -10,6 +10,7 @@
<meta property="og:url" content="http://facebook.github.io/react{{ page.url }}" />
<meta property="og:image" content="http://facebook.github.io/react/img/logo_og.png" />
<meta property="og:description" content="A JavaScript library for building user interfaces" />
<meta property="fb:app_id" content="623268441017527" />
<link rel="shortcut icon" href="/react/favicon.ico">
<link rel="alternate" type="application/rss+xml" title="{{ site.name }}" href="{{ site.url }}{{ site.baseurl }}/feed.xml">

View File

@@ -0,0 +1,6 @@
<html>
<head>
<meta http-equiv="refresh" content="0; {{ page.destination }}">
</head>
<body></body>
</html>

View File

@@ -0,0 +1,17 @@
require 'redcarpet'
require 'sanitize'
# Simple converter that is probably better than RedCarpet's built in TOC id
# generator (which ends up with things lik id="toc_1"... terrible).
class Redcarpet::Render::HTML
def header(title, level)
clean_title = Sanitize.clean(title)
.downcase
.gsub(/\s+/, "-")
.gsub(/[^A-Za-z0-9\-_.]/, "")
return "<h#{level} id=\"#{clean_title}\"><a href=\"##{clean_title}\">#{title}</a></h#{level}>"
end
end

View File

@@ -20,8 +20,8 @@ These templates dictate the full set of abstractions that you are allowed to use
to build your UI.
React approaches building user interfaces differently by breaking them into
**components**. This means React uses JavaScript to generate markup, which we
see as an advantage over templates for a few reasons:
**components**. This means React uses a real, full featured programming language
to render views, which we see as an advantage over templates for a few reasons:
- **JavaScript is a flexible, powerful programming language** with the ability
to build abstractions. This is incredibly important in large applications.

View File

@@ -23,7 +23,7 @@ The best part is the demo of how React reconciliation process makes live editing
## React Snippets
Over the past several weeks, members of our team, [Pete Hunt](http://www.petehunt.net/) and [Paul O'Shannessy](http://zpao.com/), answered many questions that were asked in the [React group](https://groups.google.com/forum/#!forum/reactjs). They give a good overview of how to integrate React with other libraries and APIs through the use of [Mixins](/react/docs/mixins.html) and [Lifecycle Methods](/react/docs/advanced-components.html).
Over the past several weeks, members of our team, [Pete Hunt](http://www.petehunt.net/) and [Paul O'Shannessy](http://zpao.com/), answered many questions that were asked in the [React group](https://groups.google.com/forum/#!forum/reactjs). They give a good overview of how to integrate React with other libraries and APIs through the use of [Mixins](/react/docs/reusable-components.html) and [Lifecycle Methods](/react/docs/working-with-the-browser.html).
> [Listening Scroll Event](https://groups.google.com/forum/#!topic/reactjs/l6PnP8qbofk)
>

View File

@@ -24,7 +24,7 @@ When you're ready, [go download it](/react/downloads.html)!
* Removed `React.autoBind`. [Read our blog post for details...](http://facebook.github.io/react/blog/2013/07/02/react-v0-4-autobind-by-default.html)
* Improvements to forms. We've written wrappers around `<input>`, `<textarea>`, `<option>`, and `<select>` in order to standardize many inconsistencies in browser implementations. This includes support for `defaultValue`, and improved implementation of the `onChange` event, and circuit completion. [Read the docs for details...](http://facebook.github.io/react/docs/forms.html)
* We've implemented an improved synthetic event system that conforms to the W3C spec.
* Updates to your component are batched now, which may result in a significantly faster re-render of components. `this.setState` now takes an optional callback as it's second parameter. If you were using `onClick={this.setState.bind(this, state)}` previously, you'll want to make sure you add a third parameter so that the event is not treated as the callback.
* Updates to your component are batched now, which may result in a significantly faster re-render of components. `this.setState` now takes an optional callback as its second parameter. If you were using `onClick={this.setState.bind(this, state)}` previously, you'll want to make sure you add a third parameter so that the event is not treated as the callback.
### JSX

View File

@@ -96,4 +96,4 @@ React.renderComponent(
> * [Working With the Browser](/react/docs/working-with-the-browser.html)
> * [More About Refs](/react/docs/more-about-refs.html)
> * [Tooling integration](/react/docs/tooling-integration.html)
> * [Reference](/react/docs/reference.html)
> * [Reference](/react/docs/top-level-api.html)

View File

@@ -0,0 +1,25 @@
---
title: "React v0.4.1"
layout: post
author: Paul O'Shannessy
---
React v0.4.1 is a small update, mostly containing correctness fixes. Some code has been restructured internally but those changes do not impact any of our public APIs.
## React
* `setState` callbacks are now executed in the scope of your component.
* `click` events now work on Mobile Safari.
* Prevent a potential error in event handling if `Object.prototype` is extended.
* Don't set DOM attributes to the string `"undefined"` on update when previously defined.
* Improved support for `<iframe>` attributes.
* Added checksums to detect and correct cases where server-side rendering markup mismatches what React expects client-side.
## JSXTransformer
* Improved environment detection so it can be run in a non-browser environment.
[Download it now!](/react/downloads.html)

View File

@@ -0,0 +1,54 @@
---
title: "Use React and JSX in Ruby on Rails"
layout: post
author: Paul O'Shannessy
---
Today we're releasing a gem to make it easier to use React and JSX in Ruby on Rails applications: [react-rails](https://github.com/facebook/react-rails).
This gem has 2 primary purposes:
1. To package `react.js` in a way that's easy to use and easy to update.
2. To allow you to write JSX without an external build step to transform that into JS.
## Packaging react.js
To make `react.js` available for use client-side, simply add `react` to your manifest, and declare the variant you'd like to use in your environment. When you use `:production`, the minified and optimized `react.min.js` will be used instead of the development version. For example:
```ruby
# config/environments/development.rb
MyApp::Application.configure do
config.react.variant = :development
# use :production in production.rb
end
```
```js
// app/assets/javascript/application.js
//= require react
```
## Writing JSX
When you name your file with `myfile.js.jsx`, `react-rails` will automatically try to transform that file. For the time being, we still require that you include the docblock at the beginning of the file. For example, this file will get transformed on request.
```js
/** @jsx React.DOM */
React.renderComponent(<MyComponent/>, document.body)
```
## Asset Pipeline
`react-rails` takes advantage of the [asset pipeline](http://guides.rubyonrails.org/asset_pipeline.html) that was introduced in Rails 3.1. A very important part of that pipeline is the `assets:precompile` Rake task. `react-rails` will ensure that your JSX files will be transformed into regular JS before all of your assets are minified and packaged.
## Installation
Installation follows the same process you're familiar with. You can install it globally with `gem install react-rails`, though we suggest you add the dependency to your `Gemfile` directly.

View File

@@ -0,0 +1,80 @@
---
title: "Community Round-up #6"
layout: post
author: Vjeux
---
This is the first Community Round-up where none of the items are from Facebook/Instagram employees. It's great to see the adoption of React growing.
## React Game Tutorial
[Caleb Cassel](https://twitter.com/CalebCassel) wrote a [step-by-step tutorial](https://rawgithub.com/calebcassel/react-demo/master/part1.html) about making a small game. It covers JSX, State and Events, Embedded Components and Integration with Backbone.
<figure>[![](/react/img/blog/dog-tutorial.png)](https://rawgithub.com/calebcassel/react-demo/master/part1.html)</figure>
## Reactify
[Andrey Popp](http://andreypopp.com/) created a [Browserify](http://browserify.org/) helper to compile JSX files.
> Browserify v2 transform for `text/jsx`. Basic usage is:
>
> ```
% browserify -t reactify main.jsx
```
>
> `reactify` transform activates for files with either `.jsx` extension or `/** @jsx React.DOM */` pragma as a first line for any `.js` file.
>
> [Check it out on Github...](https://github.com/andreypopp/reactify)
## React Integration with Este
[Daniel Steigerwald](http://daniel.steigerwald.cz/) is now using React within [Este](https://github.com/steida/este), which is a development stack for web apps in CoffeeScript that are statically typed using the Closure Library.
```coffeescript
este.demos.react.todoApp = este.react.create (`/** @lends {React.ReactComponent.prototype} */`)
render: ->
@div [
este.demos.react.todoList 'items': @state['items']
if @state['items'].length
@p "#{@state['items'].length} items."
@form 'onSubmit': @onFormSubmit, [
@input
'onChange': @onChange
'value': @state['text']
'autoFocus': true
'ref': 'textInput'
@button "Add ##{@state['items'].length + 1}"
]
]
```
[Check it out on Github...](https://github.com/steida/este-library/blob/master/este/demos/thirdparty/react/start.coffee)
## React Stylus Boilerplate
[Zaim Bakar](http://zaim.github.io/) shared his boilerplate to get started with Stylus CSS processor.
> This is my boilerplate React project using Grunt as the build tool, and Stylus as my CSS preprocessor.
>
> - Very minimal HTML boilerplate
> - Uses Stylus, with nib included
> - Uses two build targets:
> - `grunt build` to compile JSX and Stylus into a development build
> - `grunt dist` to minify and optimize the development build for production
>
> [Check it out on Github...](https://github.com/zaim/react-stylus-boilerplate)
## WebFUI
[Conrad Barski](http://lisperati.com/), author of the popular book [Land of Lisp](http://landoflisp.com/), wants to use React for his ClojureScript library called [WebFUI](https://github.com/drcode/webfui).
> I'm the author of "[Land of Lisp](http://landoflisp.com/)" and I love your framework. I built a somewhat similar framework a year ago [WebFUI](https://github.com/drcode/webfui) aimed at ClojureScript. My framework also uses global event delegates, a global "render" function, DOM reconciliation, etc just like react.js. (Of course these ideas all have been floating around the ether for ages, always great to see more people building on them.)
>
> Your implementation is more robust, and so I think the next point release of webfui will simply delegate all the "hard work" to react.js and will only focus on the areas where it adds value (enabling purely functional UI programming in clojurescript, and some other stuff related to streamlining event handling)
<figure>[![](/react/img/blog/landoflisp.png)](https://groups.google.com/forum/#!msg/reactjs/e3bYersyd64/qODfcuBR9LwJ)</figure>
>
> [Read the full post...](https://groups.google.com/forum/#!msg/reactjs/e3bYersyd64/qODfcuBR9LwJ)

View File

@@ -0,0 +1,56 @@
---
title: "Use React and JSX in Python Applications"
layout: post
author: Kunal Mehta
---
Today we're happy to announce the initial release of [PyReact](https://github.com/facebook/react-python), which makes it easier to use React and JSX in your Python applications. It's designed to provide an API to transform your JSX files into JavaScript, as well as provide access to the latest React source files.
## Usage
Transform your JSX files via the provided `jsx` module:
```python
from react import jsx
# For multiple paths, use the JSXTransformer class.
transformer = jsx.JSXTransformer()
for jsx_path, js_path in my_paths:
transformer.transform(jsx_path, js_path)
# For a single file, you can use a shortcut method.
jsx.transform('path/to/input/file.jsx', 'path/to/output/file.js')
```
For full paths to React files, use the `source` module:
```python
from react import source
# path_for raises IOError if the file doesn't exist.
react_js = source.path_for('react.min.js')
```
## Django
PyReact includes a JSX compiler for [django-pipeline](https://github.com/cyberdelia/django-pipeline). Add it to your project's pipeline settings like this:
```python
PIPELINE_COMPILERS = (
'react.utils.pipeline.JSXCompiler',
)
```
## Installation
PyReact is hosted on PyPI, and can be installed with `pip`:
$ pip install PyReact
Alternatively, add it into your `requirements` file:
PyReact==0.1.1
**Dependencies**: PyReact uses [PyExecJS](https://github.com/doloopwhile/PyExecJS) to execute the bundled React code, which requires that a JS runtime environment is installed on your machine. We don't explicitly set a dependency on a runtime environment; Mac OS X comes bundled with one. If you're on a different platform, we recommend [PyV8](https://code.google.com/p/pyv8/).
For the initial release, we've only tested on Python 2.7. Look out for support for Python 3 in the future, and if you see anything that can be improved, we welcome your [contributions](https://github.com/facebook/react-python/blob/master/CONTRIBUTING.md)!

View File

@@ -0,0 +1,74 @@
---
title: "Community Round-up #7"
layout: post
author: Vjeux
---
It's been three months since we open sourced React and it is going well. Some stats so far:
* 114 285 unique visitors on this website
* [1933 stars](https://github.com/facebook/react/stargazers) and [210 forks](https://github.com/facebook/react/network/members)
* [226 posts on Google Group](https://groups.google.com/forum/#!forum/reactjs)
* [76 Github projects using React](https://gist.github.com/vjeux/6335762)
* [30 contributors](https://github.com/facebook/react/graphs/contributors)
* [15 blog posts](http://facebook.github.io/react/blog/)
* 2 early adopters: [Khan Academy](http://benalpert.com/2013/06/09/using-react-to-speed-up-khan-academy.html) and [Propeller](http://usepropeller.com/blog/posts/from-backbone-to-react/)
## Wolfenstein Rendering Engine Ported to React
[Pete Hunt](http://www.petehunt.net/) ported the render code of the web version of Wolfenstein 3D to React. Check out [the demo](http://www.petehunt.net/wolfenstein3D-react/wolf3d.html) and [render.js](https://github.com/petehunt/wolfenstein3D-react/blob/master/js/renderer.js#L183) file for the implementation.
<figure>[![](/react/img/blog/wolfenstein_react.png)](http://www.petehunt.net/wolfenstein3D-react/wolf3d.html)</figure>
## React & Meteor
[Ben Newman](https://twitter.com/benjamn) made a [13-lines wrapper](https://github.com/benjamn/meteor-react/blob/master/lib/mixin.js) to use React and Meteor together. [Meteor](http://www.meteor.com/) handles the real-time data synchronization between client and server. React provides the declarative way to write the interface and only updates the parts of the UI that changed.
> This repository defines a Meteor package that automatically integrates the React rendering framework on both the client and the server, to complement or replace the default Handlebars templating system.
>
> The React core is officially agnostic about how you fetch and update your data, so it is far from obvious which approach is the best. This package provides one answer to that question (use Meteor!), and I hope you will find it a compelling combination.
>
>```javascript
>var MyComponent = React.createClass({
> mixins: [MeteorMixin],
>
> getMeteorState: function() {
> return { foo: Session.get('foo') };
> },
>
> render: function() {
> return <div>{this.state.foo}</div>;
> }
>});
>```
>
> Dependencies will be registered for any data accesses performed by getMeteorState so that the component can be automatically re-rendered whenever the data changes.
>
> [Read more ...](https://github.com/benjamn/meteor-react)
## React Page
[Jordan Walke](https://github.com/jordwalke) implemented a complete React project creator called [react-page](https://github.com/facebook/react-page/). It supports both server-side and client-side rendering, source transform and packaging JSX files using CommonJS modules, and instant reload.
> Easy Application Development with React JavaScript
> <figure>[![](/react/img/blog/react-page.png)](https://github.com/facebook/react-page/)</figure>
>
> **Why Server Rendering?**
>
> * Faster initial page speed:
> * Markup displayed before downloading large JavaScript.
> * Markup can be generated more quickly on a fast server than low power client devices.
> * Faster Development and Prototyping:
> * Instantly refresh your app without waiting for any watch scripts or bundlers.
> * Easy deployment of static content pages/blogs: just archive using recursive wget.
> * SEO benefits of indexability and perf.
>
> **How Does Server Rendering Work?**
>
> * `react-page` computes page markup on the server, sends it to the client so the user can see it quickly.
> * The corresponding JavaScript is then packaged and sent.
> * The browser runs that JavaScript, so that all of the event handlers, interactions and update code will run seamlessly on top of the server generated markup.
> * From the developer's (and the user's) perspective, it's just as if the rendering occurred on the client, only faster.
>
> [Try it out ...](https://github.com/facebook/react-page/)

View File

@@ -0,0 +1,70 @@
---
title: "Community Round-up #8"
layout: post
author: Vjeux
---
A lot has happened in the month since our last update. Here are some of the more interesting things we've found. But first, we have a couple updates before we share links.
First, we are organizing a [React Hackathon](http://reactjshack-a-thon.splashthat.com/) in Facebook's Seattle office on Saturday September 28. If you want to hack on React, meet some of the team or win some prizes, feel free to join us!
We've also reached a point where there are too many questions for us to handle directly. We're encouraging people to ask questions on [StackOverflow](http://stackoverflow.com/questions/tagged/reactjs) using the tag [[reactjs]](http://stackoverflow.com/questions/tagged/reactjs). Many members of the team and community have subscribed to the tag, so feel free to ask questions there. We think these will be more discoverable than Google Groups archives or IRC logs.
## Javascript Jabber
[Pete Hunt](http://www.petehunt.net/) and [Jordan Walke](https://github.com/jordwalke) were interviewed on [Javascript Jabber](http://javascriptjabber.com/073-jsj-react-with-pete-hunt-and-jordan-walke/) for an hour. They go over many aspects of React such as 60 FPS, Data binding, Performance, Diffing Algorithm, DOM Manipulation, Node.js support, server-side rendering, JSX, requestAnimationFrame and the community. This is a gold mine of information about React.
> **PETE:** So React was designed all around that. Conceptually, how you build a React app is that every time your data changes, it's like hitting the refresh button in a server-rendered app. What we do is we conceptually throw out all of the markup and event handlers that you've registered and we reset the whole page and then we redraw the entire page. If you're writing a server-rendered app, handling updates is really easy because you hit the refresh button and you're pretty much guaranteed to get what you expect.
>
> **MERRICK:** That's true. You don't get into these odd states.
>
> **PETE:** Exactly, exactly. In order to implement that, we communicate it as a fake DOM. What we'll do is rather than throw out the actual browser html and event handlers, we have an internal representation of what the page looks like and then we generate a brand new representation of what we want the page to look like. Then we perform this really, really fast diffing algorithm between those two page representations, DOM representations. Then React will compute the minimum set of DOM mutations it needs to make to bring the page up to date.
>
> Then to finally get to answer your question, that set of DOM mutations then goes into a queue and we can plug in arbitrary flushing strategies for that. For example, when we originally launched React in open source, every setState would immediately trigger a flush to the DOM. That wasn't part of the contract of setState, but that was just our strategy and it worked pretty well. Then this totally awesome open source contributor Ben Alpert at Khan Academy built a new batching strategy which would basically queue up every single DOM update and state change that happened within an event tick and would execute them in bulk at the end of the event tick.
>
> [Read the full conversation ...](http://javascriptjabber.com/073-jsj-react-with-pete-hunt-and-jordan-walke/)
## JSXTransformer Trick
While this is not going to work for all the attributes since they are camelCased in React, this is a pretty cool trick.
<div style="margin-left: 74px;"><blockquote class="twitter-tweet"><p>Turn any DOM element into a React.js function: JSXTransformer.transform(&quot;/** <a href="https://twitter.com/jsx">@jsx</a> React.DOM */&quot; + element.innerHTML).code</p>&mdash; Ross Allen (@ssorallen) <a href="https://twitter.com/ssorallen/statuses/377105575441489920">September 9, 2013</a></blockquote></div>
<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>
## Remarkable React
[Stoyan Stefanov](http://www.phpied.com/) gave a talk at [BrazilJS](http://braziljs.com.br/) about React and wrote an article with the content of the presentation. He goes through the difficulties of writting _active apps_ using the DOM API and shows how React handles it.
> So how does exactly React deal with it internally? Two crazy ideas - virtual DOM and synthetic events.
>
> You define you components in React. It builds a virtual DOM in JavaScript land which is way more efficient. Then it updates the DOM. (And "virtual DOM" is a very big name for what is simply a JavaScript object with nested key-value pairs)
>
> Data changes. React computes a diff (in JavaScript land, which is, of course, much more efficient) and updates the single table cell that needs to change. React replicates the state of the virtual DOM into the actual DOM only when and where it's necessary. And does it all at once, in most cases in a single tick of the `requestAnimationFrame()`.
>
> What about event handlers? They are synthetic. React uses event delegation to listen way at the top of the React tree. So removing a node in the virtual DOM has no effect on the event handling.
>
> The events are automatically cross-browser (they are React events). They are also much closer to W3C than any browser. That means that for example `e.target` works, no need to look for the event object or checking whether it's `e.target` or `e.srcElement` (IE). Bubbling and capturing phases also work cross browser. React also takes the liberty of making some small fixes, e.g. the event `<input onChange>` fires when you type, not when blur away from the input. And of course, event delegation is used as the most efficient way to handle events. You know that "thou shall use event delegation" is also commonly given advice for making web apps snappy.
>
> The good thing about the virtual DOM is that it's all in JavaScript land. You build all your UI in JavaScript. Which means it can be rendered on the server side, so you initial view is fast (and any SEO concerns are addressed). Also, if there are especially heavy operations they can be threaded into WebWorkers, which otherwise have no DOM access.
>
> [Read More ...](http://www.phpied.com/remarkable-react/)
## Markdown in React
[Ben Alpert](http://benalpert.com/) converted [marked](https://github.com/chjj/marked), a Markdown Javascript implementation, in React: [marked-react](https://github.com/spicyj/marked-react). Even without using JSX, the HTML generation is now a lot cleaner. It is also safer as forgetting a call to `escape` will not introduce an XSS vulnerability.
<figure>[![](/react/img/blog/markdown_refactor.png)](https://github.com/spicyj/marked-react/commit/cb70c9df6542c7c34ede9efe16f9b6580692a457)</figure>
## Unite from BugBusters
[Renault John Lecoultre](https://twitter.com/renajohn) wrote [Unite](https://www.bugbuster.com/), an interactive tool for analyzing code dynamically using React. It integrates with CodeMirror.
<figure>[![](/react/img/blog/unite.png)](https://unite.bugbuster.com/)</figure>
## #reactjs IRC Logs
[Vjeux](http://blog.vjeux.com/) re-implemented the display part of the IRC logger in React. Just 130 lines are needed for a performant infinite scroll with timestamps and color-coded author names.
<iframe width="100%" height="300" src="http://jsfiddle.net/vjeux/QL9tz/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>

View File

@@ -0,0 +1,52 @@
---
title: "React v0.5"
layout: post
author: Paul O'Shannessy
---
This release is the result of several months of hard work from members of the team and the community. While there are no groundbreaking changes in core, we've worked hard to improve performance and memory usage. We've also worked hard to make sure we are being consistent in our usage of DOM properties.
The biggest change you'll notice as a developer is that we no longer support `class` in JSX as a way to provide CSS classes. Since this prop was being converted to `className` at the transform step, it caused some confusion when trying to access it in composite components. As a result we decided to make our DOM properties mirror their counterparts in the JS DOM API. There are [a few exceptions](https://github.com/facebook/react/blob/master/src/dom/DefaultDOMPropertyConfig.js#L156) where we deviate slightly in an attempt to be consistent internally.
The other major change in v0.5 is that we've added an additional build - `react-with-addons` - which adds support for some extras that we've been working on including animations and two-way binding. [Read more about these addons in the docs](/react/docs/addons.html).
## Thanks to Our Community
We added *22 new people* to the list of authors since we launched React v0.4.1 nearly 3 months ago. With a total of 48 names in our `AUTHORS` file, that means we've nearly doubled the number of contributors in that time period. We've seen the number of people contributing to discussion on IRC, mailing lists, Stack Overflow, and GitHub continue rising. We've also had people tell us about talks they've given in their local community about React.
It's been awesome to see the things that people are building with React, and we can't wait to see what you come up with next!
## Changelog
### React
* Memory usage improvements - reduced allocations in core which will help with GC pauses
* Performance improvements - in addition to speeding things up, we made some tweaks to stay out of slow path code in V8 and Nitro.
* Standardized prop -> DOM attribute process. This previously resulting in additional type checking and overhead as well as confusing cases for users. Now we will always convert your value to a string before inserting it into the DOM.
* Support for Selection events.
* Support for [Composition events](https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent).
* Support for additional DOM properties (`charSet`, `content`, `form`, `httpEquiv`, `rowSpan`, `autoCapitalize`).
* Support for additional SVG properties (`rx`, `ry`).
* Support for using `getInitialState` and `getDefaultProps` in mixins.
* Support mounting into iframes.
* Bug fixes for controlled form components.
* Bug fixes for SVG element creation.
* Added `React.version`.
* Added `React.isValidClass` - Used to determine if a value is a valid component constructor.
* Removed `React.autoBind` - This was deprecated in v0.4 and now properly removed.
* Renamed `React.unmountAndReleaseReactRootNode` to `React.unmountComponentAtNode`.
* Began laying down work for refined performance analysis.
* Better support for server-side rendering - [react-page](https://github.com/facebook/react-page) has helped improve the stability for server-side rendering.
* Made it possible to use React in environments enforcing a strict [Content Security Policy](https://developer.mozilla.org/en-US/docs/Security/CSP/Introducing_Content_Security_Policy). This also makes it possible to use React to build Chrome extensions.
### React with Addons (New!)
* Introduced a separate build with several "addons" which we think can help improve the React experience. We plan to deprecate this in the long-term, instead shipping each as standalone pieces. [Read more in the docs](/react/docs/addons.html).
### JSX
* No longer transform `class` to `className` as part of the transform! This is a breaking change - if you were using `class`, you *must* change this to `className` or your components will be visually broken.
* Added warnings to the in-browser transformer to make it clear it is not intended for production use.
* Improved compatibility for Windows
* Improved support for maintaining line numbers when transforming.

View File

@@ -0,0 +1,100 @@
---
title: "Community Round-up #9"
layout: post
author: Vjeux
---
We organized a React hackathon last week-end in the Facebook Seattle office. 50 people, grouped into 15 teams, came to hack for a day on React. It was a lot of fun and we'll probably organize more in the future.
![](/react/img/blog/react-hackathon.jpg)
## React Hackathon Winner
[Alex Swan](http://bold-it.com/) implemented [Qu.izti.me](http://qu.izti.me/), a multi-player quiz game. It is real-time via Web Socket and mobile friendly.
> The game itself is pretty simple. People join the "room" by going to [http://qu.izti.me](http://qu.izti.me/) on their device. Large displays will show a leaderboard along with the game, and small displays (such as phones) will act as personal gamepads. Users will see questions and a choice of answers. The faster you answer, the more points you earn.
>
> In my opinion, Socket.io and React go together like chocolate and peanut butter. The page was always an accurate representation of the game object.
><figure>[![](/react/img/blog/quiztime.png)](http://bold-it.com/javascript/facebook-react-example/)</figure>
>
> [Read More...](http://bold-it.com/javascript/facebook-react-example/)
## JSConf EU Talk: Rethinking Best Practices
[Pete Hunt](http://www.petehunt.net/) presented React at JSConf EU. He covers three controversial design decisions of React:
1. Build **components**, not templates
2. Re-render the whole app on every update
3. Virtual DOM
The video will be available soon on the [JSConf EU website](http://2013.jsconf.eu/speakers/pete-hunt-react-rethinking-best-practices.html), but in the meantime, here are Pete's slides:
<figure><iframe src="http://www.slideshare.net/slideshow/embed_code/26589373" width="550" height="450" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" allowfullscreen></iframe></figure>
## Pump - Clojure bindings for React
[Alexander Solovyov](http://solovyov.net/) has been working on React bindings for ClojureScript. This is really exciting as it is using "native" ClojureScript data structures.
```ruby
(ns your.app
(:require-macros [pump.def-macros :refer [defr]])
(:require [pump.core]))
(defr Component
:get-initial-state #(identity {:some-value ""})
[component props state]
[:div {:class-name "test"} "hello"])
```
[Check it out on GitHub...](https://github.com/piranha/pump)
## JSXHint
[Todd Kennedy](http://blog.selfassembled.org/) working at [Cond&eacute; Nast](http://www.condenast.com/) implemented a wrapper on-top of [JSHint](http://www.jshint.com/) that first converts JSX files to JS.
> A wrapper around JSHint to allow linting of files containg JSX syntax. Accepts glob patterns. Respects your local .jshintrc file and .gitignore to filter your glob patterns.
>
> ```
npm install -g jsxhint
```
>
> [Check it out on GitHub...](https://github.com/CondeNast/JSXHint)
## Turbo React
[Ross Allen](https://twitter.com/ssorallen) working at [Mesosphere](http://mesosphere.io/) combined [Turbolinks](https://github.com/rails/turbolinks/), a library used by Ruby on Rails to speed up page transition, and React.
> "Re-request this page" is just a link to the current page. When you click it, Turbolinks intercepts the GET request and fetchs the full page via XHR.
>
> The panel is rendered with a random panel- class on each request, and the progress bar gets a random widthX class.
>
> With Turbolinks alone, the entire <body> would be replaced, and transitions would not happen. In this little demo though, React adds and removes classes and text, and the attribute changes are animated with CSS transitions. The DOM is otherwise left intact.
><figure>[![](/react/img/blog/turboreact.png)](https://turbo-react.herokuapp.com/)</figure>
>
> [Check out the demo...](https://turbo-react.herokuapp.com/)
## Reactive Table
[Stoyan Stefanov](http://www.phpied.com/) continues his series of blog posts about React. This one is an introduction tutorial on rendering a simple table with React.
> React is all about components. So let's build one.
>
> Let's call it Table (to avoid any confusion what the component is about).
>
> ```javascript
var Table = React.createClass({
/*stuff goeth here*/
});
```
>
> You see that React components are defined using a regular JS object. Some properties and methods of the object such as render() have special meanings, the rest is upforgrabs.
>
> [Read the full article...](http://www.phpied.com/reactive-table/)

15
docs/blog/all.html Normal file
View File

@@ -0,0 +1,15 @@
---
title: Blog
layout: default
sectionid: blog
id: all-posts
---
<section class="content wrap documentationContent nosidebar">
<div class="inner-content">
<h1>All Posts</h1>
{% for page in site.posts %}
<p><strong><a href="/react{{ page.url }}">{{ page.title }}</a></strong> on {{ page.date | date: "%B %e, %Y" }} by {{ page.author }}</p>
{% endfor %}
</div>
</section>

View File

@@ -7,22 +7,28 @@ sectionid: blog
<section class="content wrap blogContent">
{% include nav_blog.html %}
<div class="inner-content">
{% for page in site.posts %}
{% for page in paginator.posts %}
<div class="post-list-item">
<h1><a href="/react{{ page.url }}">{{ page.title }}</a></h1>
<p class="meta">{{ page.date | date: "%B %e, %Y" }} by {{ page.author }}</p>
<hr>
<hr />
<div class="post">
{{ page.excerpt }}
{% if page.excerpt != page.content %}
<p>
<a href="/react{{ page.url }}">Continue Reading &rarr;</a>
</p>
{% endif %}
{{ page.content }}
</div>
</div>
{% endfor %}
<div class="pagination">
{% if paginator.previous_page %}
<a href="/react/blog/{{ paginator.previous_page_path }}" class="previous">
&laquo; Previous Page
</a>
{% endif %}
{% if paginator.next_page %}
<a href="/react/blog/{{ paginator.next_page_path }}" class="next">
Next Page &raquo;
</a>
{% endif %}
</div>
</div>
</section>

View File

@@ -82,7 +82,7 @@ var div = React.DOM.div;
var app = <div className="appClass">Hello, React!</div>;
```
### React Component Components
### React Composite Components
To construct an instance of a composite component, create a variable that
references the class.
@@ -92,7 +92,7 @@ var MyComponent = React.createClass({/*...*/});
var app = <MyComponent someProperty={true} />;
```
See [Component Basics](component-basics.html) to learn more about components.
See [Multiple Components](multiple-components.html) to learn more about using composite components.
> Note:
>
@@ -162,10 +162,15 @@ var content = <Container>{/* this is a comment */}<Nav /></Container>;
Beyond the compilation step, JSX does not require any special tools.
* Many editors already include reasonable support for JSX (Vim, Emacs js2-mode).
* JSX syntax highlighting is available for Sublime Text and other editors
that support `*.tmLanguage` using the third-party
[`JavaScript (JSX).tmLanguage`][1].
* Linting provides accurate line numbers after compiling without sourcemaps.
* Elements use standard scoping so linters can find usage of out-of-scope
components.
[1]: https://github.com/yungsters/sublime/blob/master/tmLanguage/JavaScript%20(JSX).tmLanguage
## Prior Work
JSX is similar to several other JavaScript embedded XML language

View File

@@ -9,6 +9,9 @@ next: interactivity-and-dynamic-uis.html
JSX looks like HTML but there are some important differences you may run into.
> Note:
>
> For DOM differences, such as the inline `style` attribute, check [here](dom-differences.html).
## Whitespace Removal

View File

@@ -144,7 +144,7 @@ In React, data flows from owner to owned component through `props` as discussed
You may be thinking that it's expensive to react to changing data if there are a large number of nodes under an owner. The good news is that JavaScript is fast and `render()` methods tend to be quite simple, so in most applications this is extremely fast. Additionally, the bottleneck is almost always the DOM mutation and not JS execution and React will optimize this for you using batching and change detection.
However, sometimes you really want to have fine-grained control over your performance. In that case, simply override `shouldComponentUpdate()` to return false when you want React to skip processing of a subtree. See [the React reference docs](./reference.html) for more information.
However, sometimes you really want to have fine-grained control over your performance. In that case, simply override `shouldComponentUpdate()` to return false when you want React to skip processing of a subtree. See [the React reference docs](component-specs.html) for more information.
> Note:
>

View File

@@ -119,14 +119,16 @@ In addition to that philosophy, we've also taken the stance that we, as authors
### Polyfills Needed to Support Older Browsers
These six functions can be polyfilled using `es5-shim.js` from [kriskowal's es5-shim](https://github.com/kriskowal/es5-shim):
* `Array.isArray`
* `Array.prototype.forEach`
* `Array.prototype.indexOf`
* `Function.prototype.bind`
* `Array.prototype.some`
* `Date.now`
* `Array.prototype.some` (also in `es5-shim.js`)
* `Function.prototype.bind`
All of these can be polyfilled using `es5-shim.js` from [https://github.com/kriskowal/es5-shim](https://github.com/kriskowal/es5-shim).
Other required polyfills:
* `console.*` - Only needed when not using the minified build. If you need to polyfill this, try [https://github.com/paulmillr/console-polyfill](https://github.com/paulmillr/console-polyfill).
* `Object.create` - Provided in `es5-sham.js` @ [https://github.com/kriskowal/es5-shim](https://github.com/kriskowal/es5-shim).
* `Object.create` Provided by `es5-sham.js` from [kriskowal's es5-shim](https://github.com/kriskowal/es5-shim).
* `console.*` Only needed when using the unminified build. If you need to polyfill this, try [paulmillr's console-polyfill](https://github.com/paulmillr/console-polyfill).

View File

@@ -39,7 +39,7 @@ Consider the case when you wish to tell an `<input />` element (that exists with
```
Notice how, in this example, we want to "tell" the input something - something that it cannot infer from it's props over time. In this case we want to "tell" it that it should now become focused. However, there are some challenges. What is returned from `render()`` is not your actual composition of "child" components, it is merely a *description* of the children at a particular instance in time - a snapshot, if you will.
Notice how, in this example, we want to "tell" the input something - something that it cannot infer from its props over time. In this case we want to "tell" it that it should now become focused. However, there are some challenges. What is returned from `render()` is not your actual composition of "child" components, it is merely a *description* of the children at a particular instance in time - a snapshot, if you will.
> Note:
>

View File

@@ -1,26 +1,28 @@
---
id: tooling-integration
title: Tooling integration
title: Tooling Integration
layout: docs
permalink: tooling-integration.html
prev: more-about-refs.html
next: reference.html
next: addons.html
---
Every project uses a different system for building and deploying JavaScript. We've tried to make React as environment-agnostic as possible.
## React
## CDN-hosted React
### CDN-hosted React
We provide CDN-hosted versions of React [on our download page](/react/downloads.html). These prebuilt files use the UMD module format. Dropping them in with a simple `<script>` tag will inject a `React` global into your environment. It should also work out-of-the-box in CommonJS and AMD environments.
## Using master
### Using master
We have instructions for building from `master` [in our GitHub repository](https://github.com/facebook/react). We build a tree of CommonJS modules under `build/modules` which you can drop into any environment or packaging tool that supports CommonJS.
## JSX
## In-browser JSX Transform
### In-browser JSX Transform
If you like using JSX, we provide an in-browser JSX transformer for development [on our download page](/react/downloads.html). Simply include a `<script type="text/jsx">` tag to engage the JSX transformer. Be sure to include the `/** @jsx React.DOM */` comment as well, otherwise the transformer will not run the transforms.
@@ -29,16 +31,22 @@ If you like using JSX, we provide an in-browser JSX transformer for development
> The in-browser JSX transformer is fairly large and results in extraneous computation client-side that can be avoided. Do not use it in production — see the next section.
## Productionizing: Precompiled JSX
### Productionizing: Precompiled JSX
If you have [npm](http://npmjs.org/), you can simply run `npm install -g react-tools` to install our command-line `jsx` tool. This tool will translate files that use JSX syntax to plain JavaScript files that can run directly in the browser. It will also watch directories for you and automatically transform files when they are changed; for example: `jsx --watch src/ build/`. Run `jsx --help` for more information on how to use this tool.
## Helpful Open-Source Projects
### Helpful Open-Source Projects
The open-source community has built tools that integrate JSX with several build systems.
* [reactify](https://github.com/andreypopp/reactify) - use JSX with [browserify](http://browserify.org/).
* [reactify](https://github.com/andreypopp/reactify) - use JSX with [browserify](http://browserify.org/)
* [grunt-react](https://github.com/ericclemmons/grunt-react) - [grunt](http://gruntjs.com/) task for JSX
* [require-jsx](https://github.com/seiffert/require-jsx) - use JSX with [require.js](http://requirejs.org/)
* [reactapp](https://github.com/jordwalke/reactapp) - a sample project to get up-and-running with React quickly
* [pyReact](https://github.com/facebook/react-python) - use JSX with [Python](http://www.python.org/)
* [react-rails](https://github.com/facebook/react-rails) - use JSX with [Ruby on Rails](http://rubyonrails.org/)
## React Page
To get started on a new project, you can use [react-page](https://github.com/facebook/react-page/), a complete React project creator. It supports both server-side and client-side rendering, source transform and packaging JSX files using CommonJS modules, and instant reload.

210
docs/docs/09-addons.md Normal file
View File

@@ -0,0 +1,210 @@
---
id: addons
title: Add-ons
layout: docs
permalink: addons.html
prev: tooling-integration.html
next: examples.html
---
`React.addons` is where we park some useful utilities for building React apps. **These should be considered experimental** but will eventually be rolled into core or a blessed utilities library.
## CSS Animation and Transitions
`ReactTransitions` is an easy way to perform CSS transitions and animations when a React component enters or leaves the DOM. `ReactTransitions` is inspired by the excellent [ng-animate](http://www.nganimate.org/) library.
### Getting Started
`ReactTransitionGroup` is the interface to `ReactTransitions`. This is a simple element that wraps all of the components you are interested in animating. Here's an example where we fade list items in and out.
```javascript{22-24}
/** @jsx React.DOM */
var ReactTransitionGroup = React.addons.TransitionGroup;
var TodoList = React.createClass({
getInitialState: function() {
return {items: ['hello', 'world', 'click', 'me']};
},
handleAdd: function() {
var newItems =
this.state.items.concat([prompt('Enter some text')]);
this.setState({items: newItems});
},
handleRemove: function(i) {
var newItems = this.state.items;
newItems.splice(i, 1)
this.setState({items: newItems});
},
render: function() {
var items = this.state.items.map(function(item, i) {
return (
<div key={i} onClick={this.handleRemove.bind(this, i)}>
{item}
</div>
);
}.bind(this));
return (
<div>
<div><button onClick={this.handleAdd} /></div>
<ReactTransitionGroup transitionName="example">
{items}
</ReactTransitionGroup>
</div>
);
}
});
```
In this component, when a new item is added `ReactTransitionGroup` it will get the `example-enter` CSS class and the `example-enter-active` CSS class added in the next tick. This is a convention based on the `transitionName` prop.
You can use these classes to trigger a CSS animation or transition. For example, try adding this CSS and adding a new list item:
```css
.example-enter {
opacity: 0.01;
transition: opacity .5s ease-in;
}
.example-enter.example-enter-active {
opacity: 0.99;
}
```
You'll notice that when you try to remove an item `ReactTransitionGroup` keeps it in the DOM. If you're using an unminified build of React you'll see a warning that React was expecting an animation or transition to occur. That's because `ReactTransitionGroup` keeps your DOM elements on the page until the animation completes. Try adding this CSS:
```css
.example-leave {
opacity: 0.99;
transition: opacity .5s ease-in;
}
.example-leave.example-leave-active {
opacity: 0.01;
}
```
### Disabling Animations
You can disable animating `enter` or `leave` animations if you want. For example, sometimes you may want an `enter` animation and no `leave` animation, but `ReactTransitionGroup` waits for an animation to complete before removing your DOM node. You can add `transitionEnter={false}` or `transitionLeave={false}` props to `ReactTransitionGroup` to disable these animations.
### Rendering a Different Component
By default `ReactTransitionGroup` renders as a `span`. You can change this behavior by providing a `component` prop. For example, here's how you would render a `<ul>`:
```javascript{3}
<ReactTransitionGroup
transitionName="example"
component={React.DOM.ul}>
...
</ReactTransitionGroup>
```
`component` does not need to be a DOM component. It can be any component you want; even one you've written yourself!
## ReactLink
`ReactLink` is an easy way to express two-way binding with React.
In React, data flows one way: from owner to child. This is because data only flows one direction in [the Von Neumann model of computing](http://en.wikipedia.org/wiki/Von_Neumann_architecture). You can think of it as "one-way data binding."
However, there are lots of applications that require you to read some data and flow it back into your program. For example, when developing forms, you'll often want to update some React `state` when you receive user input. Or perhaps you want to perform layout in JavaScript and react to changes in some DOM element size.
In React, you would implement this by listening to a "change" event, read from your data source (usually the DOM) and call `setState()` on one of your components. "Closing the data flow loop" explicitly leads to more understandable and easier-to-maintain programs. See [our forms documentation](./forms.html) for more information.
Two-way binding -- implicitly enforcing that some value in the DOM is always consistent with some React `state` -- is concise and supports a wide variety of applications. We've provided `ReactLink`: syntactic sugar for setting up the common data flow loop pattern described above, or "linking" some data source to React `state`.
> Note:
>
> ReactLink is just a thin wrapper and convention around the `onChange`/`setState()` pattern. It doesn't fundamentally change how data flows in your React application.
### ReactLink: Before and After
Here's a simple form example without using `ReactLink`:
```javascript
/** @jsx React.DOM */
var NoLink = React.createClass({
getInitialState: function() {
return {value: 'Hello!'};
},
handleChange: function(event) {
this.setState({value: event.target.value});
},
render: function() {
var value = this.state.value;
return <input type="text" value={value} onChange={this.handleChange} />;
}
});
```
This works really well and it's very clear how data is flowing, however with a lot of form fields it could get a bit verbose. Let's use `ReactLink` to save us some typing:
```javascript{4,9}
/** @jsx React.DOM */
var WithLink = React.createClass({
mixins: [React.addons.LinkedStateMixin],
getInitialState: function() {
return {value: 'Hello!'};
},
render: function() {
return <input type="text" valueLink={this.linkState('value')} />;
}
});
```
`LinkedStateMixin` adds a method ot your React component called `linkState()`. `linkState()` returns a `ReactLink` object which contains the current value of the React state and a callback to change it.
`ReactLink` objects can be passed up and down the tree as props, so it's easy (and explicit) to set up two-way binding between a component deep in the hierarchy and state that lives higher in the hierarchy.
### Under the Hood
There are two sides to `ReactLink`: the place where you create the `ReactLink` instance and the place where you use it. To prove how simple `ReactLink` is, let's rewrite each side separately to be more explicit.
#### ReactLink Without LinkedStateMixin
```javascript{7-9,11-14}
/** @jsx React.DOM */
var WithoutMixin = React.createClass({
getInitialState: function() {
return {value: 'Hello!'};
},
handleChange: function(newValue) {
this.setState({value: newValue});
},
render: function() {
var valueLink = {
value: this.state.value,
requestChange: this.handleChange
};
return <input type="text" valueLink={valueLink} />;
}
});
```
As you can see, `ReactLink` objects are very simple objects that just have a `value` and `requestChange` prop. And `LinkedStateMixin` is similarly simple: it just populates those fields with a value from `this.state` and a callback that calls `this.setState()`.
#### ReactLink Without valueLink
```javascript
/** @jsx React.DOM */
var WithoutLink = React.createClass({
mixins: [React.addons.LinkedStateMixin],
getInitialState: function() {
return {value: 'Hello!'};
},
render: function() {
var valueLink = this.linkState('value');
var handleChange = function(e) {
valueLink.requestChange(e.target.value);
};
return <input type="text" value={valueLink.value} onChange={handleChange} />;
}
});
```
The `valueLink` prop is also quite simple. It simply handles the `onChange` event and calls `this.props.valueLink.requestChange()` and also uses `this.props.valueLink.value` instead of `this.props.value`. That's it!

View File

@@ -1,209 +0,0 @@
---
id: reference
title: Reference
layout: docs
permalink: reference.html
prev: tooling-integration.html
---
## Examples
### Production Apps
* All of [Instagram.com](http://instagram.com/) is built on React.
* Many components on [Facebook.com](http://www.facebook.com/), including the commenting interface, ads creation flows, and page insights.
* [Khan Academy](http://khanacademy.org/) is using React for its question editor.
### Sample Code
* We've included [a step-by-step comment box tutorial](./tutorial.html).
* [The React starter kit](/react/downloads.html) includes several examples which you can [view online in our GitHub repository](https://github.com/facebook/react/tree/master/examples/).
* [reactapp](https://github.com/jordwalke/reactapp) is a simple app template to get you up-and-running quickly with React.
* [React one-hour email](https://github.com/petehunt/react-one-hour-email/commits/master) goes step-by-step from a static HTML mock to an interactive email reader (written in just one hour!)
* [Rendr + React app template](https://github.com/petehunt/rendr-react-template/) demonstrates how to use React's server rendering capabilities.
## API
### React
`React` is the entry point to the React framework. If you're using one of the prebuilt packages it's available as a global; if you're using CommonJS modules you can `require()` it.
#### React.DOM
`React.DOM` provides all of the standard HTML tags needed to build a React app. You generally don't use it directly; instead, just include it as part of the `/** @jsx React.DOM */` docblock.
#### React.initializeTouchEvents
```javascript
initializeTouchEvents(boolean shouldUseTouch)
```
Configure React's event system to handle touch events on mobile devices.
#### React.createClass
```javascript
function createClass(object specification)
```
Creates a component given a specification. A component implements a `render` method which returns **one single** child. That child may have an arbitrarily deep child structure. One thing that makes components different than standard prototypal classes is that you don't need to call new on them. They are convenience wrappers that construct backing instances (via new) for you.
#### React.renderComponent
```javascript
ReactComponent renderComponent(ReactComponent container, DOMElement container)
```
Renders a React component into the DOM in the supplied `container`.
If the React component was previously rendered into `container`, this will perform an update on it and only mutate the DOM as necessary to reflect the latest React component.
#### React.unmountAndReleaseReactRootNode
```javascript
unmountAndReleaseReactRootNode(DOMElement container)
```
Remove a mounted React component from the DOM and clean up its event handlers and state.
#### React.renderComponentToString
```javascript
renderComponentToString(ReactComponent component, function callback)
```
Render a component to its initial HTML. This should only be used on the server. React will call `callback` with an HTML string when the markup is ready. You can use this method to create static site generators, or you can generate HTML on the server and send it down to have a very fast initial page load. If you call `React.renderComponent()` on a node that already has this server-rendered markup, React will preserve it and only attach event handlers, allowing you to have a very performant first-load experience.
### AbstractEvent
Your event handlers will be passed instances of `AbstractEvent`, a cross-browser wrapper around the browser's native event. It has the same interface as the browser's native event (such as `stopPropagation()` and `preventDefault()`) except they work exactly the same across all browsers.
If you find that you need the underlying browser event for some reason, simply use the `nativeEvent` attribute to get it.
### ReactComponent
Component classses created by `createClass()` return instances of `ReactComponent` when called. Most of the time when you're using React you're either creating or consuming `ReactComponent`s.
#### getDOMNode
```javascript
DOMElement getDOMNode()
```
If this component has been mounted into the DOM, this returns the corresponding native browser DOM element. This method is useful for reading values out of the DOM, such as form field values and performing DOM measurements.
#### setProps
```javascript
setProps(object nextProps)
```
When you're integrating with an external JavaScript application you may want to signal a change to a React component rendered with `renderComponent()`. Simply call `setProps()` to change its properties and trigger a re-render.
> Note:
>
> This method can only be called on a root-level component. That is, it's only available on the component passed directly to `renderComponent()` and none of its children. If you're inclined to use `setProps()` on a child component, instead take advantage of reactive updates and pass the new prop to the child component when it's created in `render()`.
#### replaceProps
```javascript
replaceProps(object nextProps)
```
Like `setProps()` but deletes any pre-existing props that are not in nextProps.
#### transferPropsTo
```javascript
ReactComponent transferPropsTo(ReactComponent targetComponent)
```
Transfer properties from this component to a target component that have not already been set on the target component. This is usually used to pass down properties to the returned root component. `targetComponent`, now updated with some new props is returned as a convenience.
#### setState
```javascript
setState(object nextState[, function callback])
```
Merges nextState with the current state. This is the primary method you use to trigger UI updates from event handlers and server request callbacks. In addition, you can supply an optional callback function that is executed once `setState` is completed.
> Note:
>
> *NEVER* mutate `this.state` directly. As calling `setState()` afterwards may replace the mutation you made. Treat `this.state` as if it were immutable.
> Note:
>
> `setState()` does not immediately mutate `this.state` but creates a pending state transition. Accessing `this.state` after calling this method can potentially return the existing value.
> Note:
>
> There is no guarantee of synchronous operation of calls to `setState` and calls may be batched for performance gains.
#### replaceState
```javascript
replaceState(object nextState[, function callback])
```
Like `setState()` but deletes any pre-existing state keys that are not in nextState.
#### forceUpdate()
```javascript
forceUpdate([function callback])
```
If your `render()` method reads from something other than `this.props` or `this.state` you'll need to tell React when it needs to re-run `render()`. Use `forceUpdate()` to cause React to automatically re-render. This will cause `render()` to be called on the component and all of its children but React will only update the DOM if the markup changes.
Normally you should try to avoid all uses of `forceUpdate()` and only read from `this.props` and `this.state` in `render()`. This makes your application much simpler and more efficient.
> Note:
>
> There is no guarantee of synchronous operation of calls to `forceUpdate` and calls may be batched for performance gains.
#### Lifecycle methods
```javascript
object getInitialState()
componentWillMount()
componentDidMount(DOMElement domNode)
componentWillReceiveProps(object nextProps)
boolean shouldComponentUpdate(object nextProps, object nextState)
componentWillUpdate(object nextProps, object nextState)
ReactComponent render()
componentDidUpdate(object prevProps, object prevState, DOMElement domNode)
componentWillUnmount()
```
See the [working with the browser](./working-with-the-browser.html) documentation for more details on these lifecycle methods.
## DOM Differences
React has implemented a browser-independent events and DOM system for performance and cross-browser compatibility reasons. We took the opportunity to clean up a few rough edges in browser DOM implementations.
* All events (including submit) bubble correctly per the W3C spec
* All event objects conform to the W3C spec
* All DOM properties and attributes (including event handlers) should be camelCased to be consistent with standard JavaScript style. We intentionally break with the spec here, since the spec is inconsistent.
* The `style` attribute accepts a JavaScript object with camelCased properties rather than a CSS string. This is consistent with the DOM `style` JavaScript property, is more efficient, and prevents XSS security holes.
* `onChange` behaves as you would expect it to: whenever a form field is changed this event is fired rather than inconsistently on blur. We intentionally break from existing browser behavior because `onChange` is a misnomer for its behavior and React relies on this event to react to user input in real time.

22
docs/docs/10-examples.md Normal file
View File

@@ -0,0 +1,22 @@
---
id: examples
title: Examples
layout: docs
permalink: examples.html
prev: addons.html
---
### Production Apps
* All of [Instagram.com](http://instagram.com/) is built on React.
* Many components on [Facebook.com](http://www.facebook.com/), including the commenting interface, ads creation flows, and page insights.
* [Khan Academy](http://khanacademy.org/) is using React for most new JS development.
### Sample Code
* We've included [a step-by-step comment box tutorial](./tutorial.html).
* [The React starter kit](/react/downloads.html) includes several examples which you can [view online in our GitHub repository](https://github.com/facebook/react/tree/master/examples/).
* [React Page](https://github.com/facebook/react-page) is a simple React project creator to get you up-and-running quickly with React. It supports both server-side and client-side rendering, source transform and packaging JSX files using CommonJS modules, and instant reload.
* [React one-hour email](https://github.com/petehunt/react-one-hour-email/commits/master) goes step-by-step from a static HTML mock to an interactive email reader (written in just one hour!)
* [Rendr + React app template](https://github.com/petehunt/rendr-react-template/) demonstrates how to use React's server rendering capabilities.

View File

@@ -1,96 +0,0 @@
---
id: OUTLINE
title: Goals of the documentation
layout: docs
prev: 09.1-tutorial.html
---
- Flow of docs should mimic progression of questions a new user would ask
- High information density -- assume the reader is adept at JS
- Talk about best practices
- JSFiddles for all code samples
- Provide background for some of the design decisions
- Less words less words less words!
## Outline
Motivation / Why React?
- Declarative (simple)
- Components (separation of concerns)
- Give it 5 minutes
Displaying data
- Hello world example
- Reactive updates
- Components are just functions
- JSX syntax (link to separate doc?)
- JSX gotchas
Interactivity and dynamic UIs
- Click handler example
- Event handlers / synthetic events (link to w3c docs)
- Under the hood: autoBind and event delegation (IE8 notes)
- React is a state machine
- How state works
- What components should have state?
- What should go in state?
- What shouldn't go in state?
Scaling up: using multiple components
- Motivation: separate concerns
- Composition example
- Ownership (and owner vs. parent)
- Children
- Data flow (one-way data binding)
- A note on performance
Building effective reusable components
- You should build a reusable component library (CSS, testing etc)
- Prop validation
- Transferring props: a shortcut
- Mixins
- Testing
Forms
Working with the browser
- The mock DOM
- Refs / getDOMNode()
- More about refs
- Component lifecycle
- Browser support and polyfills
Working with your environment
- CDN-hosted React
- Using master
- In-browser JSX transform
- Productionizing: precompiled JSX
- Helpful open-source projects
Integrating with other UI libraries
- Using jQuery plugins
- Letting jQuery manage React components
- Using with Backbone.View
- CoffeeScript
- Moving from Handlebars to React: an example
Server / static rendering
- Motivation
- Simple example
- How does it work? (No DOM)
- Rendr + React
Big ideas
- Animation
- Bootstrap bindings (responsive grids)
- Reactive CSS
- Web workers
- Native views
Case studies
- Comment box tutorial from scratch
- From HTML mock to application: React one-hour email
- Jordan's LikeToggler example
Reference
- API
- DOM differences

View File

@@ -44,7 +44,7 @@ In the root directory of the starter kit, create a `helloworld.html` with the fo
</html>
```
The XML syntax inside of JavaScript is called JSX; check out the [JSX syntax](syntax.html) to learn more about it. In order to translate it to vanilla JavaScript we use `<script type="text/jsx">` and include `JSXTransformer.js` to actually perform the transformation in the browser.
The XML syntax inside of JavaScript is called JSX; check out the [JSX syntax](jsx-in-depth.html) to learn more about it. In order to translate it to vanilla JavaScript we use `<script type="text/jsx">` and include `JSXTransformer.js` to actually perform the transformation in the browser.
### Separate File
@@ -84,7 +84,7 @@ The file `build/helloworld.js` is autogenerated whenever you make a change.
/** @jsx React.DOM */
React.renderComponent(
React.DOM.h1(null, 'Hello, world!'),
document.getElementyById('example')
document.getElementById('example')
);
```

4
docs/docs/index.html Normal file
View File

@@ -0,0 +1,4 @@
---
layout: redirect
destination: getting-started.html
---

View File

@@ -0,0 +1,77 @@
---
id: top-level-api
title: Top-Level API
layout: docs
permalink: top-level-api.html
next: component-api.html
---
## React
`React` is the entry point to the React framework. If you're using one of the prebuilt packages it's available as a global; if you're using CommonJS modules you can `require()` it.
### React.DOM
`React.DOM` provides all of the standard HTML tags needed to build a React app. You generally don't use it directly; instead, just include it as part of the `/** @jsx React.DOM */` docblock.
### React.initializeTouchEvents
```javascript
initializeTouchEvents(boolean shouldUseTouch)
```
Configure React's event system to handle touch events on mobile devices.
### React.createClass
```javascript
function createClass(object specification)
```
Creates a component given a specification. A component implements a `render` method which returns **one single** child. That child may have an arbitrarily deep child structure. One thing that makes components different than standard prototypal classes is that you don't need to call new on them. They are convenience wrappers that construct backing instances (via new) for you.
For more information about the specification object, see [Component Specs and Lifecycle](component-specs.html).
### React.renderComponent
```javascript
ReactComponent renderComponent(
ReactComponent component,
DOMElement container,
[function callback]
)
```
Renders a React component into the DOM in the supplied `container`.
If the React component was previously rendered into `container`, this will perform an update on it and only mutate the DOM as necessary to reflect the latest React component.
If the optional callback is provided, it will be executed after the component is rendered or updated.
### React.unmountComponentAtNode
```javascript
unmountComponentAtNode(DOMElement container)
```
Remove a mounted React component from the DOM and clean up its event handlers and state.
> Note:
>
> This method was called `React.unmountAndReleaseReactRootNode` until v0.5. It still works in v0.5 but will be removed in future versions.
### React.renderComponentToString
```javascript
renderComponentToString(ReactComponent component, function callback)
```
Render a component to its initial HTML. This should only be used on the server. React will call `callback` with an HTML string when the markup is ready. You can use this method to can generate HTML on the server and send the markup down on the initial request for faster page loads and to allow search engines to crawl your pages for SEO purposes.
If you call `React.renderComponent()` on a node that already has this server-rendered markup, React will preserve it and only attach event handlers, allowing you to have a very performant first-load experience.

View File

@@ -0,0 +1,109 @@
---
id: component-api
title: Component API
layout: docs
permalink: component-api.html
prev: top-level-api.html
next: component-specs.html
---
## ReactComponent
Component classses created by `createClass()` return instances of `ReactComponent` when called. Most of the time when you're using React you're either creating or consuming these component objects.
### getDOMNode
```javascript
DOMElement getDOMNode()
```
If this component has been mounted into the DOM, this returns the corresponding native browser DOM element. This method is useful for reading values out of the DOM, such as form field values and performing DOM measurements.
### setProps
```javascript
setProps(object nextProps)
```
When you're integrating with an external JavaScript application you may want to signal a change to a React component rendered with `renderComponent()`. Simply call `setProps()` to change its properties and trigger a re-render.
> Note:
>
> This method can only be called on a root-level component. That is, it's only available on the component passed directly to `renderComponent()` and none of its children. If you're inclined to use `setProps()` on a child component, instead take advantage of reactive updates and pass the new prop to the child component when it's created in `render()`.
### replaceProps
```javascript
replaceProps(object nextProps)
```
Like `setProps()` but deletes any pre-existing props instead of merging the two objects.
### transferPropsTo
```javascript
ReactComponent transferPropsTo(ReactComponent targetComponent)
```
Transfer properties from this component to a target component that have not already been set on the target component. After the props are updated, `targetComponent` is returned as a convenience. This function is useful when creating simple HTML-like components:
```javascript
var Avatar = React.createClass({
render: function() {
return this.transferPropsTo(
<img src={"/avatars/" + this.props.userId + ".png"} userId={null} />
);
}
});
// <AvatarImage userId={17} width={200} height={200} />
```
Properties that are specified directly on the target component instance (such as `src` and `userId` in the above example) will not be overwritten by `transferPropsTo`.
> Note:
>
> Use `transferPropsTo` with caution; it encourages tight coupling and makes it easy to accidentally introduce implicit dependencies between components. When in doubt, it's safer to explicitly copy the properties that you need onto the child component.
### setState
```javascript
setState(object nextState[, function callback])
```
Merges nextState with the current state. This is the primary method you use to trigger UI updates from event handlers and server request callbacks. In addition, you can supply an optional callback function that is executed once `setState` is completed.
> Notes:
>
> *NEVER* mutate `this.state` directly, as calling `setState()` afterwards may replace the mutation you made. Treat `this.state` as if it were immutable.
>
> `setState()` does not immediately mutate `this.state` but creates a pending state transition. Accessing `this.state` after calling this method can potentially return the existing value.
>
> There is no guarantee of synchronous operation of calls to `setState` and calls may be batched for performance gains.
### replaceState
```javascript
replaceState(object nextState[, function callback])
```
Like `setState()` but deletes any pre-existing state keys that are not in nextState.
### forceUpdate()
```javascript
forceUpdate([function callback])
```
If your `render()` method reads from something other than `this.props` or `this.state`, you'll need to tell React when it needs to re-run `render()` by calling `forceUpdate()`. You'll also need to call `forceUpdate()` if you mutate `this.state` directly.
Calling `forceUpdate()` will cause `render()` to be called on the component and its children, but React will still only update the DOM if the markup changes.
Normally you should try to avoid all uses of `forceUpdate()` and only read from `this.props` and `this.state` in `render()`. This makes your application much simpler and more efficient.

View File

@@ -0,0 +1,176 @@
---
id: component-specs
title: Component Specs and Lifecycle
layout: docs
permalink: component-specs.html
prev: component-api.html
next: tags-and-attributes.html
---
## Component Specifications
When creating a component class by invoking `React.createClass()`, you should provide a specification object that contains a `render` method and can optionally contain other lifecycle methods described here.
### render
```javascript
ReactComponent render()
```
The `render()` method is required.
When called, it should examine `this.props` and `this.state` and return a single child component. This child component can be either a native DOM component (such as `<div>`) or another composite component that you've defined yourself.
The `render()` function should be *pure*, meaning that it does not modify component state, it returns the same result each time it's invoked, and it does not read from or write to the DOM or otherwise interact with the browser (e.g., by using `setTimeout`). If you need to interact with the browser, perform your work in `componentDidMount()` or the other lifecycle methods instead. Keeping `render()` pure makes server rendering more practical and makes components easier to think about.
### getInitialState
```javascript
object getInitialState()
```
Invoked once when the component is mounted. The return value will be used as the initial value of `this.state`.
### getDefaultProps
```javascript
object getDefaultProps()
```
Invoked once when the component is mounted. Values in the mapping will be set on `this.props` if that prop is not specified by the parent component (i.e. using an `in` check).
This method is invoked before `getInitialState` and therefore cannot rely on `this.state` or use `this.setState`.
### propTypes
```javascript
object propTypes
```
The `propTypes` object allows you to validate props being passed to your components. For more information about `propTypes`, see [Reusable Components](reusable-components.html).
<!-- TODO: Document propTypes here directly. -->
### mixins
```javascript
array mixins
```
The `mixins` array allows you to use mixins to share behavior among multiple components. For more information about mixins, see [Reusable Components](reusable-components.html).
<!-- TODO: Document mixins here directly. -->
## Lifecycle Methods
Various methods are executed at specific points in a component's lifecycle.
### Mounting: componentWillMount
```javascript
componentWillMount()
```
Invoked immediately before rendering occurs. If you call `setState` within this method, `render()` will see the updated state and will be executed only once despite the state change.
### Mounting: componentDidMount
```javascript
componentDidMount(DOMElement rootNode)
```
Invoked immediately after rendering occurs. At this point in the lifecycle, the component has a DOM representation which you can access via the `rootNode` argument or by calling `this.getDOMNode()`.
If you want to integrate with other JavaScript frameworks, set timers using `setTimeout` or `setInterval`, or send AJAX requests, perform those operations in this method.
### Updating: componentWillReceiveProps
```javascript
componentWillReceiveProps(object nextProps)
```
Invoked when a component is receiving new props. This method is not called for the initial render.
Use this as an opportunity to react to a prop transition before `render()` is called by updating the state using `this.setState()`. The old props can be accessed via `this.props`. Calling `this.setState()` within this function will not trigger an additional render.
```javascript
componentWillReceiveProps: function(nextProps) {
this.setState({
likesIncreasing: nextProps.likeCount > this.props.likeCount
});
}
```
> Note:
>
> There is no analogous method `componentWillReceiveState`. An incoming prop transition may cause a state change, but the opposite is not true. If you need to perform operations in response to a state change, use `componentWillUpdate`.
### Updating: shouldComponentUpdate
```javascript
boolean shouldComponentUpdate(object nextProps, object nextState)
```
Invoked before rendering when new props or state are being received. This method is not called for the initial render or when `forceUpdate` is used.
Use this as an opportunity to `return false` when you're certain that the
transition to the new props and state will not require a component update.
```javascript
shouldComponentUpdate: function(nextProps, nextState) {
return !equal(nextProps, this.props) || !equal(nextState, this.state);
}
```
If `shouldComponentUpdate` returns false, then `render()` will be completely skipped until the next state change. (In addition, `componentWillUpdate` and `componentDidUpdate` will not be called.)
By default, `shouldComponentUpdate` always returns true to prevent subtle bugs when `state` is mutated in place, but if you are careful to always treat `state` as immutable and to read only from `props` and `state` in `render()` then you can override `shouldComponentUpdate` with an implementation that compares the old props and state to their replacements.
If performance is a bottleneck, especially with dozens or hundreds of components, use `shouldComponentUpdate` to speed up your app.
### Updating: componentWillUpdate
```javascript
componentWillUpdate(object nextProps, object nextState)
```
Invoked immediately before rendering when new props or state are being received. This method is not called for the initial render.
Use this as an opportunity to perform preparation before an update occurs.
> Note:
>
> You *cannot* use `this.setState()` in this method. If you need to update state in response to a prop change, use `componentWillReceiveProps` instead.
### Updating: componentDidUpdate
```javascript
componentDidUpdate(object prevProps, object prevState, DOMElement rootNode)
```
Invoked immediately after updating occurs. This method is not called for the initial render.
Use this as an opportunity to operate on the DOM when the component has been updated.
### Unmounting: componentWillUnmount
```javascript
componentWillUnmount()
```
Invoked immediately before a component is unmounted from the DOM.
Perform any necessary cleanup in this method, such as invalidating timers or cleaning up any DOM elements that were created in `componentDidMount`.

View File

@@ -0,0 +1,65 @@
---
id: tags-and-attributes
title: Tags and Attributes
layout: docs
permalink: tags-and-attributes.html
prev: component-specs.html
next: events.html
---
## Supported Tags
React attempts to support all common elements. If you need an element that isn't listed here, please file an issue.
The following elements are supported:
### HTML Elements
```
a abbr address area article aside audio b base bdi bdo big blockquote body br
button canvas caption cite code col colgroup data datalist dd del details dfn
div dl dt em embed fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6
head header hr html i iframe img input ins kbd keygen label legend li link main
map mark menu menuitem meta meter nav noscript object ol optgroup option output
p param pre progress q rp rt ruby s samp script section select small source
span strong style sub summary sup table tbody td textarea tfoot th thead time
title tr track u ul var video wbr
```
### SVG elements
```
circle g line path polyline rect svg text
```
## Supported Attributes
React supports all `data-*` and `aria-*` attributes as well as every attribute
in the following lists. Note that all attributes are camel-cased and the attributes `class` and `for` are `className` and `htmlFor`, respectively, to match the DOM API specification.
For a list of events, see [Supported Events](events.html).
### HTML Attributes
```
accept accessKey action allowFullScreen allowTransparency alt autoCapitalize
autoComplete autoFocus autoPlay cellPadding cellSpacing charSet checked
className colSpan content contentEditable contextMenu controls data dateTime
dir disabled draggable encType form frameBorder height hidden href htmlFor
httpEquiv icon id label lang list max maxLength method min multiple name
pattern placeholder poster preload radioGroup readOnly rel required role
rowSpan scrollLeft scrollTop selected size spellCheck src step style tabIndex
target title type value width wmode
```
In addition, the non-standard `autoCapitalize` attribute is supported for Mobile Safari.
### SVG Attributes
```
cx cy d fill fx fy gradientTransform gradientUnits offset points r rx ry
spreadMethod stopColor stopOpacity stroke strokeLinecap strokeWidth transform
version viewBox x1 x2 x y1 y2 y
```

186
docs/docs/ref-05-events.md Normal file
View File

@@ -0,0 +1,186 @@
---
id: events
title: Event System
layout: docs
permalink: events.html
prev: tags-and-attributes.html
next: dom-differences.html
---
## SyntheticEvent
Your event handlers will be passed instances of `SyntheticEvent`, a cross-browser wrapper around the browser's native event. It has the same interface as the browser's native event, including `stopPropagation()` and `preventDefault()`, except the events work identically across all browsers.
If you find that you need the underlying browser event for some reason, simply use the `nativeEvent` attribute to get it. Every `SyntheticEvent` object has the following attributes:
```javascript
boolean bubbles
boolean cancelable
DOMEventTarget currentTarget
boolean defaultPrevented
Number eventPhase
boolean isTrusted
DOMEvent nativeEvent
void preventDefault()
void stopPropagation()
DOMEventTarget target
Date timeStamp
String type
```
## Supported Events
React normalizes events so that they have consistent properties across
different browsers.
### Clipboard Events
Event names:
```
onCopy onCut onPaste
```
Properties:
```javascript
DOMDataTransfer clipboardData
```
### Keyboard Events
Event names:
```
onKeyDown onKeyPress onKeyUp
```
Properties:
```javascript
boolean altKey
String char
boolean ctrlKey
String key
String locale
Number location
boolean metaKey
boolean repeat
boolean shiftKey
```
### Focus Events
Event names:
```
onFocus onBlur
```
Properties:
```javascript
DOMEventTarget relatedTarget
```
### Form Events
Event names:
```
onChange onInput onSubmit
```
For more information about the onChange event, see [Forms](forms.html).
### Mouse Events
Event names:
```
onClick onDoubleClick onDrag onDragEnd onDragEnter onDragExit onDragLeave
onDragOver onDragStart onDrop onMouseDown onMouseEnter onMouseLeave
onMouseMove onMouseUp
```
Properties:
```javascript
boolean altKey
Number button
Number buttons
Number clientX
Number clientY
boolean ctrlKey
boolean metaKey
Number pageX
Number pageY
DOMEventTarget relatedTarget
Number screenX
Number screenY
boolean shiftKey
```
### Touch events
To enable touch events, call `React.initializeTouchEvents(true)` before
rendering any component.
Event names:
```
onTouchCancel onTouchEnd onTouchMove onTouchStart
```
Properties:
```javascript
boolean altKey
DOMTouchList changedTouches
boolean ctrlKey
boolean metaKey
boolean shiftKey
DOMTouchList targetTouches
DOMTouchList touches
```
### UI Events
Event names:
```
onScroll
```
Properties:
```javascript
Number detail
DOMAbstractView view
```
### Wheel Events
Event names:
```
onWheel
```
Properties:
```javascript
Number deltaX
Number deltaMode
Number deltaY
Number deltaZ
```

View File

@@ -0,0 +1,14 @@
---
id: dom-differences
title: DOM Differences
layout: docs
permalink: dom-differences.html
prev: events.html
---
React has implemented a browser-independent events and DOM system for performance and cross-browser compatibility reasons. We took the opportunity to clean up a few rough edges in browser DOM implementations.
* All DOM properties and attributes (including event handlers) should be camelCased to be consistent with standard JavaScript style. We intentionally break with the spec here since the spec is inconsistent.
* The `style` attribute accepts a JavaScript object with camelCased properties rather than a CSS string. This is consistent with the DOM `style` JavaScript property, is more efficient, and prevents XSS security holes.
* All event objects conform to the W3C spec, and all events (including submit) bubble correctly per the W3C spec. See [Event System](events.html) for more details.
* The `onChange` event behaves as you would expect it to: whenever a form field is changed this event is fired rather than inconsistently on blur. We intentionally break from existing browser behavior because `onChange` is a misnomer for its behavior and React relies on this event to react to user input in real time. See [Forms](forms.html) for more details.

4
docs/docs/reference.html Normal file
View File

@@ -0,0 +1,4 @@
---
layout: redirect
destination: top-level-api.html
---

View File

@@ -99,7 +99,7 @@ React.renderComponent(
);
```
Its use is optional but we've found JSX syntax easier to use than plain JavaScript. Read more on the [JSX Syntax article](syntax.html).
Its use is optional but we've found JSX syntax easier to use than plain JavaScript. Read more on the [JSX Syntax article](jsx-in-depth.html).
#### What's going on
@@ -107,7 +107,7 @@ We pass some methods in a JavaScript object to `React.createClass()` to create a
The `<div>` tags are not actual DOM nodes; they are instantiations of React `div` components. You can think of these as markers or pieces of data that React knows how to handle. React is **safe**. We are not generating HTML strings so XSS protection is the default.
You do not have to return basic HTML. You can return a tree of components that you (or someone else built). This is what makes React **composable**: a key tenet of maintainable frontends.
You do not have to return basic HTML. You can return a tree of components that you (or someone else) built. This is what makes React **composable**: a key tenet of maintainable frontends.
`React.renderComponent()` instantiates the root component, starts the framework, and injects the markup into a raw DOM element, provided as the second argument.
@@ -203,7 +203,17 @@ By surrounding a JavaScript expression in braces inside JSX (as either an attrib
Markdown is a simple way to format your text inline. For example, surrounding text with asterisks will make it emphasized.
First, add the third-party **Showdown** library to your application. This is a JavaScript library which takes Markdown text and converts it to raw HTML. This requires a script tag in your head (which we have already included in the React playground).
First, add the third-party **Showdown** library to your application. This is a JavaScript library which takes Markdown text and converts it to raw HTML. This requires a script tag in your head (which we have already included in the React playground):
```html{6}
<!-- template.html -->
<head>
<title>Hello React</title>
<script src="http://fb.me/react-{{site.react_version}}.js"></script>
<script src="http://fb.me/JSXTransformer-{{site.react_version}}.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/showdown/0.3.1/showdown.min.js"></script>
</head>
```
Next, let's convert the comment text to Markdown and output it:
@@ -314,7 +324,7 @@ Let's replace the hard-coded data with some dynamic data from the server. We wil
// tutorial11.js
React.renderComponent(
<CommentBox url="comments.json" />,
document.getElementById('example')
document.getElementById('content')
);
```
@@ -438,7 +448,7 @@ All we have done here is move the AJAX call to a separate method and call it whe
Now it's time to build the form. Our `CommentForm` component should ask the user for their name and comment text and send a request to the server to save the comment.
```javascript{5-8}
```javascript{5-9}
// tutorial15.js
var CommentForm = React.createClass({
render: function() {
@@ -489,7 +499,7 @@ var CommentForm = React.createClass({
React attaches event handlers to components using a camelCase naming convention. We attach an `onSubmit` handler to the form that clears the form fields when the form is submitted with valid input.
We always return `false` from the event handler to prevent the browser's default action of submitting the form. (If you prefer, you can instead take the event as an argument and call `preventDefault()` on it &ndash; read more about [event handling](event-handling.html).)
We always return `false` from the event handler to prevent the browser's default action of submitting the form. (If you prefer, you can instead take the event as an argument and call `preventDefault()` on it.)
##### Refs
@@ -677,4 +687,4 @@ var CommentBox = React.createClass({
### Congrats!
You have just built a comment box in a few simple steps. Learn more about React in the [reference](syntax.html) or start hacking! Good luck!
You have just built a comment box in a few simple steps. Learn more about [why to use React](why-react.html), or dive into the [API reference](top-level-api.html) and start hacking! Good luck!

View File

@@ -29,12 +29,14 @@ The uncompressed, development version of React core with inline documentation.
```
#### <a href="http://fb.me/JSXTransformer-{{site.react_version}}.js">JSX Transform</a>
The JSX transformer used to support [XML syntax](/react/docs/syntax.html) in JavaScript.
The JSX transformer used to support [XML syntax](/react/docs/jsx-in-depth.html) in JavaScript.
```html
<script src="http://fb.me/JSXTransformer-{{site.react_version}}.js"></script>
```
All scripts are also available via [CDNJS](http://cdnjs.com/#react).
## Bower
```sh

Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 156 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.2 KiB

BIN
docs/img/blog/quiztime.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 KiB

BIN
docs/img/blog/unite.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 121 KiB

View File

@@ -6,7 +6,7 @@ id: jsx-compiler
<div class="jsxCompiler">
<h1>JSX Compiler</h1>
<p>
This tool demonstrates how <a href="/react/docs/syntax.html">JSX syntax</a>
This tool demonstrates how <a href="/react/docs/jsx-in-depth.html">JSX syntax</a>
is desguared into native JavaScript.
</p>
<div id="jsxCompiler"></div>

View File

@@ -6,9 +6,13 @@ id: support
**React** is worked on full-time by Facebook's product infrastructure and Instagram's user interface engineering teams. They're often around and available for questions.
## Stack Overflow
Many members of the community use Stack Overflow to ask questions. Read through the [existing questions](http://stackoverflow.com/questions/tagged/reactjs) tagged with **reactjs** or [ask your own](http://stackoverflow.com/questions/ask)!
## Google Groups mailing list
<a href="http://groups.google.com/group/reactjs" target="_blank">The **reactjs** Google Group</a> is the best place to ask questions and find answers.
<a href="http://groups.google.com/group/reactjs" target="_blank">The **reactjs** Google Group</a> is also a good place to ask questions and find answers.
## IRC

View File

@@ -14,7 +14,7 @@
<pre>
python -m SimpleHTTPServer
</pre>
and going to <a href="http://localhost:8080/">http://localhost:8080/</a>.
and going to <a href="http://localhost:8000/">http://localhost:8000/</a>.
</p>
</div>
<h4>Example Details</h4>

View File

@@ -54,7 +54,7 @@
<pre id="chromeServerCLI" class="codeBox">
cd /Path/To/This/File
python -m SimpleHTTPServer
open -a "Google Chrome" <a href="http://localhost:8080/">http://localhost:8080/</a>. </pre>
open -a "Google Chrome" <a href="http://localhost:8000/">http://localhost:8000/</a>. </pre>
</li>
</ol>
<h4 id="chromeErrorFooter" style="color: #733"></h4>

View File

@@ -10,7 +10,7 @@
<div id="container">
<p>
To install React, follow the instructions on
<a href="http://www.github.com/facebook/react.js/">GitHub</a>.
<a href="http://www.github.com/facebook/react/">GitHub</a>.
</p>
<p>
If you can see this, React is not running. You probably didn't run:

View File

@@ -10,7 +10,7 @@
<div id="container">
<p>
To install React, follow the instructions on
<a href="http://www.github.com/facebook/react.js/">GitHub</a>.
<a href="http://www.github.com/facebook/react/">GitHub</a>.
</p>
<p>
If you can see this, React is not working right.

View File

@@ -10,7 +10,7 @@
<div id="container">
<p>
To install React, follow the instructions on
<a href="http://www.github.com/facebook/react.js/">GitHub</a>.
<a href="http://www.github.com/facebook/react/">GitHub</a>.
</p>
<p>
If you can see this, React is not working right.

View File

@@ -0,0 +1,3 @@
# TodoMVC-Backbone
This is a lightweight version of TodoMVC. Its primary purpose is to demo the Backbone integration rather than being feature-complete (refer to `todomvc-director` for a full TodoMVC-compilant app).

View File

@@ -34,7 +34,7 @@ body {
font-smoothing: antialiased;
}
.todoapp {
#todoapp {
background: #fff;
background: rgba(255, 255, 255, 0.9);
margin: 130px 0 40px 0;
@@ -46,7 +46,7 @@ body {
0 25px 50px 0 rgba(0, 0, 0, 0.15);
}
.todoapp:before {
#todoapp:before {
content: '';
border-left: 1px solid #f5d6d6;
border-right: 1px solid #f5d6d6;
@@ -57,16 +57,16 @@ body {
height: 100%;
}
.todoapp input::-webkit-input-placeholder {
#todoapp input::-webkit-input-placeholder {
font-style: italic;
}
.todoapp input:-moz-placeholder {
#todoapp input::-moz-placeholder {
font-style: italic;
color: #a9a9a9;
}
.todoapp h1 {
#todoapp h1 {
position: absolute;
top: -120px;
width: 100%;
@@ -83,12 +83,12 @@ body {
text-rendering: optimizeLegibility;
}
.header {
#header {
padding-top: 15px;
border-radius: inherit;
}
.header:before {
#header:before {
content: '';
position: absolute;
top: 0;
@@ -109,7 +109,7 @@ body {
border-top-right-radius: 1px;
}
.new-todo,
#new-todo,
.edit {
position: relative;
margin: 0;
@@ -135,7 +135,7 @@ body {
font-smoothing: antialiased;
}
.new-todo {
#new-todo {
padding: 16px 16px 16px 60px;
border: none;
background: rgba(0, 0, 0, 0.02);
@@ -143,17 +143,17 @@ body {
box-shadow: none;
}
.main {
#main {
position: relative;
z-index: 2;
border-top: 1px dotted #adadad;
}
.toggle-all-label {
label[for='toggle-all'] {
display: none;
}
.toggle-all {
#toggle-all {
position: absolute;
top: -42px;
left: -4px;
@@ -162,50 +162,50 @@ body {
border: none; /* Mobile Safari */
}
.toggle-all:before {
#toggle-all:before {
content: '»';
font-size: 28px;
color: #d9d9d9;
padding: 0 25px 7px;
}
.toggle-all:checked:before {
#toggle-all:checked:before {
color: #737373;
}
.todo-list {
#todo-list {
margin: 0;
padding: 0;
list-style: none;
}
.todo-list li {
#todo-list li {
position: relative;
font-size: 24px;
border-bottom: 1px dotted #ccc;
}
.todo-list li:last-child {
#todo-list li:last-child {
border-bottom: none;
}
.todo-list li.editing {
#todo-list li.editing {
border-bottom: none;
padding: 0;
}
.todo-list li.editing .edit {
#todo-list li.editing .edit {
display: block;
width: 506px;
padding: 13px 17px 12px 17px;
margin: 0 0 0 43px;
}
.todo-list li.editing .view {
#todo-list li.editing .view {
display: none;
}
.todo-list li .toggle {
#todo-list li .toggle {
text-align: center;
width: 40px;
/* auto, since non-WebKit browsers doesn't support input styling */
@@ -222,7 +222,7 @@ body {
appearance: none;
}
.todo-list li .toggle:after {
#todo-list li .toggle:after {
content: '✔';
line-height: 43px; /* 40 + a couple of pixels visual adjustment */
font-size: 20px;
@@ -230,16 +230,17 @@ body {
text-shadow: 0 -1px 0 #bfbfbf;
}
.todo-list li .toggle:checked:after {
#todo-list li .toggle:checked:after {
color: #85ada7;
text-shadow: 0 1px 0 #669991;
bottom: 1px;
position: relative;
}
.todo-list li label {
#todo-list li label {
white-space: pre;
word-break: break-word;
padding: 15px;
padding: 15px 60px 15px 15px;
margin-left: 45px;
display: block;
line-height: 1.2;
@@ -250,12 +251,12 @@ body {
transition: color 0.4s;
}
.todo-list li.completed label {
#todo-list li.completed label {
color: #a9a9a9;
text-decoration: line-through;
}
.todo-list li .destroy {
#todo-list li .destroy {
display: none;
position: absolute;
top: 0;
@@ -273,7 +274,7 @@ body {
transition: all 0.2s;
}
.todo-list li .destroy:hover {
#todo-list li .destroy:hover {
text-shadow: 0 0 1px #000,
0 0 10px rgba(199, 107, 107, 0.8);
-webkit-transform: scale(1.3);
@@ -283,23 +284,23 @@ body {
transform: scale(1.3);
}
.todo-list li .destroy:after {
#todo-list li .destroy:after {
content: '✖';
}
.todo-list li:hover .destroy {
#todo-list li:hover .destroy {
display: block;
}
.todo-list li .edit {
#todo-list li .edit {
display: none;
}
.todo-list li.editing:last-child {
#todo-list li.editing:last-child {
margin-bottom: -1px;
}
.footer {
#footer {
color: #777;
padding: 0 15px;
position: absolute;
@@ -311,7 +312,7 @@ body {
text-align: center;
}
.footer:before {
#footer:before {
content: '';
position: absolute;
right: 0;
@@ -326,12 +327,12 @@ body {
0 44px 2px -6px rgba(0, 0, 0, 0.2);
}
.todo-count {
#todo-count {
float: left;
text-align: left;
}
.filters {
#filters {
margin: 0;
padding: 0;
list-style: none;
@@ -340,21 +341,21 @@ body {
left: 0;
}
.filters li {
#filters li {
display: inline;
}
.filters li a {
#filters li a {
color: #83756f;
margin: 2px;
text-decoration: none;
}
.filters li a.selected {
#filters li a.selected {
font-weight: bold;
}
.clear-completed {
#clear-completed {
float: right;
position: relative;
line-height: 20px;
@@ -366,12 +367,12 @@ body {
box-shadow: 0 -1px 0 0 rgba(0, 0, 0, 0.2);
}
.clear-completed:hover {
#clear-completed:hover {
background: rgba(0, 0, 0, 0.15);
box-shadow: 0 -1px 0 0 rgba(0, 0, 0, 0.3);
}
.info {
#info {
margin: 65px auto 0;
color: #a6a6a6;
font-size: 12px;
@@ -379,29 +380,25 @@ body {
text-align: center;
}
.info a {
#info a {
color: inherit;
}
.submitButton {
display: none;
}
/*
Hack to remove background from Mobile Safari.
Can't use it globally since it destroys checkboxes in Firefox and Opera
*/
@media screen and (-webkit-min-device-pixel-ratio:0) {
.toggle-all,
.todo-list li .toggle {
#toggle-all,
#todo-list li .toggle {
background: none;
}
.todo-list li .toggle {
#todo-list li .toggle {
height: 40px;
}
.toggle-all {
#toggle-all {
top: -56px;
left: -15px;
width: 65px;
@@ -413,6 +410,147 @@ body {
}
}
.hidden{
display:none;
.hidden {
display: none;
}
hr {
margin: 20px 0;
border: 0;
border-top: 1px dashed #C5C5C5;
border-bottom: 1px dashed #F7F7F7;
}
.learn a {
font-weight: normal;
text-decoration: none;
color: #b83f45;
}
.learn a:hover {
text-decoration: underline;
color: #787e7e;
}
.learn h3,
.learn h4,
.learn h5 {
margin: 10px 0;
font-weight: 500;
line-height: 1.2;
color: #000;
}
.learn h3 {
font-size: 24px;
}
.learn h4 {
font-size: 18px;
}
.learn h5 {
margin-bottom: 0;
font-size: 14px;
}
.learn ul {
padding: 0;
margin: 0 0 30px 25px;
}
.learn li {
line-height: 20px;
}
.learn p {
font-size: 15px;
font-weight: 300;
line-height: 1.3;
margin-top: 0;
margin-bottom: 0;
}
.quote {
border: none;
margin: 20px 0 60px 0;
}
.quote p {
font-style: italic;
}
.quote p:before {
content: '“';
font-size: 50px;
opacity: .15;
position: absolute;
top: -20px;
left: 3px;
}
.quote p:after {
content: '”';
font-size: 50px;
opacity: .15;
position: absolute;
bottom: -42px;
right: 3px;
}
.quote footer {
position: absolute;
bottom: -40px;
right: 0;
}
.quote footer img {
border-radius: 3px;
}
.quote footer a {
margin-left: 5px;
vertical-align: middle;
}
.speech-bubble {
position: relative;
padding: 10px;
background: rgba(0, 0, 0, .04);
border-radius: 5px;
}
.speech-bubble:after {
content: '';
position: absolute;
top: 100%;
right: 30px;
border: 13px solid transparent;
border-top-color: rgba(0, 0, 0, .04);
}
/**body*/.learn-bar > .learn {
position: absolute;
width: 272px;
top: 8px;
left: -300px;
padding: 10px;
border-radius: 5px;
background-color: rgba(255, 255, 255, .6);
transition-property: left;
transition-duration: 500ms;
}
@media (min-width: 899px) {
/**body*/.learn-bar {
width: auto;
margin: 0 0 0 300px;
}
/**body*/.learn-bar > .learn {
left: 8px;
}
/**body*/.learn-bar #todoapp {
width: 550px;
margin: 130px auto 40px auto;
}
}

View File

@@ -10,7 +10,7 @@
<![endif]-->
</head>
<body>
<div id="todoapp"></div>
<div id="container"></div>
<script src="../../build/react.js"></script>
<script src="../../build/JSXTransformer.js"></script>
<script type="text/javascript" src="../shared/thirdparty/jquery.min.js" charset="utf-8"></script>

View File

@@ -1,20 +1,6 @@
/** @jsx React.DOM */
function cx(obj) {
var s = '';
for (var key in obj) {
if (!obj.hasOwnProperty(key)) {
continue;
}
if (obj[key]) {
s += key + ' ';
}
}
return s;
}
var Todo = Backbone.Model.extend({
// Default attributes for the todo
// and ensure that each todo created has `title` and `completed` keys.
defaults: {
@@ -28,7 +14,6 @@ var Todo = Backbone.Model.extend({
completed: !this.get('completed')
});
}
});
var TodoList = Backbone.Collection.extend({
@@ -68,6 +53,19 @@ var TodoList = Backbone.Collection.extend({
var Utils = {
pluralize: function( count, word ) {
return count === 1 ? word : word + 's';
},
stringifyObjKeys: function(obj) {
var s = '';
for (var key in obj) {
if (!obj.hasOwnProperty(key)) {
continue;
}
if (obj[key]) {
s += key + ' ';
}
}
return s;
}
};
@@ -75,31 +73,47 @@ var Utils = {
var TodoItem = React.createClass({
handleSubmit: function(event) {
var val = this.refs.editField.getDOMNode().value;
var val = this.refs.editField.getDOMNode().value.trim();
if (val) {
this.props.onSave(val);
} else {
this.props.onDestroy();
}
return false;
},
onEdit: function() {
this.props.onEdit();
this.refs.editField.getDOMNode().focus();
},
render: function() {
var classes = Utils.stringifyObjKeys({
completed: this.props.todo.get('completed'), editing: this.props.editing
});
return (
<li class={cx({completed: this.props.todo.get('completed'), editing: this.props.editing})}>
<div class="view">
<li className={classes}>
<div className="view">
<input
class="toggle"
className="toggle"
type="checkbox"
checked={this.props.todo.get('completed') ? 'checked' : null}
checked={this.props.todo.get('completed')}
onChange={this.props.onToggle}
key={this.props.key}
/>
<label onDoubleClick={this.onEdit}>{this.props.todo.get('title')}</label>
<button class="destroy" onClick={this.props.onDestroy} />
<label onDoubleClick={this.onEdit}>
{this.props.todo.get('title')}
</label>
<button className="destroy" onClick={this.props.onDestroy} />
</div>
<form onSubmit={this.handleSubmit}>
<input ref="editField" class="edit" value={this.props.todo.get('title')} />
<input
ref="editField"
className="edit"
defaultValue={this.props.todo.get('title')}
onBlur={this.handleSubmit}
autoFocus="autofocus"
/>
</form>
</li>
);
@@ -113,37 +127,46 @@ var TodoFooter = React.createClass({
if (this.props.completedCount > 0) {
clearButton = (
<button class="clear-completed" onClick={this.props.onClearCompleted}>Clear completed ({this.props.completedCount})</button>
<button id="clear-completed" onClick={this.props.onClearCompleted}>
Clear completed ({this.props.completedCount})
</button>
);
}
return (
<footer class="footer">
<span class="todo-count"><strong>{this.props.count}</strong>{' '}{activeTodoWord}{' '}left</span>
<footer id="footer">
<span id="todo-count">
<strong>{this.props.count}</strong>{' '}
{activeTodoWord}{' '}left
</span>
{clearButton}
</footer>
);
}
});
// An example generic Mixin that you can add to any component that should react to changes in a Backbone component.
// The use cases we've identified thus far are for Collections -- since they trigger a change event whenever
// any of their constituent items are changed there's no need to reconcile for regular models.
// One caveat: this relies on getBackboneModels() to always return the same model instances throughout the
// lifecycle of the component. If you're using this mixin correctly (it should be near the top of your
// component hierarchy) this should not be an issue.
// An example generic Mixin that you can add to any component that should react
// to changes in a Backbone component. The use cases we've identified thus far
// are for Collections -- since they trigger a change event whenever any of
// their constituent items are changed there's no need to reconcile for regular
// models. One caveat: this relies on getBackboneModels() to always return the
// same model instances throughout the lifecycle of the component. If you're
// using this mixin correctly (it should be near the top of your component
// hierarchy) this should not be an issue.
var BackboneMixin = {
componentDidMount: function() {
// Whenever there may be a change in the Backbone data, trigger a reconcile.
this.getBackboneModels().map(function(model) {
model.on('add change remove', this.forceUpdate, this);
}.bind(this));
this.getBackboneModels().forEach(function(model) {
model.on('add change remove', this.forceUpdate.bind(this, null), this);
}, this);
},
componentWillUnmount: function() {
// Ensure that we clean up any dangling references when the component is destroyed.
this.getBackboneModels().map(function(model) {
// Ensure that we clean up any dangling references when the component is
// destroyed.
this.getBackboneModels().forEach(function(model) {
model.off(null, null, this);
}.bind(this));
}, this);
}
};
@@ -152,21 +175,28 @@ var TodoApp = React.createClass({
getInitialState: function() {
return {editing: null};
},
componentDidMount: function() {
// Additional functionality for todomvc: fetch() the collection on init
this.props.todos.fetch();
this.refs.newField.getDOMNode().focus();
},
componentDidUpdate: function() {
// If saving were expensive we'd listen for mutation events on Backbone and do this manually.
// however, since saving isn't expensive this is an elegant way to keep it reactively up-to-date.
this.props.todos.map(function(todo) {
// If saving were expensive we'd listen for mutation events on Backbone and
// do this manually. however, since saving isn't expensive this is an
// elegant way to keep it reactively up-to-date.
this.props.todos.forEach(function(todo) {
todo.save();
});
},
getBackboneModels: function() {
return [this.props.todos];
},
handleSubmit: function() {
handleSubmit: function(event) {
event.preventDefault();
var val = this.refs.newField.getDOMNode().value.trim();
if (val) {
this.props.todos.create({
@@ -176,48 +206,63 @@ var TodoApp = React.createClass({
});
this.refs.newField.getDOMNode().value = '';
}
return false;
},
toggleAll: function(event) {
var checked = event.nativeEvent.target.checked;
this.props.todos.map(function(todo) {
this.props.todos.forEach(function(todo) {
todo.set('completed', checked);
});
},
destroy: function(todo) {
this.props.todos.remove(todo);
},
edit: function(todo) {
this.setState({editing: todo.get('id')});
},
save: function(todo, text) {
todo.set('title', text);
this.setState({editing: null});
},
clearCompleted: function() {
this.props.todos.completed().map(function(todo) {
this.props.todos.completed().forEach(function(todo) {
todo.destroy();
});
},
render: function() {
var footer = null;
var main = null;
var todoItems = this.props.todos.map(function(todo) {
return <TodoItem todo={todo} onToggle={todo.toggle.bind(todo)} onDestroy={this.destroy.bind(this, todo)} onEdit={this.edit.bind(this, todo)} editing={this.state.editing === todo.get('id')} onSave={this.save.bind(this, todo)} />;
}.bind(this));
return (
<TodoItem
key={Math.random()}
todo={todo}
onToggle={todo.toggle.bind(todo)}
onDestroy={todo.destroy.bind(todo)}
onEdit={this.edit.bind(this, todo)}
editing={this.state.editing === todo.get('id')}
onSave={this.save.bind(this, todo)}
/>
);
}, this);
var activeTodoCount = this.props.todos.remaining().length;
var completedCount = todoItems.length - activeTodoCount;
if (activeTodoCount || completedCount) {
footer = <TodoFooter count={activeTodoCount} completedCount={completedCount} onClearCompleted={this.clearCompleted} />;
if (activeTodoCount || completedCount) {
footer =
<TodoFooter
count={activeTodoCount}
completedCount={completedCount}
onClearCompleted={this.clearCompleted}
/>;
}
if (todoItems.length) {
main = (
<section class="main">
<input class="toggle-all" type="checkbox" onChange={this.toggleAll} />
<label class="toggle-all-label">Mark all as complete</label>
<ul class="todo-list">
<section id="main">
<input id="toggle-all" type="checkbox" onChange={this.toggleAll} />
<ul id="todo-list">
{todoItems}
</ul>
</section>
@@ -226,23 +271,33 @@ var TodoApp = React.createClass({
return (
<div>
<section class="todoapp">
<header class="header">
<section id="todoapp">
<header id="header">
<h1>todos</h1>
<form onSubmit={this.handleSubmit}>
<input ref="newField" class="new-todo" placeholder="What needs to be done?" autofocus="autofocus" />
<input
ref="newField"
id="new-todo"
placeholder="What needs to be done?"
/>
</form>
</header>
{main}
{footer}
</section>
<footer class="info">
<footer id="info">
<p>Double-click to edit a todo</p>
<p>Created by{' '}<a href="http://github.com/petehunt/">petehunt</a></p>
<p>
Created by{' '}
<a href="http://github.com/petehunt/">petehunt</a>
</p>
<p>Part of{' '}<a href="http://todomvc.com">TodoMVC</a></p>
</footer>
</div>
);
}
});
React.renderComponent(<TodoApp todos={new TodoList()} />, document.getElementById('todoapp'));
React.renderComponent(
<TodoApp todos={new TodoList()} />, document.getElementById('container')
);

View File

@@ -0,0 +1,11 @@
# TodoMVC-director
This is the exact copy of the React-powered [TodoMVC](http://todomvc.com/labs/architecture-examples/react/). To test it, use [bower](http://bower.io) to fetch the dependencies:
`bower install`
Then fire up a server here:
`python -m SimpleHTTPServer`
And go visit `localhost:8000`.

View File

@@ -0,0 +1,9 @@
{
"name": "todomvc-react",
"version": "0.0.0",
"dependencies": {
"todomvc-common": "~0.1.7",
"react": "~0.4.0",
"director": "~1.2.0"
}
}

View File

@@ -0,0 +1,24 @@
<!doctype html>
<html lang="en" data-framework="react">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>React • TodoMVC</title>
<link rel="stylesheet" href="bower_components/todomvc-common/base.css">
</head>
<body>
<section id="todoapp"></section>
<footer id="info"></footer>
<div id="benchmark"></div>
<script src="bower_components/todomvc-common/base.js"></script>
<script src="bower_components/react/react.js"></script>
<script src="bower_components/react/JSXTransformer.js"></script>
<script src="bower_components/director/build/director.min.js"></script>
<script type="text/jsx" src="js/utils.jsx"></script>
<script type="text/jsx" src="js/todoItem.jsx"></script>
<script type="text/jsx" src="js/footer.jsx"></script>
<script type="text/jsx" src="js/app.jsx"></script>
</body>
</html>

View File

@@ -0,0 +1,207 @@
/**
* @jsx React.DOM
*/
/*jshint quotmark:false */
/*jshint white:false */
/*jshint trailing:false */
/*jshint newcap:false */
/*global Utils, ALL_TODOS, ACTIVE_TODOS, COMPLETED_TODOS,
TodoItem, TodoFooter, React, Router*/
(function (window, React) {
'use strict';
window.ALL_TODOS = 'all';
window.ACTIVE_TODOS = 'active';
window.COMPLETED_TODOS = 'completed';
var ENTER_KEY = 13;
var TodoApp = React.createClass({
getInitialState: function () {
var todos = Utils.store('react-todos');
return {
todos: todos,
nowShowing: ALL_TODOS,
editing: null
};
},
componentDidMount: function () {
var router = Router({
'/': this.setState.bind(this, {nowShowing: ALL_TODOS}),
'/active': this.setState.bind(this, {nowShowing: ACTIVE_TODOS}),
'/completed': this.setState.bind(this, {nowShowing: COMPLETED_TODOS})
});
router.init();
this.refs.newField.getDOMNode().focus();
},
handleNewTodoKeyDown: function (event) {
if (event.which !== ENTER_KEY) {
return;
}
var val = this.refs.newField.getDOMNode().value.trim();
var todos;
var newTodo;
if (val) {
todos = this.state.todos;
newTodo = {
id: Utils.uuid(),
title: val,
completed: false
};
this.setState({todos: todos.concat([newTodo])});
this.refs.newField.getDOMNode().value = '';
}
return false;
},
toggleAll: function (event) {
var checked = event.target.checked;
this.state.todos.forEach(function (todo) {
todo.completed = checked;
});
this.setState({todos: this.state.todos});
},
toggle: function (todo) {
todo.completed = !todo.completed;
this.setState({todos: this.state.todos});
},
destroy: function (todo) {
var newTodos = this.state.todos.filter(function (candidate) {
return candidate.id !== todo.id;
});
this.setState({todos: newTodos});
},
edit: function (todo, callback) {
// refer to todoItem.js `handleEdit` for the reasoning behind the
// callback
this.setState({editing: todo.id}, function () {
callback();
});
},
save: function (todo, text) {
todo.title = text;
this.setState({todos: this.state.todos, editing: null});
},
cancel: function () {
this.setState({editing: null});
},
clearCompleted: function () {
var newTodos = this.state.todos.filter(function (todo) {
return !todo.completed;
});
this.setState({todos: newTodos});
},
componentDidUpdate: function () {
Utils.store('react-todos', this.state.todos);
},
render: function () {
var footer = null;
var main = null;
var todoItems = {};
var activeTodoCount;
var completedCount;
var shownTodos = this.state.todos.filter(function (todo) {
switch (this.state.nowShowing) {
case ACTIVE_TODOS:
return !todo.completed;
case COMPLETED_TODOS:
return todo.completed;
default:
return true;
}
}.bind(this));
shownTodos.forEach(function (todo) {
todoItems[todo.id] = (
<TodoItem
todo={todo}
onToggle={this.toggle.bind(this, todo)}
onDestroy={this.destroy.bind(this, todo)}
onEdit={this.edit.bind(this, todo)}
editing={this.state.editing === todo.id}
onSave={this.save.bind(this, todo)}
onCancel={this.cancel}
/>
);
}.bind(this));
activeTodoCount = this.state.todos.filter(function (todo) {
return !todo.completed;
}).length;
completedCount = this.state.todos.length - activeTodoCount;
if (activeTodoCount || completedCount) {
footer =
<TodoFooter
count={activeTodoCount}
completedCount={completedCount}
nowShowing={this.state.nowShowing}
onClearCompleted={this.clearCompleted}
/>;
}
if (this.state.todos.length) {
main = (
<section id="main">
<input
id="toggle-all"
type="checkbox"
onChange={this.toggleAll}
checked={activeTodoCount === 0}
/>
<ul id="todo-list">
{todoItems}
</ul>
</section>
);
}
return (
<div>
<header id="header">
<h1>todos</h1>
<input
ref="newField"
id="new-todo"
placeholder="What needs to be done?"
onKeyDown={this.handleNewTodoKeyDown}
/>
</header>
{main}
{footer}
</div>
);
}
});
React.renderComponent(<TodoApp />, document.getElementById('todoapp'));
React.renderComponent(
<div>
<p>Double-click to edit a todo</p>
<p>Created by{' '}
<a href="http://github.com/petehunt/">petehunt</a>
</p>
<p>Part of{' '}<a href="http://todomvc.com">TodoMVC</a></p>
</div>,
document.getElementById('info'));
})(window, React);

View File

@@ -0,0 +1,58 @@
/**
* @jsx React.DOM
*/
/*jshint quotmark:false */
/*jshint white:false */
/*jshint trailing:false */
/*jshint newcap:false */
/*global React, ALL_TODOS, ACTIVE_TODOS, Utils, COMPLETED_TODOS */
(function (window) {
'use strict';
window.TodoFooter = React.createClass({
render: function () {
var activeTodoWord = Utils.pluralize(this.props.count, 'item');
var clearButton = null;
if (this.props.completedCount > 0) {
clearButton = (
<button
id="clear-completed"
onClick={this.props.onClearCompleted}>
{''}Clear completed ({this.props.completedCount}){''}
</button>
);
}
var show = {
ALL_TODOS: '',
ACTIVE_TODOS: '',
COMPLETED_TODOS: ''
};
show[this.props.nowShowing] = 'selected';
return (
<footer id="footer">
<span id="todo-count">
<strong>{this.props.count}</strong>
{' '}{activeTodoWord}{' '}left{''}
</span>
<ul id="filters">
<li>
<a href="#/" className={show[ALL_TODOS]}>All</a>
</li>
{' '}
<li>
<a href="#/active" className={show[ACTIVE_TODOS]}>Active</a>
</li>
{' '}
<li>
<a href="#/completed" className={show[COMPLETED_TODOS]}>Completed</a>
</li>
</ul>
{clearButton}
</footer>
);
}
});
})(window);

View File

@@ -0,0 +1,93 @@
/**
* @jsx React.DOM
*/
/*jshint quotmark: false */
/*jshint white: false */
/*jshint trailing: false */
/*jshint newcap: false */
/*global React, Utils */
(function (window) {
'use strict';
var ESCAPE_KEY = 27;
var ENTER_KEY = 13;
window.TodoItem = React.createClass({
handleSubmit: function () {
var val = this.state.editText.trim();
if (val) {
this.props.onSave(val);
this.setState({editText: val});
} else {
this.props.onDestroy();
}
return false;
},
handleEdit: function () {
// react optimizes renders by batching them. This means you can't call
// parent's `onEdit` (which in this case triggeres a re-render), and
// immediately manipulate the DOM as if the rendering's over. Put it as a
// callback. Refer to app.js' `edit` method
this.props.onEdit(function () {
var node = this.refs.editField.getDOMNode();
node.focus();
node.setSelectionRange(node.value.length, node.value.length);
}.bind(this));
},
handleKeyDown: function (event) {
if (event.keyCode === ESCAPE_KEY) {
this.setState({editText: this.props.todo.title});
this.props.onCancel();
} else if (event.keyCode === ENTER_KEY) {
this.handleSubmit();
} else {
this.setState({editText: event.target.value});
}
},
handleChange: function (event) {
this.setState({editText: event.target.value});
},
getInitialState: function () {
return {editText: this.props.todo.title};
},
componentWillReceiveProps: function (nextProps) {
if (nextProps.todo.title !== this.props.todo.title) {
this.setState(this.getInitialState());
}
},
render: function () {
return (
<li className={Utils.stringifyObjKeys({
completed: this.props.todo.completed,
editing: this.props.editing
})}>
<div className="view">
<input
className="toggle"
type="checkbox"
checked={this.props.todo.completed ? 'checked' : null}
onChange={this.props.onToggle}
/>
<label onDoubleClick={this.handleEdit}>
{this.props.todo.title}
</label>
<button className='destroy' onClick={this.props.onDestroy} />
</div>
<input
ref="editField"
className="edit"
value={this.state.editText}
onBlur={this.handleSubmit}
onChange={this.handleChange}
onKeyDown={this.handleKeyDown}
/>
</li>
);
}
});
})(window);

View File

@@ -0,0 +1,49 @@
(function (window) {
'use strict';
window.Utils = {
uuid: function () {
/*jshint bitwise:false */
var i, random;
var uuid = '';
for (i = 0; i < 32; i++) {
random = Math.random() * 16 | 0;
if (i === 8 || i === 12 || i === 16 || i === 20) {
uuid += '-';
}
uuid += (i === 12 ? 4 : (i === 16 ? (random & 3 | 8) : random))
.toString(16);
}
return uuid;
},
pluralize: function (count, word) {
return count === 1 ? word : word + 's';
},
store: function (namespace, data) {
if (data) {
return localStorage.setItem(namespace, JSON.stringify(data));
}
var store = localStorage.getItem(namespace);
return (store && JSON.parse(store)) || [];
},
stringifyObjKeys: function (obj) {
var s = '';
var key;
for (key in obj) {
if (obj.hasOwnProperty(key) && obj[key]) {
s += key + ' ';
}
}
return s.trim();
}
};
})(window);

View File

@@ -1,425 +0,0 @@
html,
body {
margin: 0;
padding: 0;
}
button {
margin: 0;
padding: 0;
border: 0;
background: none;
font-size: 100%;
vertical-align: baseline;
font-family: inherit;
color: inherit;
-webkit-appearance: none;
/*-moz-appearance: none;*/
-ms-appearance: none;
-o-appearance: none;
appearance: none;
}
body {
font: 14px 'Helvetica Neue', Helvetica, Arial, sans-serif;
line-height: 1.4em;
background: #eaeaea url('bg.png');
color: #4d4d4d;
width: 550px;
margin: 0 auto;
-webkit-font-smoothing: antialiased;
-moz-font-smoothing: antialiased;
-ms-font-smoothing: antialiased;
-o-font-smoothing: antialiased;
font-smoothing: antialiased;
}
.todoapp {
background: #fff;
background: rgba(255, 255, 255, 0.9);
margin: 130px 0 40px 0;
border: 1px solid #ccc;
position: relative;
border-top-left-radius: 2px;
border-top-right-radius: 2px;
box-shadow: 0 2px 6px 0 rgba(0, 0, 0, 0.2),
0 25px 50px 0 rgba(0, 0, 0, 0.15);
}
.todoapp:before {
content: '';
border-left: 1px solid #f5d6d6;
border-right: 1px solid #f5d6d6;
width: 2px;
position: absolute;
top: 0;
left: 40px;
height: 100%;
}
.todoapp input::-webkit-input-placeholder {
font-style: italic;
}
.todoapp input:-moz-placeholder {
font-style: italic;
color: #a9a9a9;
}
.todoapp h1 {
position: absolute;
top: -120px;
width: 100%;
font-size: 70px;
font-weight: bold;
text-align: center;
color: #b3b3b3;
color: rgba(255, 255, 255, 0.3);
text-shadow: -1px -1px rgba(0, 0, 0, 0.2);
-webkit-text-rendering: optimizeLegibility;
-moz-text-rendering: optimizeLegibility;
-ms-text-rendering: optimizeLegibility;
-o-text-rendering: optimizeLegibility;
text-rendering: optimizeLegibility;
}
.header {
padding-top: 15px;
border-radius: inherit;
}
.header:before {
content: '';
position: absolute;
top: 0;
right: 0;
left: 0;
height: 15px;
z-index: 2;
border-bottom: 1px solid #6c615c;
background: #8d7d77;
background: -webkit-gradient(linear, left top, left bottom, from(rgba(132, 110, 100, 0.8)),to(rgba(101, 84, 76, 0.8)));
background: -webkit-linear-gradient(top, rgba(132, 110, 100, 0.8), rgba(101, 84, 76, 0.8));
background: -moz-linear-gradient(top, rgba(132, 110, 100, 0.8), rgba(101, 84, 76, 0.8));
background: -o-linear-gradient(top, rgba(132, 110, 100, 0.8), rgba(101, 84, 76, 0.8));
background: -ms-linear-gradient(top, rgba(132, 110, 100, 0.8), rgba(101, 84, 76, 0.8));
background: linear-gradient(top, rgba(132, 110, 100, 0.8), rgba(101, 84, 76, 0.8));
filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,StartColorStr='#9d8b83', EndColorStr='#847670');
border-top-left-radius: 1px;
border-top-right-radius: 1px;
}
.new-todo,
.edit {
position: relative;
margin: 0;
width: 100%;
font-size: 24px;
font-family: inherit;
line-height: 1.4em;
border: 0;
outline: none;
color: inherit;
padding: 6px;
border: 1px solid #999;
box-shadow: inset 0 -1px 5px 0 rgba(0, 0, 0, 0.2);
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
-ms-box-sizing: border-box;
-o-box-sizing: border-box;
box-sizing: border-box;
-webkit-font-smoothing: antialiased;
-moz-font-smoothing: antialiased;
-ms-font-smoothing: antialiased;
-o-font-smoothing: antialiased;
font-smoothing: antialiased;
}
.new-todo {
padding: 16px 16px 16px 60px;
border: none;
background: rgba(0, 0, 0, 0.02);
z-index: 2;
box-shadow: none;
}
.main {
position: relative;
z-index: 2;
border-top: 1px dotted #adadad;
}
.toggle-all-label {
display: none;
}
.toggle-all {
position: absolute;
top: -42px;
left: -4px;
width: 40px;
text-align: center;
border: none; /* Mobile Safari */
}
.toggle-all:before {
content: '»';
font-size: 28px;
color: #d9d9d9;
padding: 0 25px 7px;
}
.toggle-all:checked:before {
color: #737373;
}
.todo-list {
margin: 0;
padding: 0;
list-style: none;
}
.todo-list li {
position: relative;
font-size: 24px;
border-bottom: 1px dotted #ccc;
}
.todo-list li:last-child {
border-bottom: none;
}
.todo-list li.editing {
border-bottom: none;
padding: 0;
}
.todo-list li.editing .edit {
display: block;
width: 506px;
padding: 13px 17px 12px 17px;
margin: 0 0 0 43px;
}
.todo-list li.editing .view {
display: none;
}
.todo-list li .toggle {
text-align: center;
width: 40px;
/* auto, since non-WebKit browsers doesn't support input styling */
height: auto;
position: absolute;
top: 0;
bottom: 0;
margin: auto 0;
border: none; /* Mobile Safari */
-webkit-appearance: none;
/*-moz-appearance: none;*/
-ms-appearance: none;
-o-appearance: none;
appearance: none;
}
.todo-list li .toggle:after {
content: '✔';
line-height: 43px; /* 40 + a couple of pixels visual adjustment */
font-size: 20px;
color: #d9d9d9;
text-shadow: 0 -1px 0 #bfbfbf;
}
.todo-list li .toggle:checked:after {
color: #85ada7;
text-shadow: 0 1px 0 #669991;
bottom: 1px;
position: relative;
}
.todo-list li label {
word-break: break-word;
padding: 15px;
margin-left: 45px;
display: block;
line-height: 1.2;
-webkit-transition: color 0.4s;
-moz-transition: color 0.4s;
-ms-transition: color 0.4s;
-o-transition: color 0.4s;
transition: color 0.4s;
}
.todo-list li.completed label {
color: #a9a9a9;
text-decoration: line-through;
}
.todo-list li .destroy {
display: none;
position: absolute;
top: 0;
right: 10px;
bottom: 0;
width: 40px;
height: 40px;
margin: auto 0;
font-size: 22px;
color: #a88a8a;
-webkit-transition: all 0.2s;
-moz-transition: all 0.2s;
-ms-transition: all 0.2s;
-o-transition: all 0.2s;
transition: all 0.2s;
}
.todo-list li .destroy:hover {
text-shadow: 0 0 1px #000,
0 0 10px rgba(199, 107, 107, 0.8);
-webkit-transform: scale(1.3);
-moz-transform: scale(1.3);
-ms-transform: scale(1.3);
-o-transform: scale(1.3);
transform: scale(1.3);
}
.todo-list li .destroy:after {
content: '✖';
}
.todo-list li:hover .destroy {
display: block;
}
.todo-list li .edit {
display: none;
}
.todo-list li.editing:last-child {
margin-bottom: -1px;
}
.footer {
color: #777;
padding: 0 15px;
position: absolute;
right: 0;
bottom: -31px;
left: 0;
height: 20px;
z-index: 1;
text-align: center;
}
.footer:before {
content: '';
position: absolute;
right: 0;
bottom: 31px;
left: 0;
height: 50px;
z-index: -1;
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.3),
0 6px 0 -3px rgba(255, 255, 255, 0.8),
0 7px 1px -3px rgba(0, 0, 0, 0.3),
0 43px 0 -6px rgba(255, 255, 255, 0.8),
0 44px 2px -6px rgba(0, 0, 0, 0.2);
}
.todo-count {
float: left;
text-align: left;
}
.filters {
margin: 0;
padding: 0;
list-style: none;
position: absolute;
right: 0;
left: 0;
}
.filters li {
display: inline;
}
.filters li a {
color: #83756f;
margin: 2px;
text-decoration: none;
}
.filters li a.selected {
font-weight: bold;
}
.clear-completed {
float: right;
position: relative;
line-height: 20px;
text-decoration: none;
background: rgba(0, 0, 0, 0.1);
font-size: 11px;
padding: 0 10px;
border-radius: 3px;
box-shadow: 0 -1px 0 0 rgba(0, 0, 0, 0.2);
}
.clear-completed:hover {
background: rgba(0, 0, 0, 0.15);
box-shadow: 0 -1px 0 0 rgba(0, 0, 0, 0.3);
}
.info {
margin: 65px auto 0;
color: #a6a6a6;
font-size: 12px;
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.7);
text-align: center;
}
.info a {
color: inherit;
}
/*
Hack to remove background from Mobile Safari.
Can't use it globally since it destroys checkboxes in Firefox and Opera
*/
@media screen and (-webkit-min-device-pixel-ratio:0) {
.toggle-all,
.todo-list li .toggle {
background: none;
}
.todo-list li .toggle {
height: 40px;
}
.toggle-all {
top: -56px;
left: -15px;
width: 65px;
height: 41px;
-webkit-transform: rotate(90deg);
transform: rotate(90deg);
-webkit-appearance: none;
appearance: none;
}
}
.hidden{
display:none;
}
#benchmark {
position: absolute;
left: 0;
top: 0;
padding: 10px;
}
.submitButton {
display: none;
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 KiB

View File

@@ -1,19 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>React • TodoMVC</title>
<link rel="stylesheet" href="css/base.css">
<!--[if IE]>
<script src="js/ie.js"></script>
<![endif]-->
</head>
<body>
<div id="todoapp"></div>
<div id="benchmark"></div>
<script src="../../build/react.js"></script>
<script src="../../build/JSXTransformer.js"></script>
<script type="text/jsx" src="js/app.js"></script>
</body>
</html>

View File

@@ -1,255 +0,0 @@
/**
* @jsx React.DOM
*/
var Utils = {
// https://gist.github.com/1308368
uuid: function(a,b){for(b=a='';a++<36;b+=a*51&52?(a^15?8^Math.random()*(a^20?16:4):4).toString(16):'-');return b},
pluralize: function( count, word ) {
return count === 1 ? word : word + 's';
},
store: function( namespace, data ) {
if ( arguments.length > 1 ) {
return localStorage.setItem( namespace, JSON.stringify( data ) );
} else {
var store = localStorage.getItem( namespace );
return ( store && JSON.parse( store ) ) || [];
}
}
};
function cx(obj) {
var s = '';
for (var key in obj) {
if (!obj.hasOwnProperty(key)) {
continue;
}
if (obj[key]) {
s += key + ' ';
}
}
return s;
}
var TodoItem = React.createClass({
handleSubmit: function() {
var val = this.state.editText;
if (val) {
this.props.onSave(val);
this.setState({editField: ''});
}
return false;
},
handleEdit: function() {
this.props.onEdit();
this.refs.editField.getDOMNode().focus();
},
handleKey: function(event) {
if (event.nativeEvent.keyCode === 27) {
this.handleSubmit();
}
this.setState({editText: event.target.value});
},
getInitialState: function() {
return {editText: this.props.todo.title};
},
componentWillReceiveProps: function(nextProps) {
if (nextProps.todo.title !== this.props.todo.title) {
this.setState(this.getInitialState());
}
},
render: function() {
return (
<li class={cx({completed: this.props.todo.completed, editing: this.props.editing})}>
<div class="view">
<input
class="toggle"
type="checkbox"
checked={this.props.todo.completed ? 'checked' : null}
onChange={this.props.onToggle}
/>
<label onDoubleClick={this.handleEdit}>{this.props.todo.title}</label>
<button class="destroy" onClick={this.props.onDestroy} />
</div>
<form onSubmit={this.handleSubmit}>
<input
ref="editField"
class="edit"
value={this.state.editText}
onBlur={this.handleSubmit}
onKeyUp={this.handleKey}
/>
<input type="submit" class="submitButton" />
</form>
</li>
);
}
});
var TodoFooter = React.createClass({
render: function() {
var activeTodoWord = Utils.pluralize(this.props.count, 'todo');
var clearButton = null;
if (this.props.completedCount > 0) {
clearButton = (
<button class="clear-completed" onClick={this.props.onClearCompleted}>Clear completed ({this.props.completedCount})</button>
);
}
return (
<footer class="footer">
<span class="todo-count"><strong>{this.props.count}</strong>{' '}{activeTodoWord}{' '}left</span>
{clearButton}
</footer>
);
}
});
var TodoApp = React.createClass({
getInitialState: function() {
return {
todos: Utils.store('react-todos'),
editing: {}
};
},
handleSubmit: function() {
var val = this.refs.newField.getDOMNode().value.trim();
if (val) {
var todos = this.state.todos;
var newTodo = {
id: Utils.uuid(),
title: val,
completed: false
};
this.setState({todos: todos.concat([newTodo])});
this.refs.newField.getDOMNode().value = '';
}
return false;
},
toggleAll: function(event) {
var checked = event.nativeEvent.target.checked;
this.state.todos.map(function(todo) {
todo.completed = checked;
});
this.setState({todos: this.state.todos});
},
toggle: function(todo) {
todo.completed = !todo.completed;
this.setState({todos: this.state.todos});
},
destroy: function(todo) {
var newTodos = this.state.todos.filter(function(candidate) {
return candidate.id !== todo.id;
});
this.setState({todos: newTodos});
},
edit: function(todo) {
this.state.todos.map(function(todo) {
this.state.editing[todo.id] = false;
}.bind(this));
this.state.editing[todo.id] = true;
this.setState({editing: this.state.editing});
},
save: function(todo, text) {
todo.title = text;
this.state.editing[todo.id] = false;
this.setState({todos: this.state.todos, editing: this.state.editing});
},
clearCompleted: function() {
var newTodos = this.state.todos.filter(function(todo) {
return !todo.completed;
});
this.setState({todos: newTodos});
},
render: function() {
Utils.store('react-todos', this.state.todos);
var footer = null;
var main = null;
var todoItems = this.state.todos.map(function(todo) {
return (
<TodoItem
todo={todo}
onToggle={this.toggle.bind(this, todo)}
onDestroy={this.destroy.bind(this, todo)}
onEdit={this.edit.bind(this, todo)}
editing={this.state.editing[todo.id]}
onSave={this.save.bind(this, todo)}
/>
);
}.bind(this));
var activeTodoCount = this.state.todos.filter(function(todo) {
return !todo.completed;
}).length;
var completedCount = todoItems.length - activeTodoCount;
if (activeTodoCount || completedCount) {
footer =
<TodoFooter
count={activeTodoCount}
completedCount={completedCount}
onClearCompleted={this.clearCompleted.bind(this)}
/>;
}
if (todoItems.length) {
main = (
<section class="main">
<input class="toggle-all" type="checkbox" onChange={this.toggleAll.bind(this)} />
<label class="toggle-all-label">Mark all as complete</label>
<ul class="todo-list">
{todoItems}
</ul>
</section>
);
}
return (
<div>
<section class="todoapp">
<header class="header">
<h1>todos</h1>
<form onSubmit={this.handleSubmit}>
<input
ref="newField"
class="new-todo"
placeholder="What needs to be done?"
autofocus="autofocus"
/>
<input type="submit" class="submitButton" />
</form>
</header>
{main}
{footer}
</section>
<footer class="info">
<p>Double-click to edit a todo</p>
<p>Created by{' '}<a href="http://github.com/petehunt/">petehunt</a></p>
<p>Part of{' '}<a href="http://todomvc.com">TodoMVC</a></p>
</footer>
</div>
);
}
});
React.renderComponent(<TodoApp />, document.getElementById('todoapp'));
// Some benchmarking that requires either a custom build of React or more
// modules exposed from React.*
// var initTime = ReactMount.totalInstantiationTime + ReactMount.totalInjectionTime;
// var benchmark = document.getElementById('benchmark');
// setInterval(function() {
// benchmark.innerHTML = (
// 'Init render time = ' + initTime + 'ms' +
// '<br />' +
// 'Post-init render time = ' + (ReactMount.totalInstantiationTime + ReactMount.totalInjectionTime - initTime) + 'ms'
// );
// }, 1000);

View File

@@ -1,34 +0,0 @@
/*! HTML5 Shiv pre3.6 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed
Uncompressed source: https://github.com/aFarkas/html5shiv */
(function(l,f){function m(){var a=e.elements;return"string"==typeof a?a.split(" "):a}function i(a){var b=n[a[o]];b||(b={},h++,a[o]=h,n[h]=b);return b}function p(a,b,c){b||(b=f);if(g)return b.createElement(a);c||(c=i(b));b=c.cache[a]?c.cache[a].cloneNode():r.test(a)?(c.cache[a]=c.createElem(a)).cloneNode():c.createElem(a);return b.canHaveChildren&&!s.test(a)?c.frag.appendChild(b):b}function t(a,b){if(!b.cache)b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag();
a.createElement=function(c){return!e.shivMethods?b.createElem(c):p(c,a,b)};a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+m().join().replace(/\w+/g,function(a){b.createElem(a);b.frag.createElement(a);return'c("'+a+'")'})+");return n}")(e,b.frag)}function q(a){a||(a=f);var b=i(a);if(e.shivCSS&&!j&&!b.hasCSS){var c,d=a;c=d.createElement("p");d=d.getElementsByTagName("head")[0]||d.documentElement;c.innerHTML="x<style>article,aside,figcaption,figure,footer,header,hgroup,nav,section{display:block}mark{background:#FF0;color:#000}</style>";
c=d.insertBefore(c.lastChild,d.firstChild);b.hasCSS=!!c}g||t(a,b);return a}var k=l.html5||{},s=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,r=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,j,o="_html5shiv",h=0,n={},g;(function(){try{var a=f.createElement("a");a.innerHTML="<xyz></xyz>";j="hidden"in a;var b;if(!(b=1==a.childNodes.length)){f.createElement("a");var c=f.createDocumentFragment();b="undefined"==typeof c.cloneNode||
"undefined"==typeof c.createDocumentFragment||"undefined"==typeof c.createElement}g=b}catch(d){g=j=!0}})();var e={elements:k.elements||"abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video",shivCSS:!1!==k.shivCSS,supportsUnknownElements:g,shivMethods:!1!==k.shivMethods,type:"default",shivDocument:q,createElement:p,createDocumentFragment:function(a,b){a||(a=f);if(g)return a.createDocumentFragment();
for(var b=b||i(a),c=b.frag.cloneNode(),d=0,e=m(),h=e.length;d<h;d++)c.createElement(e[d]);return c}};l.html5=e;q(f)})(this,document);
/* ES5-shim
https://github.com/kriskowal/es5-shim
Copyright 2009-2012 by contributors, MIT License */
(function(definition){if(typeof define=="function")define(definition);else if(typeof YUI=="function")YUI.add("es5",definition);else definition()})(function(){if(!Function.prototype.bind)Function.prototype.bind=function bind(that){var target=this;if(typeof target!="function")throw new TypeError("Function.prototype.bind called on incompatible "+target);var args=slice.call(arguments,1);var bound=function(){if(this instanceof bound){var result=target.apply(this,args.concat(slice.call(arguments)));if(Object(result)===
result)return result;return this}else return target.apply(that,args.concat(slice.call(arguments)))};if(target.prototype)bound.prototype=Object.create(target.prototype);return bound};var call=Function.prototype.call;var prototypeOfArray=Array.prototype;var prototypeOfObject=Object.prototype;var slice=prototypeOfArray.slice;var _toString=call.bind(prototypeOfObject.toString);var owns=call.bind(prototypeOfObject.hasOwnProperty);var defineGetter;var defineSetter;var lookupGetter;var lookupSetter;var supportsAccessors;
if(supportsAccessors=owns(prototypeOfObject,"__defineGetter__")){defineGetter=call.bind(prototypeOfObject.__defineGetter__);defineSetter=call.bind(prototypeOfObject.__defineSetter__);lookupGetter=call.bind(prototypeOfObject.__lookupGetter__);lookupSetter=call.bind(prototypeOfObject.__lookupSetter__)}if([1,2].splice(0).length!=2){var array_splice=Array.prototype.splice;Array.prototype.splice=function(start,deleteCount){if(!arguments.length)return[];else return array_splice.apply(this,[start===void 0?
0:start,deleteCount===void 0?this.length-start:deleteCount].concat(slice.call(arguments,2)))}}if(!Array.isArray)Array.isArray=function isArray(obj){return _toString(obj)=="[object Array]"};var boxedString=Object("a"),splitString=boxedString[0]!="a"||!(0 in boxedString);if(!Array.prototype.forEach)Array.prototype.forEach=function forEach(fun){var object=toObject(this),self=splitString&&_toString(this)=="[object String]"?this.split(""):object,thisp=arguments[1],i=-1,length=self.length>>>0;if(_toString(fun)!=
"[object Function]")throw new TypeError;while(++i<length)if(i in self)fun.call(thisp,self[i],i,object)};if(!Array.prototype.map)Array.prototype.map=function map(fun){var object=toObject(this),self=splitString&&_toString(this)=="[object String]"?this.split(""):object,length=self.length>>>0,result=Array(length),thisp=arguments[1];if(_toString(fun)!="[object Function]")throw new TypeError(fun+" is not a function");for(var i=0;i<length;i++)if(i in self)result[i]=fun.call(thisp,self[i],i,object);return result};
if(!Array.prototype.filter)Array.prototype.filter=function filter(fun){var object=toObject(this),self=splitString&&_toString(this)=="[object String]"?this.split(""):object,length=self.length>>>0,result=[],value,thisp=arguments[1];if(_toString(fun)!="[object Function]")throw new TypeError(fun+" is not a function");for(var i=0;i<length;i++)if(i in self){value=self[i];if(fun.call(thisp,value,i,object))result.push(value)}return result};if(!Array.prototype.every)Array.prototype.every=function every(fun){var object=
toObject(this),self=splitString&&_toString(this)=="[object String]"?this.split(""):object,length=self.length>>>0,thisp=arguments[1];if(_toString(fun)!="[object Function]")throw new TypeError(fun+" is not a function");for(var i=0;i<length;i++)if(i in self&&!fun.call(thisp,self[i],i,object))return false;return true};if(!Array.prototype.some)Array.prototype.some=function some(fun){var object=toObject(this),self=splitString&&_toString(this)=="[object String]"?this.split(""):object,length=self.length>>>
0,thisp=arguments[1];if(_toString(fun)!="[object Function]")throw new TypeError(fun+" is not a function");for(var i=0;i<length;i++)if(i in self&&fun.call(thisp,self[i],i,object))return true;return false};if(!Array.prototype.reduce)Array.prototype.reduce=function reduce(fun){var object=toObject(this),self=splitString&&_toString(this)=="[object String]"?this.split(""):object,length=self.length>>>0;if(_toString(fun)!="[object Function]")throw new TypeError(fun+" is not a function");if(!length&&arguments.length==
1)throw new TypeError("reduce of empty array with no initial value");var i=0;var result;if(arguments.length>=2)result=arguments[1];else{do{if(i in self){result=self[i++];break}if(++i>=length)throw new TypeError("reduce of empty array with no initial value");}while(true)}for(;i<length;i++)if(i in self)result=fun.call(void 0,result,self[i],i,object);return result};if(!Array.prototype.reduceRight)Array.prototype.reduceRight=function reduceRight(fun){var object=toObject(this),self=splitString&&_toString(this)==
"[object String]"?this.split(""):object,length=self.length>>>0;if(_toString(fun)!="[object Function]")throw new TypeError(fun+" is not a function");if(!length&&arguments.length==1)throw new TypeError("reduceRight of empty array with no initial value");var result,i=length-1;if(arguments.length>=2)result=arguments[1];else{do{if(i in self){result=self[i--];break}if(--i<0)throw new TypeError("reduceRight of empty array with no initial value");}while(true)}do if(i in this)result=fun.call(void 0,result,
self[i],i,object);while(i--);return result};if(!Array.prototype.indexOf||[0,1].indexOf(1,2)!=-1)Array.prototype.indexOf=function indexOf(sought){var self=splitString&&_toString(this)=="[object String]"?this.split(""):toObject(this),length=self.length>>>0;if(!length)return-1;var i=0;if(arguments.length>1)i=toInteger(arguments[1]);i=i>=0?i:Math.max(0,length+i);for(;i<length;i++)if(i in self&&self[i]===sought)return i;return-1};if(!Array.prototype.lastIndexOf||[0,1].lastIndexOf(0,-3)!=-1)Array.prototype.lastIndexOf=
function lastIndexOf(sought){var self=splitString&&_toString(this)=="[object String]"?this.split(""):toObject(this),length=self.length>>>0;if(!length)return-1;var i=length-1;if(arguments.length>1)i=Math.min(i,toInteger(arguments[1]));i=i>=0?i:length-Math.abs(i);for(;i>=0;i--)if(i in self&&sought===self[i])return i;return-1};if(!Object.keys){var hasDontEnumBug=true,dontEnums=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],dontEnumsLength=
dontEnums.length;for(var key in{"toString":null})hasDontEnumBug=false;Object.keys=function keys(object){if(typeof object!="object"&&typeof object!="function"||object===null)throw new TypeError("Object.keys called on a non-object");var keys=[];for(var name in object)if(owns(object,name))keys.push(name);if(hasDontEnumBug)for(var i=0,ii=dontEnumsLength;i<ii;i++){var dontEnum=dontEnums[i];if(owns(object,dontEnum))keys.push(dontEnum)}return keys}}var negativeDate=-621987552E5,negativeYearString="-000001";
if(!Date.prototype.toISOString||(new Date(negativeDate)).toISOString().indexOf(negativeYearString)===-1)Date.prototype.toISOString=function toISOString(){var result,length,value,year,month;if(!isFinite(this))throw new RangeError("Date.prototype.toISOString called on non-finite value.");year=this.getUTCFullYear();month=this.getUTCMonth();year+=Math.floor(month/12);month=(month%12+12)%12;result=[month+1,this.getUTCDate(),this.getUTCHours(),this.getUTCMinutes(),this.getUTCSeconds()];year=(year<0?"-":
year>9999?"+":"")+("00000"+Math.abs(year)).slice(0<=year&&year<=9999?-4:-6);length=result.length;while(length--){value=result[length];if(value<10)result[length]="0"+value}return year+"-"+result.slice(0,2).join("-")+"T"+result.slice(2).join(":")+"."+("000"+this.getUTCMilliseconds()).slice(-3)+"Z"};var dateToJSONIsSupported=false;try{dateToJSONIsSupported=Date.prototype.toJSON&&(new Date(NaN)).toJSON()===null&&(new Date(negativeDate)).toJSON().indexOf(negativeYearString)!==-1&&Date.prototype.toJSON.call({toISOString:function(){return true}})}catch(e){}if(!dateToJSONIsSupported)Date.prototype.toJSON=
function toJSON(key){var o=Object(this),tv=toPrimitive(o),toISO;if(typeof tv==="number"&&!isFinite(tv))return null;toISO=o.toISOString;if(typeof toISO!="function")throw new TypeError("toISOString property is not callable");return toISO.call(o)};if(!Date.parse||"Date.parse is buggy")Date=function(NativeDate){function Date(Y,M,D,h,m,s,ms){var length=arguments.length;if(this instanceof NativeDate){var date=length==1&&String(Y)===Y?new NativeDate(Date.parse(Y)):length>=7?new NativeDate(Y,M,D,h,m,s,ms):
length>=6?new NativeDate(Y,M,D,h,m,s):length>=5?new NativeDate(Y,M,D,h,m):length>=4?new NativeDate(Y,M,D,h):length>=3?new NativeDate(Y,M,D):length>=2?new NativeDate(Y,M):length>=1?new NativeDate(Y):new NativeDate;date.constructor=Date;return date}return NativeDate.apply(this,arguments)}var isoDateExpression=new RegExp("^"+"(\\d{4}|[+-]\\d{6})"+"(?:-(\\d{2})"+"(?:-(\\d{2})"+"(?:"+"T(\\d{2})"+":(\\d{2})"+"(?:"+":(\\d{2})"+"(?:\\.(\\d{3}))?"+")?"+"("+"Z|"+"(?:"+"([-+])"+"(\\d{2})"+":(\\d{2})"+")"+")?)?)?)?"+
"$");var months=[0,31,59,90,120,151,181,212,243,273,304,334,365];function dayFromMonth(year,month){var t=month>1?1:0;return months[month]+Math.floor((year-1969+t)/4)-Math.floor((year-1901+t)/100)+Math.floor((year-1601+t)/400)+365*(year-1970)}for(var key in NativeDate)Date[key]=NativeDate[key];Date.now=NativeDate.now;Date.UTC=NativeDate.UTC;Date.prototype=NativeDate.prototype;Date.prototype.constructor=Date;Date.parse=function parse(string){var match=isoDateExpression.exec(string);if(match){var year=
Number(match[1]),month=Number(match[2]||1)-1,day=Number(match[3]||1)-1,hour=Number(match[4]||0),minute=Number(match[5]||0),second=Number(match[6]||0),millisecond=Number(match[7]||0),offset=!match[4]||match[8]?0:Number(new NativeDate(1970,0)),signOffset=match[9]==="-"?1:-1,hourOffset=Number(match[10]||0),minuteOffset=Number(match[11]||0),result;if(hour<(minute>0||second>0||millisecond>0?24:25)&&minute<60&&second<60&&millisecond<1E3&&month>-1&&month<12&&hourOffset<24&&minuteOffset<60&&day>-1&&day<dayFromMonth(year,
month+1)-dayFromMonth(year,month)){result=((dayFromMonth(year,month)+day)*24+hour+hourOffset*signOffset)*60;result=((result+minute+minuteOffset*signOffset)*60+second)*1E3+millisecond+offset;if(-864E13<=result&&result<=864E13)return result}return NaN}return NativeDate.parse.apply(this,arguments)};return Date}(Date);if(!Date.now)Date.now=function now(){return(new Date).getTime()};if("0".split(void 0,0).length){var string_split=String.prototype.split;String.prototype.split=function(separator,limit){if(separator===
void 0&&limit===0)return[];return string_split.apply(this,arguments)}}if("".substr&&"0b".substr(-1)!=="b"){var string_substr=String.prototype.substr;String.prototype.substr=function(start,length){return string_substr.call(this,start<0?(start=this.length+start)<0?0:start:start,length)}}var ws="\t\n\x0B\f\r \u00a0\u1680\u180e\u2000\u2001\u2002\u2003"+"\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028"+"\u2029\ufeff";if(!String.prototype.trim||ws.trim()){ws="["+ws+"]";var trimBeginRegexp=
new RegExp("^"+ws+ws+"*"),trimEndRegexp=new RegExp(ws+ws+"*$");String.prototype.trim=function trim(){if(this===undefined||this===null)throw new TypeError("can't convert "+this+" to object");return String(this).replace(trimBeginRegexp,"").replace(trimEndRegexp,"")}}function toInteger(n){n=+n;if(n!==n)n=0;else if(n!==0&&n!==1/0&&n!==-(1/0))n=(n>0||-1)*Math.floor(Math.abs(n));return n}function isPrimitive(input){var type=typeof input;return input===null||type==="undefined"||type==="boolean"||type===
"number"||type==="string"}function toPrimitive(input){var val,valueOf,toString;if(isPrimitive(input))return input;valueOf=input.valueOf;if(typeof valueOf==="function"){val=valueOf.call(input);if(isPrimitive(val))return val}toString=input.toString;if(typeof toString==="function"){val=toString.call(input);if(isPrimitive(val))return val}throw new TypeError;}var toObject=function(o){if(o==null)throw new TypeError("can't convert "+o+" to object");return Object(o)}});

View File

@@ -0,0 +1,91 @@
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='Content-type' content='text/html; charset=utf-8'>
<title>Basic Example with JSX</title>
<link rel="stylesheet" href="../shared/css/base.css" />
<link rel="stylesheet" href="transition.css" />
</head>
<body>
<h1>Example with Transitions</h1>
<div id="container">
<p>
To install React, follow the instructions on
<a href="http://www.github.com/facebook/react/">GitHub</a>.
</p>
<p>
If you can see this, React is not working right.
If you checked out the source from GitHub make sure to run <code>grunt</code>.
</p>
</div>
<h4>Example Details</h4>
<ul>
<li>
This is built with
<a href="https://github.com/substack/node-browserify">browserify</a>.
</li>
<li>
This is written with JSX and transformed in the browser.
</li>
</ul>
<p>
</p>
<p>
Learn more at
<a href="http://facebook.github.io/react" target="_blank">facebook.github.io/react</a>.
</p>
<script src="../../build/react-with-addons.js"></script>
<script src="../../build/JSXTransformer.js"></script>
<script type="text/jsx">
/**
* @jsx React.DOM
*/
var TransitionGroup = React.addons.TransitionGroup;
var INTERVAL = 2000;
var AnimateDemo = React.createClass({
getInitialState: function() {
return {start: 0};
},
componentDidMount: function() {
this.interval = setInterval(this.tick, INTERVAL);
},
componentWillUnmount: function() {
clearInterval(this.interval);
},
tick: function() {
this.setState({start: this.state.start + 1});
},
render: function() {
var children = [];
var pos = 0;
var colors = ['red', 'gray', 'blue'];
for (var i = this.state.start; i < this.state.start + 3; i++) {
var style = {
left: pos * 128,
background: colors[i % 3]
};
pos++;
children.push(<div key={i} className="animateItem" style={style}>{i}</div>);
}
return (
<TransitionGroup
className="animateExample"
transitionName="example">
{children}
</TransitionGroup>
);
}
});
React.renderComponent(
<AnimateDemo />,
document.getElementById('container')
);
</script>
</body>
</html>

View File

@@ -0,0 +1,44 @@
.example-enter,
.example-leave {
-webkit-transition: all .25s;
transition: all .25s;
}
.example-enter,
.example-leave.example-leave-active {
opacity: 0.01;
}
.example-leave.example-leave-active {
margin-left: -128px;
}
.example-enter {
margin-left: 128px;
}
.example-enter.example-enter-active,
.example-leave {
margin-left: 0;
opacity: 0.99;
}
.animateExample {
display: block;
height: 128px;
position: relative;
width: 384px;
}
.animateItem {
color: white;
font-size: 36px;
font-weight: bold;
height: 128px;
line-height: 128px;
position: absolute;
text-align: center;
-webkit-transition: all .25s; /* TODO: make this a move animation */
transition: all .25s; /* TODO: make this a move animation */
width: 128px;
}

View File

@@ -10,7 +10,7 @@
<div id="container">
<p>
To install React, follow the instructions on
<a href="http://www.github.com/facebook/react.js/">GitHub</a>.
<a href="http://www.github.com/facebook/react/">GitHub</a>.
</p>
<p>
If you can see this, React is not working right.

View File

@@ -37,14 +37,16 @@ function minify(src) {
// TODO: move this out to another build step maybe.
function bannerify(src) {
var version = grunt.config.data.pkg.version;
return LICENSE_TEMPLATE.replace('@PACKAGE@', this.data.standalone)
var packageName = this.data.packageName || this.data.standalone;
return LICENSE_TEMPLATE.replace('@PACKAGE@', packageName)
.replace('@VERSION@', version) +
'\n' + src;
}
function simpleBannerify(src) {
var version = grunt.config.data.pkg.version;
return SIMPLE_TEMPLATE.replace('@PACKAGE@', this.data.standalone)
var packageName = this.data.packageName || this.data.standalone;
return SIMPLE_TEMPLATE.replace('@PACKAGE@', packageName)
.replace('@VERSION@', version) +
'\n' + src;
}
@@ -76,8 +78,27 @@ var transformer = {
after: [simpleBannerify]
};
var addons = {
entries: [
'./build/modules/ReactWithAddons.js'
],
outfile: './build/react-with-addons.js',
debug: false,
standalone: 'React',
packageName: 'React (with addons)',
after: [simpleBannerify]
};
var addonsMin = grunt.util._.merge({}, addons, {
outfile: './build/react-with-addons.min.js',
debug: false,
after: [minify, bannerify]
});
module.exports = {
basic: basic,
min: min,
transformer: transformer
transformer: transformer,
addons: addons,
addonsMin: addonsMin
};

View File

@@ -1,6 +0,0 @@
{
"debug": true,
"constants": {
"__DEV__": true
}
}

View File

@@ -1,12 +1,25 @@
'use strict';
var grunt = require('grunt');
var rootIDs = [
"React"
"React",
"ReactWithAddons"
];
var getDebugConfig = function() {
return {
"debug": true,
"constants": {
"__VERSION__": grunt.config.data.pkg.version,
"__DEV__": true
}
};
};
var debug = {
rootIDs: rootIDs,
configFile: "grunt/config/jsx/debug.json",
getConfig: getDebugConfig,
sourceDir: "src",
outputDir: "build/modules"
};
@@ -15,7 +28,7 @@ var jasmine = {
rootIDs: [
"all"
],
configFile: debug.configFile,
getConfig: getDebugConfig,
sourceDir: "vendor/jasmine",
outputDir: "build/jasmine"
};
@@ -25,18 +38,37 @@ var test = {
"test/all.js",
"**/__tests__/*.js"
]),
configFile: "grunt/config/jsx/test.json",
getConfig: function() {
return {
"debug": true,
"mocking": true,
"constants": {
"__VERSION__": grunt.config.data.pkg.version,
"__DEV__": true
}
};
},
sourceDir: "src",
outputDir: "build/modules"
};
var release = {
rootIDs: rootIDs,
configFile: "grunt/config/jsx/release.json",
getConfig: function() {
return {
"debug": false,
"constants": {
"__VERSION__": grunt.config.data.pkg.version,
"__DEV__": false
}
};
},
sourceDir: "src",
outputDir: "build/modules"
};
module.exports = {
debug: debug,
jasmine: jasmine,

View File

@@ -1,6 +0,0 @@
{
"debug": false,
"constants": {
"__DEV__": false
}
}

View File

@@ -1,7 +0,0 @@
{
"debug": true,
"mocking": true,
"constants": {
"__DEV__": true
}
}

View File

@@ -1 +0,0 @@
module.exports = '0.6.0';

View File

@@ -24,10 +24,10 @@ module.exports = function() {
});
args.push.apply(args, rootIDs);
args.push("--config", config.configFile);
args.push("--config" /* from stdin */);
var child = spawn({
cmd: "bin/jsx",
cmd: "bin/jsx-internal",
args: args
}, function(error, result, code) {
if (error) {
@@ -38,6 +38,9 @@ module.exports = function() {
}
});
child.stdin.write(JSON.stringify(config.getConfig()));
child.stdin.end();
child.stdout.pipe(process.stdout);
child.stderr.pipe(process.stderr);
};

View File

@@ -1,7 +1,6 @@
'use strict';
var assert = require("assert");
var fs = require("fs");
var grunt = require("grunt");
var spawn = grunt.util.spawn;
var semver = require("semver");
@@ -59,13 +58,11 @@ module.exports = function() {
var config = this.data;
var done = this.async();
fs.chmod(phantomjs, 755, function(err) {
spawn({
cmd: phantomjs,
args: ["--version"]
}, function(error, result, code) {
checkVersion(error, result, code);
run(config, done);
});
spawn({
cmd: phantomjs,
args: ["--version"]
}, function(error, result, code) {
checkVersion(error, result, code);
run(config, done);
});
};

View File

@@ -7,7 +7,10 @@ var grunt = require('grunt');
var BOWER_PATH = '../react-bower/';
var BOWER_GLOB = [BOWER_PATH + '*'];
var BOWER_FILES = ['react.js', 'react.min.js', 'JSXTransformer.js'];
var BOWER_FILES = [
'react.js', 'react.min.js', 'JSXTransformer.js',
'react-with-addons.js', 'react-with-addons.min.js'
];
var GH_PAGES_PATH = '../react-gh-pages/';
var GH_PAGES_GLOB = [GH_PAGES_PATH + '*'];

View File

@@ -2,7 +2,7 @@
var React = require('./build/modules/React');
var visitors = require('./vendor/fbtransform/visitors').transformVisitors;
var transform = require('./vendor/fbtransform/lib/transform').transform;
var transform = require('jstransform').transform;
module.exports = {
React: React,

1317
npm-shrinkwrap.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{
"name": "react-tools",
"version": "0.5.0-alpha",
"version": "0.5.1",
"keywords": [
"react",
"jsx",
@@ -20,6 +20,7 @@
"main.js",
"bin/jsx",
"build/modules/",
"src/",
"vendor/fbtransform/",
"vendor/constants.js"
],
@@ -35,25 +36,24 @@
"test": "grunt build && grunt test"
},
"dependencies": {
"base62": "~0.1.1",
"commoner": "~0.8.4",
"esprima": "https://github.com/facebook/esprima/tarball/a3e0ea3979eb8d54d8bfade220c272903f928b1e",
"recast": "~0.4.8",
"source-map": "~0.1.22"
"esprima-fb": "~1001.1001.2000-dev-harmony-fb",
"jstransform": "~1.0.1"
},
"devDependencies": {
"browserify": "~2.24.1",
"browserify": "~2.34.1",
"wrapup": "~0.12.0",
"populist": "~0.1.3",
"grunt-cli": "~0.1.9",
"grunt": "~0.4.1",
"grunt-contrib-copy": "~0.4.1",
"grunt-contrib-jshint": "~0.6.0",
"optimist": "~0.4.0",
"phantomjs": ">= 1.9.0",
"semver": "~2.0.0",
"uglify-js": "~2.3.6",
"grunt-contrib-clean": "~0.4.1",
"optimist": "~0.6.0",
"phantomjs": "~1.9.1-4",
"recast": "~0.4.16",
"semver": "~2.1.0",
"uglify-js": "~2.4.0",
"grunt-contrib-clean": "~0.5.0",
"grunt-compare-size": "~0.4.0",
"gzip-js": "~0.3.2",
"tmp": "~0.0.18",

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