Question:
I'm trying to programatically invoke the JSX transformer (using the version of in the npm registry) by running something like Which then throws this error: If I comment out the lines in that require/use the module loads fine and the transformer runs correctly.
Bah, I changed build filenames last minute and didn't properly test the module after :( Thanks for finding this! I guess we should write some tests for the node module too, not just our phantomjs tests. (Very) Short term, you should be able to change to and that will fix the problem. - I guess it's time to figure out what we want to do with npm versions vs library versions. Should we just bump them both for the time being?
Nope, that alone won't do it, we're not even packaging. I totally screwed up the node module :( Fix soon!
Yeah, doesn't look like there's even a directory there. :)

'use strict'; <del> var React = require('./build/React'); </del> <ins> var React = require('./build/react'); </ins> var visitors = require('./vendor/fbtransform/visitors').transformVisitors; var transform = require('./vendor/fbtransform/lib/transform').transform;

"README.md", "main.js", "bin/jsx", <del> "build/React.js", </del> <ins> "build/react.js", </ins> "vendor/fbtransform/", "vendor/woodchipper.js" ],


Question:
Please make "requireable" npm release, already fixed and only new version on npm is needed. I've developed a source transform for JSX for browserify — which doesn't work properly because of
1 pushed to npm:

} async function createBundle(bundle, bundleType) { <del> if (shouldSkipBundle(bundle, bundleType)) { return; } </del> const filename = getFilename(bundle, bundleType); const logKey = chalk.white.bold(filename) + chalk.dim(` (${bundleType.toLowerCase()})`);

); } <ins> bundles = bundles.filter(([bundle, bundleType]) => { return !shouldSkipBundle(bundle, bundleType); }); </ins> if (process.env.CIRCLE_NODE_TOTAL) { // In CI, parallelize bundles across multiple tasks. const nodeTotal = parseInt(process.env.CIRCLE_NODE_TOTAL, 10);


Question:
Trying to run jsx to build into a subdir seems to just exit with no error message: (public/js does exist) However, if run in directly in public it works without a hitch:
Are there any files in yet? Also potentially useful: what are you running, and what OS?
There is a file in src which builds when not using a subdir in the public dir. node version is 0.8.23 and im on OS X Mountain Lion
Installed 0.8.23 but no luck reproducing. Will try on a Mountain Lion machine tomorrow. Thanks for the report. Do you see this failure with an empty file? If using an empty file makes the failure go away, perhaps you can try cutting out different parts of the file to figure out the minimal contents that trigger the failure? It could be a problem with on Mountain Lion, though. That's my hunch.
One more idea: the module cache might have gotten into a bad state somehow. Try clearing it by deleting the directory ?
The same file builds fine if I use (note the lack of public/js). Deleting that directory didn't work for me.
I know this is still broken. Still working on a fix.
:heart:
I had same problem on ubuntu. Yesterday "jsx --watch" worked just fine for me. Today when I ssh-ed again and ran "jsx --watch reactjs/ js/" it just silently does nothing.
- I was having issues w/ vim file writes not being caught so I hacked together - Feel free to try it and let me know if it works (Haven't had the time to test on Ubuntu yet...) - We might use the file watcher in that repo in Commoner / JSX in the future.
:+1: Work like a charm. Thank you very much!
Ok. I think I now know what the issue is. jsx created a file in the output directory. If that file is still there when running jsx again it will quick silently.
Awesome!

}, "dependencies": { "base62": "~0.1.1", <del> "commoner": "~0.8.0", </del> <ins> "commoner": "~0.8.3", </ins> "esprima": "https://github.com/facebook/esprima/tarball/a3e0ea3979eb8d54d8bfade220c272903f928b1e", "recast": "~0.4.8", "source-map": "~0.1.22"


Question:
Basically what the title says. After install react-tools, using jsx -w <srcdir<destdirwill correctly detect existing files (but not transform them), and upon any write to any watched file jsx will exit with error code 1. Commoner tests all pass. Exact steps I followed, in Ubuntu 12.10: 0) Install via manual instructions at for Ubuntu/Mint 1) Install react-tools with 'sudo npm install -g react-tools' 2) Create file in <src, as described by the Getting Started tutorial. 3) In a new terminal, jsx -w <src<dest4) Edit and add a comment. 5) Notice that jsx exited, echo $? prints 1. akrieger ls js/ akrieger ls html/js/ akrieger jsx -w js/ html/js/ ["helloworld"] <edit , save editakrieger 1 akrieger ls html/js/ akrieger
Hypothesis: The only thing that keeps commoner from exiting in mode right now is the option passed to . That means the process will stay alive while there are any files left to watch. But some text editors save files by deleting and then re-writing them, which causes to un-watch the file (because the original inode that inotify cared about got discarded). When there's only one file, unwatching it causes Node to think no files need to be watched, so the process exits. cc
Opened a new Commoner issue: Even though said the Commoner tests pass for him, that's only because mode test coverage is… lacking. :frowning:
That didn't seem to work for me, unless the file is supposed to be a valid JSX file with something to transform.
It also doesn't solve the issue that jsx doesn't seem to be doing any static transformation anyway, even in the example getting started tutorial.
That's another regrettable but known issue: I suspect you're missing the comment at the top of the file (which won't be necessary soon, but currently is still important). cc
I copy pasted the sample code exactly: <code/ React.DOM */ React.renderComponent( blah blah );</code
Just to try something else: can take a single file name on the command line: . Does that also not show any transformations? Or did you try that already?
bin/jsx does the right thing.
Furthermore, if I have a file named in the destination directory, it is deleted when I try to run jsx on the source and dest directory, in either watch or go mode.
The deletion is by design, at least. The files that end up in the output directory are actually hard-linked with master versions that are kept (by default) in . Each build unlinks and then relinks the files in the output directory, so if the relink fails it will look like the file was just deleted. Not sure why the relinking might be failing. In case is on a different device from , you could try relocating the cache:
Yeah, they are on different devices. Moving the cache dir worked. Thanks!
Accidental close, sorry. Still need to mitigate that cache dir problem.
How important is the cache behavior? Could we disable it? I'd trade perf for ease of use with this tool
:thumbsup: to what said. I'd also take defaulting the cachedir to the src/current dir (I think this is how sass does it's cache)
pretty important; the incremental speedup is significant for a codebase the size of It's a one-line change to switch the default location, and it won't break anything for anyone. Kicking myself now because I actually considered whether ~/.commoner was likely ever to be a different device, and clearly I guessed wrong :(
I wonder if the requirements that we need for the react codebase are the same as those for end users. I think most people just want a simple syntax transform and watcher ala coffee script.
Also +1 on just moving the cache dir :)
true, but I don't think we can pretend that is a fully-featured source transform tool if it doesn't do any caching (coffeescript and sass clearly suggest that caching is worthwhile for enough people) The original location of the cache directory was , but I moved it when I support for printing the transformed code to STDIN, in which case there's no . Definitely okay with skipping the cache logic in that case.
So I've been looking through various implementations of Dir watchers (gaze, chokidar) in NodeJS and they're all pretty clowny - a pretty easy test case that breaks them is making a new directory and adding files to that directory. So since someone on the internet was wrong, I wrote another FS watcher last night that I think is way more stable: I'll try to merge this new file watcher with the transformer I made a couple days ago () and see what happens just as proof of concept. - I'll probably have something for you to play w/ in an hour or two =]
I had pretty good results with a makefile and running make every 2s :P
now you're trolling me :P
I can't wait.
Not trolling; it's very reliable and easy to reason about. Is comparing file mtimes to determine if they need to be rebuilt bad relative to a module cache?
give a shot - still a work-in-progress, but lmk how it goes
Dear Your question deserves a careful response. I know this looks long-winded, but if you read it through you'll know everything that I was thinking. The primary virtue of the module cache is that the cache filenames are hashes of all the relevant input variables: source, module name, build steps, configuration properties, Commoner version, and more. Change any one of those input variables and you get a different hash. If you find a file called in the module cache, you can be completely certain that the cached file contains the right contents. I believe that's a useful guarantee. A secondary benefit is that old versions of a file don't go away just because the file was recently rebuilt. If you revert a file to a version that has ever been built before, you don't have to rebuild it again. In order to make the same promise under the strategy, you'd have to find some way of storing all those distinct versions, and I'm confident the method you would come up with would closely resemble my hashing strategy. It's what every sensible version control system does. The goal of both strategies is to determine whether you can trust the contents of a file that was built some time in the past. This decision is completely reliable under a hashing strategy, and if it ever fails then there must be some additional piece of information that you neglected to incorporate into the hash. None of the bugs that I've fixed in Commoner had anything to do with module cache inconsistency. When's the last time you had to wipe your module cache? And no, doesn't qualify, because I made sure it left the cache untouched. With that background, let me answer your orginal question: "Is comparing file s to determine if they need to be rebuilt bad relative to a module cache?" Yes, because the only input variables considered by the strategy are (name of source file, of source file), which allows you to avoid rebuilding the file if corresponding output file has a later , and know no other input variables have changed in the meantime, such as build steps, configuration properties, new files /removed whose presence/absence affects the build, independent build processes racing to update files in the output directory, etc. Requirement 1 is too strong because you don't necessarily have to rebuild source files that appear newer than their output files (see my second paragraph above). Requirement 2 is too strong because you don't have to "know" any of those things if they can be accounted for automatically, as they are under the hashing strategy. Is the strategy good enough? Maybe it is for you, because you know how to spot signs of inconsistency and you have trained yourself to predict when a is finally necessary. I don't think we can expect the same of new users of React. They're much more likely to attribute subtle problems to the library itself instead of guessing that the build tool messed up. Sometimes we reinvent the wheel just so that we know exactly how the wheel we're using works, quirks and all. I'm guilty of this myself, but in my defense I really am trying to get us to a point where we don't have to make any apologies at all for the way our tools work. I know there are still bugs in Commoner, but I'm committed to squashing all of them.
I'm not hating on commoner. It's an excellent CommonJS build system and is totally the right choice to build react and any jsx project that uses CommonJS modules with transforms. The problem is that users think it is a simple syntax transform (like coffee?) when in reality it doesn't behave that way. Specifically it assumes that everything you're desugaring is a CommonJS module and it assumes specifics of the implementations path resolution methods, which in requirejs, browserify and haste are all different, by relativizing. If you aren't using CommonJS and define your own unrelated require() function the arguments will get rewritten, weird missing module warnings will fire and fake modules will be created. It's actually really freaking awesome to have this tooling for CommonJS projects but really confusing if you're not in a CommonJS project or using a different module resolver. Some of the annoyances we've with r.js are because it tries to be too clever in this area (we have eval('req'+'uire')(...) somewhere in the insta codebase because of this). As a user since I know jsx is willing to rewrite my code I find it hard to predict exactly how it will transform. What if instead jsx had a --relativize option that we disabled by default and it just treated everything like a file and transformed it, either with a cache or based on mtime? We'd continue to use the option on react itself and perhaps even advertise commoner+a browser packager (brigade?) as our recommended module system since they'll likely want debranching and other goodies even though they don't know it yet :)
The original issue still needs fixing, by the way. Still working on that.
One of the reasons I was not able to get the jsx transformed files was I didnt close the terminal window first time after installation. I closed the terminal window and re-opened it again and then I was able to transform any JSX file located anywhere on my disk to any folder. :) possible solution.

}, "dependencies": { "base62": "~0.1.1", <del> "commoner": "~0.8.0", </del> <ins> "commoner": "~0.8.3", </ins> "esprima": "https://github.com/facebook/esprima/tarball/a3e0ea3979eb8d54d8bfade220c272903f928b1e", "recast": "~0.4.8", "source-map": "~0.1.22"


Question:
:+1:
+1
+1
I'mma jump on the :+1: bandwagon too. Great idea.
I don't want to keep duplicated issues opened so just to sumup: said it makes sense to implement "namespacing" using colons as opt-in, config-defined option, where one of the possibilities would be a member expression. I don't have enough time to implement it this way, so I closed my issue. More on why&how in jeffmo's final comment and in in general
+1
+1
A non JavaScript-first implementation that wouldn't require changes to :
PR landing for JSX member expressions , can close this.

utils.catchup(openingElement.range[0], state, trimLeft); <del> if (nameObject.namespace) { throw new Error( 'Namespace tags are not supported. ReactJSX is not XML.'); </del> <ins> var isFallbackTag = false; if (nameObject.type === Syntax.XJSIdentifier) { if (nameObject.namespace) { throw new Error( 'Namespace tags are not supported. ReactJSX is not XML.'); } isFallbackTag = FALLBACK_TAGS.hasOwnProperty(nameObject.name); </ins> } <del> var isFallbackTag = FALLBACK_TAGS.hasOwnProperty(nameObject.name); utils.append( (isFallbackTag ? jsxObjIdent + '.' : '') + (nameObject.name) + '(', state ); </del> <ins> utils.append(isFallbackTag ? jsxObjIdent + '.' : '', state); utils.move(nameObject.range[0], state); utils.catchup(nameObject.range[1], state); </ins> <del> utils.move(nameObject.range[1], state); </del> <ins> utils.append('(', state); </ins> var hasAttributes = attributesObject.length;


Question:
http://www.polymer- needs nonstandard touch-action attribute to work. Btw, I don't know why React just don't render anything what user needs? Custom attributes should work OFTB. For control freaks there can be option React.doesNotAllowUnknownAttributtes = true.
Please allow touch-action attribute.
React needs a list of properties so that it knows whether to use the property accessor or setAttribute when changing the attribute (and also to convert between camel-casing and dash-cased, though that's not as critical). We'd like to make it easy to configure React with custom attributes; sorry this isn't easy right now.
It seems your other issue addresses this concern already and I don't see React adding this specific attribute to the global whitelist.

title: React API layout: docs prev: mixins.html <ins> next: jsx-is-not-html.html </ins> --- ## React

--- id: docs-jsx-is-not-html title: JSX is not HTML description: Differences between JSX and HTML. layout: docs prev: api.html --- JSX looks like HTML but there are some important differences you may run into. ## Whitespace removal JSX doesn't follow the same whitespace elimination rules as HTML. JSX removes all the whitespaces between two curly braces expressions. If you want to have a white space, a work-around is to add `{' '}`. ```javascript <div>{this.props.name} {' '} {this.props.surname}</div> ``` This behavior is still being debated. Follow [Issue #65](https://github.com/facebook/react/issues/65) to be updated on the situation. ## HTML Entities You can insert HTML entities within literal text in JSX: ```javascript <div>First · Second</div> ``` If you want to display an HTML entity within a dynamic content, you will run into double escaping issues as React escapes all the strings you are displaying in order to prevent a wide range of XSS attacks by default. ```javascript // Bad: It displays "First · Second" <div>{'First · Second'}</div> ``` There are various ways to work-around this issue. The easiest one is to write unicode character directly in Javascript. You've got to make sure that the file is saved as UTF-8 and that the propers UTF-8 directives are set so the browser will display it correctly. ```javascript <div>{'First · Second'}</div> ``` A safer alternative is to find the unicode number corresponding to the entity and use it inside of a Javascript string. ```javascript <div>{'First u00b7 Second'}</div> <div>{'First ' + String.fromCharCode(183) + ' Second'}</div> ``` You can use mixed arrays with strings and JSX elements. ```javascript <div>{['First ', <span>·</span>, ' Second']}</div> ``` In last resort, you always have the ability to insert raw HTML inside of the div. ```javascript <div dangerouslySetInnerHTML={{'{{'}}__html: 'First · Second'}} /> ``` ## Comments JSX supports both single-line and multi-lines Javascript comments within a tag declaration: ```javascript <div // This is a single line comment: /* And a multiline comment */ /> ``` As of React 0.3, there is no good way to insert comments within the children section. [Issue #82](https://github.com/facebook/react/issues/82) is tracking progress to enable the following way to write comments: ```javascript // Note: The following is not implemented yet! <div> {/* This is a comment */} </div> ``` ## Custom HTML attributes If you pass properties to native HTML elements that do not exist in the HTML specification, React will not render them. If you want to use a custom attribute, you should prefix it with `data-`. ```javascript <div data-custom-attribute="foo" /> ``` [Web Accessibility](http://www.w3.org/WAI/intro/aria) attributes starting with `aria-` will be rendered properly. ```javascript <div aria-hidden={true} /> ```


Question:
Someone had the trouble in IRC about it. Edit: changed the subject from "document it" to "support it", because the documentation issue is already at .
Better yet, support it!
Yeah, is there a particular reason it's not supported?
Curious if you've seen the . It's automatically injected into React by default, so you can use it today. IMHO it's (much) better than . (I suppose we could support just for the sake of completeness, but I thought I'd just make sure you guys were aware of .)
We discussed this for a bit on IRC -- was just confused that silently didn't work whereas other events did -- perhaps adding more documentation () will fix the problem too but it seems like we might as well add for completeness. (I agree that enter/leave are much more useful and suggested that over/out are likely missing simply because no one has needed them!)
Agree - I believe there are a few extra allocations (not-pooled) occuring in the event system already today. I'd love to track those down before adding more mouse-move event allocations. If you open the memory profiler in Chrome and move the mouse around, you'll see memory being allocated (and then properly freed of course) but if we use es everywhere, we should be flat. That would make me much more comfortable with adding to . Edit: Just checked out - we already have which fires way more frequently than would so it's probably not such a big deal to add - though we really should get rid of all additional allocations in the event path.
Just started to look a little bit into the allocations here. Redefining trapBubbledEvent in ReactEventEmitter with: still shows allocations in the Chrome memory timeline view, so I'm not convinced that there's anything we can do here? (Replacing trapBubbledEvent itself with a noop makes the allocations go away. simply calls addEventListener.)
I am pretty sure we have done all we can here -- at least I think we've tracked down every callsite where PooledClass would have helped us. I updated our recast transforms to log every syntax construct that would cause an obvious allocation and couldn't find anything. I was thinking maybe there was an array slice or a bind() in there, but experiment shows that this is not the case.
(I didn't verify that we don't have more allocations than the empty-function case; I don't know of a good way to do so.)
I might be misinformed, but isn't there quite a difference in use cases between mouseenter and mouseover events? Here's a theoretical (non-react) example working with some hover states for nested elements: I tried to apply the above concept in react (with nested components) using onMouseEnter instead, but it obviously fails because it's only triggered once on the top-most element. Moving into a child element and back has no effect. Maybe there's a better approach for this in react altogether?
If you render the child hierarchy with React, you can listen to on each child element you are interested in instead of using event bubbling. It is cheap.

``` onClick onDoubleClick onDrag onDragEnd onDragEnter onDragExit onDragLeave onDragOver onDragStart onDrop onMouseDown onMouseEnter onMouseLeave <del> onMouseMove onMouseUp </del> <ins> onMouseMove onMouseOut onMouseOver onMouseUp </ins> ``` Properties:

captured: keyOf({onMouseMoveCapture: true}) } }, <ins> mouseOut: { phasedRegistrationNames: { bubbled: keyOf({onMouseOut: true}), captured: keyOf({onMouseOutCapture: true}) } }, mouseOver: { phasedRegistrationNames: { bubbled: keyOf({onMouseOver: true}), captured: keyOf({onMouseOverCapture: true}) } }, </ins> mouseUp: { phasedRegistrationNames: { bubbled: keyOf({onMouseUp: true}),

topKeyUp:       eventTypes.keyUp, topMouseDown:   eventTypes.mouseDown, topMouseMove:   eventTypes.mouseMove, <ins> topMouseOut:    eventTypes.mouseOut, topMouseOver:   eventTypes.mouseOver, </ins> topMouseUp:     eventTypes.mouseUp, topPaste:       eventTypes.paste, topScroll:      eventTypes.scroll,

case topLevelTypes.topDoubleClick: case topLevelTypes.topMouseDown: case topLevelTypes.topMouseMove: <ins> case topLevelTypes.topMouseOut: case topLevelTypes.topMouseOver: </ins> case topLevelTypes.topMouseUp: EventConstructor = SyntheticMouseEvent; break;


Question:
reported the following issue on IRC: (Both on master and 4.0) The repro case is: 1) Render 2) Render 3) Render the same as 1) The div has its innerHTML empty instead of . I don't really know what's going on. can you guys look at it?
One other tidbit: this only seems to happen when the value is exactly the same in step 3 as it was in step 1. If it's different (i.e. ), things work as expected.
What happens if you change step 2 to a instead of a ? It works, right?
I just reduced the test case to 19 lines.
yeah changing 2) to use a span works as expected
If anyone wants to look into this, the bug is probably here
I cannot reproduce what you are seeing: It also bugs if I use a different string
I'm not able to reproduce that particular behavior given this small repro case. The original code had several more layers... will keep trying.
I know this is a very old issue but I had a similar problem and came across this. I found that this problem occurs when you do not add a property to the React component containing the property. So, does not seem to work reproducibly, whereas seems to. I think this could be related to React's diffing algorithm that might not properly treat a component with a statement if that component gets rerendered multiple times with different inner content. Just posting this here in case other people have the same issue and stumble upon this.
thx you saved my day :-)
Seems like the issue is back again. Thanks, solves the problem for me too.
If any of you can post a simple repro case showing the broken behavior here, I'd be happy to take a look at fixing it.
Took me a while to repro, but here you go: (ugly, but demonstrates the issue well)
Thanks. This is the same issue as . No fix currently, but using the key as a workaround is fine and I'll see if we can fix this sometime.
Thanks that was giving me fits!
If anyone is still seeing issues on 0.14, please make a new issue with a simple repro case.
I have this issue, but can't reproduce in a simple example - my original code is layered and I think that's the reason the real DOM doesn't reconcile. In the react debugger is looks as dangerouslySetInnerHTML has proper __html value, but it doesn't equeal to the innerHTML of the actual element. I used an extremely simple (and equally nasty) workaround. Writing it here just in case it will help someone:
Reading out will rarely give you what you put in because the browser does various kinds of normalization on it. If you can repro with a standalone example though I'm happy to take a look.
well, that's more like a control shot :-)
Looks like the issue still exist in 16.4.1 when using on a tag, you cannot nest other or . issue is fixed by replacing the container with a
If you experience something similar three years later, and the original issue is closed, you can be sure it's a different unrelated issue. :-) Please file a new one. We don't keep track of closed issues so your feedback is unfortunately going into the void. When filing a new issue, please provide a reproducing example. when using dangerouslySetInnerHTML on a tag, you cannot nest other or This sounds like browsers work. You can't nest into . This is why React warns when you do it (except in which case React can't validate it).

*/ var textContentAccessor = getTextContentAccessor() || 'NA'; <ins> var LEADING_SPACE = /^ /; </ins> /** * Operations used to process updates to DOM nodes. This is made injectable via * `ReactComponent.DOMIDOperations`.

}, /** <del> * Updates a DOM node's innerHTML set by `props.dangerouslySetInnerHTML`. </del> <ins> * Updates a DOM node's innerHTML. </ins> * * @param {string} id ID of the node to update. <del> * @param {object} html An HTML object with the `__html` property. </del> <ins> * @param {string} html An HTML string. </ins> * @internal */ updateInnerHTMLByID: function(id, html) { var node = ReactMount.getNode(id); // HACK: IE8- normalize whitespace in innerHTML, removing leading spaces. // @see quirksmode.org/bugreports/archives/2004/11/innerhtml_and_t.html <del> node.innerHTML = (html && html.__html || '').replace(/^ /g, ' '); </del> <ins> node.innerHTML = html.replace(LEADING_SPACE, ' '); </ins> }, /**

// For quickly matching children type, to test if can be treated as content. var CONTENT_TYPES = {'string': true, 'number': true}; <del> var DANGEROUSLY_SET_INNER_HTML = keyOf({dangerouslySetInnerHTML: null}); </del> var STYLE = keyOf({style: null}); /**

styleUpdates[styleName] = ''; } } <del> } else if (propKey === DANGEROUSLY_SET_INNER_HTML) { // http://jsperf.com/emptying-speed ReactComponent.DOMIDOperations.updateTextContentByID( this._rootNodeID, '' ); </del> } else if (registrationNames[propKey]) { deleteListener(this._rootNodeID, propKey); <del> } else { </del> <ins> } else if ( DOMProperty.isStandardName[propKey] || DOMProperty.isCustomAttribute(propKey)) { </ins> ReactComponent.DOMIDOperations.deletePropertyByID( this._rootNodeID, propKey

// Relies on `updateStylesByID` not mutating `styleUpdates`. styleUpdates = nextProp; } <del> } else if (propKey === DANGEROUSLY_SET_INNER_HTML) { var lastHtml = lastProp && lastProp.__html; var nextHtml = nextProp && nextProp.__html; if (lastHtml !== nextHtml) { ReactComponent.DOMIDOperations.updateInnerHTMLByID( this._rootNodeID, nextProp ); } </del> } else if (registrationNames[propKey]) { putListener(this._rootNodeID, propKey, nextProp); } else if (

_updateDOMChildren: function(lastProps, transaction) { var nextProps = this.props; <del> var lastUsedContent = </del> <ins> var lastContent = </ins> CONTENT_TYPES[typeof lastProps.children] ? lastProps.children : null; <del> var contentToUse = </del> <ins> var nextContent = </ins> CONTENT_TYPES[typeof nextProps.children] ? nextProps.children : null; <ins> var lastHtml = lastProps.dangerouslySetInnerHTML && lastProps.dangerouslySetInnerHTML.__html; var nextHtml = nextProps.dangerouslySetInnerHTML && nextProps.dangerouslySetInnerHTML.__html; </ins> // Note the use of `!=` which checks for null or undefined. <ins> var lastChildren = lastContent != null ? null : lastProps.children; var nextChildren = nextContent != null ? null : nextProps.children; </ins> <del> var lastUsedChildren = lastUsedContent != null ? null : lastProps.children; var childrenToUse = contentToUse != null ? null : nextProps.children; </del> <ins> // If we're switching from children to content/html or vice versa, remove // the old content var lastHasContentOrHtml = lastContent != null || lastHtml != null; var nextHasContentOrHtml = nextContent != null || nextHtml != null; if (lastChildren != null && nextChildren == null) { this.updateChildren(null, transaction); } else if (lastHasContentOrHtml && !nextHasContentOrHtml) { this.updateTextContent(''); } </ins> <del> if (contentToUse != null) { var childrenRemoved = lastUsedChildren != null && childrenToUse == null; if (childrenRemoved) { this.updateChildren(null, transaction); } if (lastUsedContent !== contentToUse) { this.updateTextContent('' + contentToUse); </del> <ins> if (nextContent != null) { if (lastContent !== nextContent) { this.updateTextContent('' + nextContent); </ins> } <del> } else { var contentRemoved = lastUsedContent != null && contentToUse == null; if (contentRemoved) { this.updateTextContent(''); </del> <ins> } else if (nextHtml != null) { if (lastHtml !== nextHtml) { ReactComponent.DOMIDOperations.updateInnerHTMLByID( this._rootNodeID, nextHtml ); </ins> } <del> this.updateChildren(flattenChildren(nextProps.children), transaction); </del> <ins> } else if (nextChildren != null) { this.updateChildren(flattenChildren(nextChildren), transaction); </ins> } },

ReactDOMIDOperations.updateInnerHTMLByID( 'testID', <del> {__html: ' testContent'} </del> <ins> ' testContent' </ins> ); expect(

it("should empty element when removing innerHTML", function() { var stub = ReactTestUtils.renderIntoDocument(

  ); expect(stub.getDOMNode().innerHTML).toEqual(':)');

expect(stub.getDOMNode().innerHTML).toEqual(''); });  it("should transition from string content to innerHTML", function() { var stub = ReactTestUtils.renderIntoDocument(
hello
 ); expect(stub.getDOMNode().innerHTML).toEqual('hello'); stub.receiveProps( {dangerouslySetInnerHTML: {__html: 'goodbye'}}, transaction ); expect(stub.getDOMNode().innerHTML).toEqual('goodbye'); }); it("should transition from innerHTML to string content", function() { var stub = ReactTestUtils.renderIntoDocument(
 ); expect(stub.getDOMNode().innerHTML).toEqual('bonjour'); stub.receiveProps({children: 'adieu'}, transaction); expect(stub.getDOMNode().innerHTML).toEqual('adieu'); });  it("should not incur unnecessary DOM mutations", function() { var stub = ReactTestUtils.renderIntoDocument(
);


Question:
This makes it basically unusable in any nontrivial project. While people shouldn't be using this in production, we should still fix this bug for newbies and people using it for hackathons.
This should be relatively easy. What should we do with inline tags?

var inlineScriptCount = 0; <ins> // This method returns a nicely formated line of code pointing the // exactly location of the error `e`. // The line is limited in size so big lines of code are also shown // in a readable way. // Example: // // ... x', overflow:'scroll'}} id={} onScroll={this.scroll} class=" ... //                                 ^ var createSourceCodeErrorMessage = function(code, e) { var sourceLines = code.split('n'); var erroneousLine = sourceLines[e.lineNumber - 1]; // Removes any leading indenting spaces and gets the number of // chars indenting the `erroneousLine` var indentation = 0; erroneousLine = erroneousLine.replace(/^s+/, function(leadingSpaces) { indentation = leadingSpaces.length; return ''; }); // Defines the number of characters that are going to show // before and after the erroneous code var LIMIT = 30; var errorColumn = e.column - indentation; if (errorColumn > LIMIT) { erroneousLine = '... ' + erroneousLine.slice(errorColumn - LIMIT); errorColumn = 4 + LIMIT; } if (erroneousLine.length - errorColumn > LIMIT) { erroneousLine = erroneousLine.slice(0, errorColumn + LIMIT) + ' ...'; } var message = 'nn' + erroneousLine + 'n'; message += new Array(errorColumn - 1).join(' ') + '^'; return message; }; </ins> var transformCode = function(code, source) { var jsx = docblock.parseAsObject(docblock.extract(code)).jsx; if (jsx) { <del> var transformed = transformReact(code); </del> <ins> try { var transformed = transformReact(code); } catch(e) { e.message += 'n    at '; if (source) { if ('fileName' in e) { // We set `fileName` if it's supported by this error object and // a `source` was provided. // The error will correctly point to `source` in Firefox. e.fileName = source; } e.message += source + ':' + e.lineNumber + ':' + e.column; } else { e.message += location.href; } e.message += createSourceCodeErrorMessage(code, e); throw e; } </ins> var map = transformed.sourceMap.toJSON(); if (source == null) {

runScripts = function() { var scripts = document.getElementsByTagName('script'); // Array.prototype.slice cannot be used on NodeList on IE8 var jsxScripts = []; for (var i = 0; i < scripts.length; i++) {

jsxScripts.push(scripts.item(i)); } } console.warn("You are using the in-browser JSX transformer. Be sure to precompile your JSX for production - http://facebook.github.io/react/docs/tooling-integration.html#jsx"); jsxScripts.forEach(function(script) {


Question:
See Return a string from and call . You get this amazing error message:
We should probably add an that whatever is returned from is in fact an object.
Invariant all the things :)
This also seems to apply when using an array, not the string only. Which makes it a pretty real-world bug IMHO (compared to the weird string scenario). Or is there a reason you don't want states to be arrays?
This will happen whenever state is anything but an Object (I think there is a check in there for arrays). Since we use merge it needs to be an object, arrays are no good either.

} this.state = this.getInitialState ? this.getInitialState() : null; <ins> invariant( typeof this.state === 'object' && !Array.isArray(this.state), '%s.getInitialState(): must return an object or null', this.constructor.displayName || 'ReactCompositeComponent' ); </ins> this._pendingState = null; this._pendingForceUpdate = false;

); }); <ins> it('should work with a null getInitialState() return value', function() { var Component = React.createClass({ getInitialState: function() { return null; }, render: function() { return <span />; } }); expect(() => <Component />).not.toThrow(); }); it('should work with object getInitialState() return values', function() { var Component = React.createClass({ getInitialState: function() { return { occupation: 'clown' }; }, render: function() { return <span />; } }); var instance = <Component />; ReactTestUtils.renderIntoDocument(instance); expect(instance.state.occupation).toEqual('clown'); }); it('should throw with non-object getInitialState() return values', function() { [['an array'], 'a string', 1234].forEach(function(state) { var Component = React.createClass({ getInitialState: function() { return state; }, render: function() { return <span />; } }); var instance = <Component />; expect(function() { ReactTestUtils.renderIntoDocument(instance); }).toThrow( 'Invariant Violation: Component.getInitialState(): ' + 'must return an object or null' ); }); }); </ins> it('should detect valid CompositeComponent classes', function() { var Component = React.createClass({ render: function() {


Question:
Should be as simple as making sure we include the polyfills we document
Somehow I assumed it was intentional that the polyfills weren't included, now I feel silly.
Eh, not really intentional, just never bothered to do it. Looking back it's a bit silly for us to say that we work in IE8 but not prove it.
It's ok guys, don't blame yourself for that IE8 story :) (this post is related to : !topic/reactjs/Z2jNf7za7cM) Meanwhile, I've just replied to Paul. Maybe you can help there because I'm stuck :+1: Thanks for your support and the work you've accomplished.
Hmm, it would appear this won't be possible so long as we use JSXTransform on the site. We could fix the NodeList -array issue, but we won't (and shouldn't try to) make changes to esprima to make it work (I think it's mostly using "reserved" words as keys. I guess we can turn this bug into "include polyfills, make sure things works as well as possible, provide some warnings if using IE8 about the problem"
So basically (tell me if I'm wrong) JSXTransform is not compatible with IE8.0 ? But ReactJS should be compatible, right ?
Correct. I just tested this myself with the zip I emailed to you - it's online for now at
Thanks zpao (you can remove it from your server if you wish I downloaded the srcs). I would recommend to add the non JSXTransformed example to git or the tutorial maybe ? Again thanks Paul and Spicyj for you help.
This should be easy now that has landed.
8 is out with , so this should be even easier to jump into.

<ins> // Copyright 2009-2012 by contributors, MIT License // vim: ts=4 sts=4 sw=4 expandtab //Add semicolon to prevent IIFE from being passed as argument to concated code. ; // Module systems magic dance (function (definition) { // RequireJS if (typeof define == "function") { define(definition); // YUI3 } else if (typeof YUI == "function") { YUI.add("es5-sham", definition); // CommonJS and <script> } else { definition(); } })(function () { var call = Function.prototype.call; var prototypeOfObject = Object.prototype; var owns = call.bind(prototypeOfObject.hasOwnProperty); // If JS engine supports accessors creating shortcuts. 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__); } // ES5 15.2.3.2 // http://es5.github.com/#x15.2.3.2 if (!Object.getPrototypeOf) { // https://github.com/es-shims/es5-shim/issues#issue/2 // http://ejohn.org/blog/objectgetprototypeof/ // recommended by fschaefer on github Object.getPrototypeOf = function getPrototypeOf(object) { return object.__proto__ || ( object.constructor ? object.constructor.prototype : prototypeOfObject ); }; } //ES5 15.2.3.3 //http://es5.github.com/#x15.2.3.3 function doesGetOwnPropertyDescriptorWork(object) { try { object.sentinel = 0; return Object.getOwnPropertyDescriptor( object, "sentinel" ).value === 0; } catch (exception) { // returns falsy } } //check whether getOwnPropertyDescriptor works if it's given. Otherwise, //shim partially. if (Object.defineProperty) { var getOwnPropertyDescriptorWorksOnObject = doesGetOwnPropertyDescriptorWork({}); var getOwnPropertyDescriptorWorksOnDom = typeof document == "undefined" || doesGetOwnPropertyDescriptorWork(document.createElement("div")); if (!getOwnPropertyDescriptorWorksOnDom || !getOwnPropertyDescriptorWorksOnObject ) { var getOwnPropertyDescriptorFallback = Object.getOwnPropertyDescriptor; } } if (!Object.getOwnPropertyDescriptor || getOwnPropertyDescriptorFallback) { var ERR_NON_OBJECT = "Object.getOwnPropertyDescriptor called on a non-object: "; Object.getOwnPropertyDescriptor = function getOwnPropertyDescriptor(object, property) { if ((typeof object != "object" && typeof object != "function") || object === null) { throw new TypeError(ERR_NON_OBJECT + object); } // make a valiant attempt to use the real getOwnPropertyDescriptor // for I8's DOM elements. if (getOwnPropertyDescriptorFallback) { try { return getOwnPropertyDescriptorFallback.call(Object, object, property); } catch (exception) { // try the shim if the real one doesn't work } } // If object does not owns property return undefined immediately. if (!owns(object, property)) { return; } // If object has a property then it's for sure both `enumerable` and // `configurable`. var descriptor =  { enumerable: true, configurable: true }; // If JS engine supports accessor properties then property may be a // getter or setter. if (supportsAccessors) { // Unfortunately `__lookupGetter__` will return a getter even // if object has own non getter property along with a same named // inherited getter. To avoid misbehavior we temporary remove // `__proto__` so that `__lookupGetter__` will return getter only // if it's owned by an object. var prototype = object.__proto__; object.__proto__ = prototypeOfObject; var getter = lookupGetter(object, property); var setter = lookupSetter(object, property); // Once we have getter and setter we can put values back. object.__proto__ = prototype; if (getter || setter) { if (getter) { descriptor.get = getter; } if (setter) { descriptor.set = setter; } // If it was accessor property we're done and return here // in order to avoid adding `value` to the descriptor. return descriptor; } } // If we got this far we know that object has an own property that is // not an accessor so we set it as a value and return descriptor. descriptor.value = object[property]; descriptor.writable = true; return descriptor; }; } // ES5 15.2.3.4 // http://es5.github.com/#x15.2.3.4 if (!Object.getOwnPropertyNames) { Object.getOwnPropertyNames = function getOwnPropertyNames(object) { return Object.keys(object); }; } // ES5 15.2.3.5 // http://es5.github.com/#x15.2.3.5 if (!Object.create) { // Contributed by Brandon Benvie, October, 2012 var createEmpty; var supportsProto = Object.prototype.__proto__ === null; if (supportsProto || typeof document == 'undefined') { createEmpty = function () { return { "__proto__": null }; }; } else { // In old IE __proto__ can't be used to manually set `null`, nor does // any other method exist to make an object that inherits from nothing, // aside from Object.prototype itself. Instead, create a new global // object and *steal* its Object.prototype and strip it bare. This is // used as the prototype to create nullary objects. createEmpty = function () { var iframe = document.createElement('iframe'); var parent = document.body || document.documentElement; iframe.style.display = 'none'; parent.appendChild(iframe); iframe.src = 'javascript:'; var empty = iframe.contentWindow.Object.prototype; parent.removeChild(iframe); iframe = null; delete empty.constructor; delete empty.hasOwnProperty; delete empty.propertyIsEnumerable; delete empty.isPrototypeOf; delete empty.toLocaleString; delete empty.toString; delete empty.valueOf; empty.__proto__ = null; function Empty() {} Empty.prototype = empty; // short-circuit future calls createEmpty = function () { return new Empty(); }; return new Empty(); }; } Object.create = function create(prototype, properties) { var object; function Type() {}  // An empty constructor. if (prototype === null) { object = createEmpty(); } else { if (typeof prototype !== "object" && typeof prototype !== "function") { // In the native implementation `parent` can be `null` // OR *any* `instanceof Object`  (Object|Function|Array|RegExp|etc) // Use `typeof` tho, b/c in old IE, DOM elements are not `instanceof Object` // like they are in modern browsers. Using `Object.create` on DOM elements // is...err...probably inappropriate, but the native version allows for it. throw new TypeError("Object prototype may only be an Object or null"); // same msg as Chrome } Type.prototype = prototype; object = new Type(); // IE has no built-in implementation of `Object.getPrototypeOf` // neither `__proto__`, but this manually setting `__proto__` will // guarantee that `Object.getPrototypeOf` will work as expected with // objects created using `Object.create` object.__proto__ = prototype; } if (properties !== void 0) { Object.defineProperties(object, properties); } return object; }; } // ES5 15.2.3.6 // http://es5.github.com/#x15.2.3.6 // Patch for WebKit and IE8 standard mode // Designed by hax <hax.github.com> // related issue: https://github.com/es-shims/es5-shim/issues#issue/5 // IE8 Reference: //     http://msdn.microsoft.com/en-us/library/dd282900.aspx //     http://msdn.microsoft.com/en-us/library/dd229916.aspx // WebKit Bugs: //     https://bugs.webkit.org/show_bug.cgi?id=36423 function doesDefinePropertyWork(object) { try { Object.defineProperty(object, "sentinel", {}); return "sentinel" in object; } catch (exception) { // returns falsy } } // check whether defineProperty works if it's given. Otherwise, // shim partially. if (Object.defineProperty) { var definePropertyWorksOnObject = doesDefinePropertyWork({}); var definePropertyWorksOnDom = typeof document == "undefined" || doesDefinePropertyWork(document.createElement("div")); if (!definePropertyWorksOnObject || !definePropertyWorksOnDom) { var definePropertyFallback = Object.defineProperty, definePropertiesFallback = Object.defineProperties; } } if (!Object.defineProperty || definePropertyFallback) { var ERR_NON_OBJECT_DESCRIPTOR = "Property description must be an object: "; var ERR_NON_OBJECT_TARGET = "Object.defineProperty called on non-object: " var ERR_ACCESSORS_NOT_SUPPORTED = "getters & setters can not be defined " + "on this javascript engine"; Object.defineProperty = function defineProperty(object, property, descriptor) { if ((typeof object != "object" && typeof object != "function") || object === null) { throw new TypeError(ERR_NON_OBJECT_TARGET + object); } if ((typeof descriptor != "object" && typeof descriptor != "function") || descriptor === null) { throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR + descriptor); } // make a valiant attempt to use the real defineProperty // for I8's DOM elements. if (definePropertyFallback) { try { return definePropertyFallback.call(Object, object, property, descriptor); } catch (exception) { // try the shim if the real one doesn't work } } // If it's a data property. if (owns(descriptor, "value")) { // fail silently if "writable", "enumerable", or "configurable" // are requested but not supported /* // alternate approach: if ( // can't implement these features; allow false but not true !(owns(descriptor, "writable") ? descriptor.writable : true) || !(owns(descriptor, "enumerable") ? descriptor.enumerable : true) || !(owns(descriptor, "configurable") ? descriptor.configurable : true) ) throw new RangeError( "This implementation of Object.defineProperty does not " + "support configurable, enumerable, or writable." ); */ if (supportsAccessors && (lookupGetter(object, property) || lookupSetter(object, property))) { // As accessors are supported only on engines implementing // `__proto__` we can safely override `__proto__` while defining // a property to make sure that we don't hit an inherited // accessor. var prototype = object.__proto__; object.__proto__ = prototypeOfObject; // Deleting a property anyway since getter / setter may be // defined on object itself. delete object[property]; object[property] = descriptor.value; // Setting original `__proto__` back now. object.__proto__ = prototype; } else { object[property] = descriptor.value; } } else { if (!supportsAccessors) { throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED); } // If we got that far then getters and setters can be defined !! if (owns(descriptor, "get")) { defineGetter(object, property, descriptor.get); } if (owns(descriptor, "set")) { defineSetter(object, property, descriptor.set); } } return object; }; } // ES5 15.2.3.7 // http://es5.github.com/#x15.2.3.7 if (!Object.defineProperties || definePropertiesFallback) { Object.defineProperties = function defineProperties(object, properties) { // make a valiant attempt to use the real defineProperties if (definePropertiesFallback) { try { return definePropertiesFallback.call(Object, object, properties); } catch (exception) { // try the shim if the real one doesn't work } } for (var property in properties) { if (owns(properties, property) && property != "__proto__") { Object.defineProperty(object, property, properties[property]); } } return object; }; } // ES5 15.2.3.8 // http://es5.github.com/#x15.2.3.8 if (!Object.seal) { Object.seal = function seal(object) { // this is misleading and breaks feature-detection, but // allows "securable" code to "gracefully" degrade to working // but insecure code. return object; }; } // ES5 15.2.3.9 // http://es5.github.com/#x15.2.3.9 if (!Object.freeze) { Object.freeze = function freeze(object) { // this is misleading and breaks feature-detection, but // allows "securable" code to "gracefully" degrade to working // but insecure code. return object; }; } // detect a Rhino bug and patch it try { Object.freeze(function () {}); } catch (exception) { Object.freeze = (function freeze(freezeObject) { return function freeze(object) { if (typeof object == "function") { return object; } else { return freezeObject(object); } }; })(Object.freeze); } // ES5 15.2.3.10 // http://es5.github.com/#x15.2.3.10 if (!Object.preventExtensions) { Object.preventExtensions = function preventExtensions(object) { // this is misleading and breaks feature-detection, but // allows "securable" code to "gracefully" degrade to working // but insecure code. return object; }; } // ES5 15.2.3.11 // http://es5.github.com/#x15.2.3.11 if (!Object.isSealed) { Object.isSealed = function isSealed(object) { return false; }; } // ES5 15.2.3.12 // http://es5.github.com/#x15.2.3.12 if (!Object.isFrozen) { Object.isFrozen = function isFrozen(object) { return false; }; } // ES5 15.2.3.13 // http://es5.github.com/#x15.2.3.13 if (!Object.isExtensible) { Object.isExtensible = function isExtensible(object) { // 1. If Type(O) is not Object throw a TypeError exception. if (Object(object) !== object) { throw new TypeError(); // TODO message } // 2. Return the Boolean value of the [[Extensible]] internal property of O. var name = ''; while (owns(object, name)) { name += '?'; } object[name] = true; var returnValue = owns(object, name); delete object[name]; return returnValue; }; } }); </ins>

<ins> // Copyright 2009-2012 by contributors, MIT License // vim: ts=4 sts=4 sw=4 expandtab //Add semicolon to prevent IIFE from being passed as argument to concated code. ; // Module systems magic dance (function (definition) { // RequireJS if (typeof define == "function") { define(definition); // YUI3 } else if (typeof YUI == "function") { YUI.add("es5", definition); // CommonJS and <script> } else { definition(); } })(function () { /** * Brings an environment as close to ECMAScript 5 compliance * as is possible with the facilities of erstwhile engines. * * Annotated ES5: http://es5.github.com/ (specific links below) * ES5 Spec: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf * Required reading: http://javascriptweblog.wordpress.com/2011/12/05/extending-javascript-natives/ */ // ES-5 15.1.2.2 if (parseInt('08') !== 8) { parseInt = (function (origParseInt) { var hexRegex = /^0[xX]/; return function parseIntES5(str, radix) { str = String(str).trim(); if (!+radix) { radix = hexRegex.test(str) ? 16 : 10; } return origParseInt(str, radix); }; }(parseInt)); } // // Function // ======== // // ES-5 15.3.4.5 // http://es5.github.com/#x15.3.4.5 function Empty() {} if (!Function.prototype.bind) { Function.prototype.bind = function bind(that) { // .length is 1 // 1. Let Target be the this value. var target = this; // 2. If IsCallable(Target) is false, throw a TypeError exception. if (typeof target != "function") { throw new TypeError("Function.prototype.bind called on incompatible " + target); } // 3. Let A be a new (possibly empty) internal list of all of the //   argument values provided after thisArg (arg1, arg2 etc), in order. // XXX slicedArgs will stand in for "A" if used var args = _Array_slice_.call(arguments, 1); // for normal call // 4. Let F be a new native ECMAScript object. // 11. Set the [[Prototype]] internal property of F to the standard //   built-in Function prototype object as specified in 15.3.3.1. // 12. Set the [[Call]] internal property of F as described in //   15.3.4.5.1. // 13. Set the [[Construct]] internal property of F as described in //   15.3.4.5.2. // 14. Set the [[HasInstance]] internal property of F as described in //   15.3.4.5.3. var binder = function () { if (this instanceof bound) { // 15.3.4.5.2 [[Construct]] // When the [[Construct]] internal method of a function object, // F that was created using the bind function is called with a // list of arguments ExtraArgs, the following steps are taken: // 1. Let target be the value of F's [[TargetFunction]] //   internal property. // 2. If target has no [[Construct]] internal method, a //   TypeError exception is thrown. // 3. Let boundArgs be the value of F's [[BoundArgs]] internal //   property. // 4. Let args be a new list containing the same values as the //   list boundArgs in the same order followed by the same //   values as the list ExtraArgs in the same order. // 5. Return the result of calling the [[Construct]] internal //   method of target providing args as the arguments. var result = target.apply( this, args.concat(_Array_slice_.call(arguments)) ); if (Object(result) === result) { return result; } return this; } else { // 15.3.4.5.1 [[Call]] // When the [[Call]] internal method of a function object, F, // which was created using the bind function is called with a // this value and a list of arguments ExtraArgs, the following // steps are taken: // 1. Let boundArgs be the value of F's [[BoundArgs]] internal //   property. // 2. Let boundThis be the value of F's [[BoundThis]] internal //   property. // 3. Let target be the value of F's [[TargetFunction]] internal //   property. // 4. Let args be a new list containing the same values as the //   list boundArgs in the same order followed by the same //   values as the list ExtraArgs in the same order. // 5. Return the result of calling the [[Call]] internal method //   of target providing boundThis as the this value and //   providing args as the arguments. // equiv: target.call(this, ...boundArgs, ...args) return target.apply( that, args.concat(_Array_slice_.call(arguments)) ); } }; // 15. If the [[Class]] internal property of Target is "Function", then //     a. Let L be the length property of Target minus the length of A. //     b. Set the length own property of F to either 0 or L, whichever is //       larger. // 16. Else set the length own property of F to 0. var boundLength = Math.max(0, target.length - args.length); // 17. Set the attributes of the length own property of F to the values //   specified in 15.3.5.1. var boundArgs = []; for (var i = 0; i < boundLength; i++) { boundArgs.push("$" + i); } // XXX Build a dynamic function with desired amount of arguments is the only // way to set the length property of a function. // In environments where Content Security Policies enabled (Chrome extensions, // for ex.) all use of eval or Function costructor throws an exception. // However in all of these environments Function.prototype.bind exists // and so this code will never be executed. var bound = Function("binder", "return function(" + boundArgs.join(",") + "){return binder.apply(this,arguments)}")(binder); if (target.prototype) { Empty.prototype = target.prototype; bound.prototype = new Empty(); // Clean up dangling references. Empty.prototype = null; } // TODO // 18. Set the [[Extensible]] internal property of F to true. // TODO // 19. Let thrower be the [[ThrowTypeError]] function Object (13.2.3). // 20. Call the [[DefineOwnProperty]] internal method of F with //   arguments "caller", PropertyDescriptor {[[Get]]: thrower, [[Set]]: //   thrower, [[Enumerable]]: false, [[Configurable]]: false}, and //   false. // 21. Call the [[DefineOwnProperty]] internal method of F with //   arguments "arguments", PropertyDescriptor {[[Get]]: thrower, //   [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: false}, //   and false. // TODO // NOTE Function objects created using Function.prototype.bind do not // have a prototype property or the [[Code]], [[FormalParameters]], and // [[Scope]] internal properties. // XXX can't delete prototype in pure-js. // 22. Return F. return bound; }; } // Shortcut to an often accessed properties, in order to avoid multiple // dereference that costs universally. // _Please note: Shortcuts are defined after `Function.prototype.bind` as we // us it in defining shortcuts. var call = Function.prototype.call; var prototypeOfArray = Array.prototype; var prototypeOfObject = Object.prototype; var _Array_slice_ = prototypeOfArray.slice; // Having a toString local variable name breaks in Opera so use _toString. var _toString = call.bind(prototypeOfObject.toString); var owns = call.bind(prototypeOfObject.hasOwnProperty); // If JS engine supports accessors creating shortcuts. 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__); } // // Array // ===== // // ES5 15.4.4.12 // http://es5.github.com/#x15.4.4.12 // Default value for second param // [bugfix, ielt9, old browsers] // IE < 9 bug: [1,2].splice(0).join("") == "" but should be "12" if ([1,2].splice(0).length != 2) { var array_splice = Array.prototype.splice; var array_push = Array.prototype.push; var array_unshift = Array.prototype.unshift; if (function() { // test IE < 9 to splice bug - see issue #138 function makeArray(l) { var a = []; while (l--) { a.unshift(l) } return a } var array = [] , lengthBefore ; array.splice.bind(array, 0, 0).apply(null, makeArray(20)); array.splice.bind(array, 0, 0).apply(null, makeArray(26)); lengthBefore = array.length; //20 array.splice(5, 0, "XXX"); // add one element if (lengthBefore + 1 == array.length) { return true;// has right splice implementation without bugs } // else { //    IE8 bug // } }()) {//IE 6/7 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(_Array_slice_.call(arguments, 2))) } }; } else {//IE8 Array.prototype.splice = function(start, deleteCount) { var result , args = _Array_slice_.call(arguments, 2) , addElementsCount = args.length ; if (!arguments.length) { return []; } if (start === void 0) { // default start = 0; } if (deleteCount === void 0) { // default deleteCount = this.length - start; } if (addElementsCount > 0) { if (deleteCount <= 0) { if (start == this.length) { // tiny optimisation #1 array_push.apply(this, args); return []; } if (start == 0) { // tiny optimisation #2 array_unshift.apply(this, args); return []; } } // Array.prototype.splice implementation result = _Array_slice_.call(this, start, start + deleteCount);// delete part args.push.apply(args, _Array_slice_.call(this, start + deleteCount, this.length));// right part args.unshift.apply(args, _Array_slice_.call(this, 0, start));// left part // delete all items from this array and replace it to 'left part' + _Array_slice_.call(arguments, 2) + 'right part' args.unshift(0, this.length); array_splice.apply(this, args); return result; } return array_splice.call(this, start, deleteCount); } } } // ES5 15.4.4.12 // http://es5.github.com/#x15.4.4.13 // Return len+argCount. // [bugfix, ielt8] // IE < 8 bug: [].unshift(0) == undefined but should be "1" if ([].unshift(0) != 1) { var array_unshift = Array.prototype.unshift; Array.prototype.unshift = function() { array_unshift.apply(this, arguments); return this.length; }; } // ES5 15.4.3.2 // http://es5.github.com/#x15.4.3.2 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/isArray if (!Array.isArray) { Array.isArray = function isArray(obj) { return _toString(obj) == "[object Array]"; }; } // The IsCallable() check in the Array functions // has been replaced with a strict check on the // internal class of the object to trap cases where // the provided function was actually a regular // expression literal, which in V8 and // JavaScriptCore is a typeof "function".  Only in // V8 are regular expression literals permitted as // reduce parameters, so it is desirable in the // general case for the shim to match the more // strict and common behavior of rejecting regular // expressions. // ES5 15.4.4.18 // http://es5.github.com/#x15.4.4.18 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/forEach // Check failure of by-index access of string characters (IE < 9) // and failure of `0 in boxedString` (Rhino) var boxedString = Object("a"), splitString = boxedString[0] != "a" || !(0 in boxedString); // Check node 0.6.21 bug where third parameter is not boxed var boxedForEach = true; if (Array.prototype.forEach) { Array.prototype.forEach.call("foo", function(item, i, obj) { if (typeof obj !== 'object') boxedForEach = false; }); } if (!Array.prototype.forEach || !boxedForEach) { Array.prototype.forEach = function forEach(fun /*, thisp*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, thisp = arguments[1], i = -1, length = self.length >>> 0; // If no callback function or if callback is not a callable function if (_toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } while (++i < length) { if (i in self) { // Invoke the callback function with call, passing arguments: // context, property value, property key, thisArg object // context fun.call(thisp, self[i], i, object); } } }; } // ES5 15.4.4.19 // http://es5.github.com/#x15.4.4.19 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/map if (!Array.prototype.map) { Array.prototype.map = function map(fun /*, thisp*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, result = Array(length), thisp = arguments[1]; // If no callback function or if callback is not a callable function 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; }; } // ES5 15.4.4.20 // http://es5.github.com/#x15.4.4.20 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/filter if (!Array.prototype.filter) { Array.prototype.filter = function filter(fun /*, thisp */) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, result = [], value, thisp = arguments[1]; // If no callback function or if callback is not a callable function 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; }; } // ES5 15.4.4.16 // http://es5.github.com/#x15.4.4.16 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/every if (!Array.prototype.every) { Array.prototype.every = function every(fun /*, thisp */) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, thisp = arguments[1]; // If no callback function or if callback is not a callable function 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; }; } // ES5 15.4.4.17 // http://es5.github.com/#x15.4.4.17 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some if (!Array.prototype.some) { Array.prototype.some = function some(fun /*, thisp */) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, thisp = arguments[1]; // If no callback function or if callback is not a callable function 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; }; } // ES5 15.4.4.21 // http://es5.github.com/#x15.4.4.21 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduce if (!Array.prototype.reduce) { Array.prototype.reduce = function reduce(fun /*, initial*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0; // If no callback function or if callback is not a callable function if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } // no value to return if no initial value and an empty array 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 array contains no values, no initial value to return 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; }; } // ES5 15.4.4.22 // http://es5.github.com/#x15.4.4.22 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduceRight if (!Array.prototype.reduceRight) { Array.prototype.reduceRight = function reduceRight(fun /*, initial*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0; // If no callback function or if callback is not a callable function if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } // no value to return if no initial value, empty array 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 array contains no values, no initial value to return if (--i < 0) { throw new TypeError("reduceRight of empty array with no initial value"); } } while (true); } if (i < 0) { return result; } do { if (i in this) { result = fun.call(void 0, result, self[i], i, object); } } while (i--); return result; }; } // ES5 15.4.4.14 // http://es5.github.com/#x15.4.4.14 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf if (!Array.prototype.indexOf || ([0, 1].indexOf(1, 2) != -1)) { Array.prototype.indexOf = function indexOf(sought /*, fromIndex */ ) { 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]); } // handle negative indices i = i >= 0 ? i : Math.max(0, length + i); for (; i < length; i++) { if (i in self && self[i] === sought) { return i; } } return -1; }; } // ES5 15.4.4.15 // http://es5.github.com/#x15.4.4.15 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/lastIndexOf if (!Array.prototype.lastIndexOf || ([0, 1].lastIndexOf(0, -3) != -1)) { Array.prototype.lastIndexOf = function lastIndexOf(sought /*, fromIndex */) { 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])); } // handle negative indices i = i >= 0 ? i : length - Math.abs(i); for (; i >= 0; i--) { if (i in self && sought === self[i]) { return i; } } return -1; }; } // // Object // ====== // // ES5 15.2.3.14 // http://es5.github.com/#x15.2.3.14 if (!Object.keys) { // http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation 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; }; } // // Date // ==== // // ES5 15.9.5.43 // http://es5.github.com/#x15.9.5.43 // This function returns a String value represent the instance in time // represented by this Date object. The format of the String is the Date Time // string format defined in 15.9.1.15. All fields are present in the String. // The time zone is always UTC, denoted by the suffix Z. If the time value of // this object is not a finite Number a RangeError exception is thrown. var negativeDate = -62198755200000, 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(); // see https://github.com/es-shims/es5-shim/issues/111 year += Math.floor(month / 12); month = (month % 12 + 12) % 12; // the date time string format is specified in 15.9.1.15. 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]; // pad months, days, hours, minutes, and seconds to have two // digits. if (value < 10) { result[length] = "0" + value; } } // pad milliseconds to have three digits. return ( year + "-" + result.slice(0, 2).join("-") + "T" + result.slice(2).join(":") + "." + ("000" + this.getUTCMilliseconds()).slice(-3) + "Z" ); }; } // ES5 15.9.5.44 // http://es5.github.com/#x15.9.5.44 // This function provides a String representation of a Date object for use by // JSON.stringify (15.12.3). var dateToJSONIsSupported = false; try { dateToJSONIsSupported = ( Date.prototype.toJSON && new Date(NaN).toJSON() === null && new Date(negativeDate).toJSON().indexOf(negativeYearString) !== -1 && Date.prototype.toJSON.call({ // generic toISOString: function () { return true; } }) ); } catch (e) { } if (!dateToJSONIsSupported) { Date.prototype.toJSON = function toJSON(key) { // When the toJSON method is called with argument key, the following // steps are taken: // 1.  Let O be the result of calling ToObject, giving it the this // value as its argument. // 2. Let tv be toPrimitive(O, hint Number). var o = Object(this), tv = toPrimitive(o), toISO; // 3. If tv is a Number and is not finite, return null. if (typeof tv === "number" && !isFinite(tv)) { return null; } // 4. Let toISO be the result of calling the [[Get]] internal method of // O with argument "toISOString". toISO = o.toISOString; // 5. If IsCallable(toISO) is false, throw a TypeError exception. if (typeof toISO != "function") { throw new TypeError("toISOString property is not callable"); } // 6. Return the result of calling the [[Call]] internal method of //  toISO with O as the this value and an empty argument list. return toISO.call(o); // NOTE 1 The argument is ignored. // NOTE 2 The toJSON function is intentionally generic; it does not // require that its this value be a Date object. Therefore, it can be // transferred to other kinds of objects for use as a method. However, // it does require that any such object have a toISOString method. An // object is free to use the argument key to filter its // stringification. }; } // ES5 15.9.4.2 // http://es5.github.com/#x15.9.4.2 // based on work shared by Daniel Friesen (dantman) // http://gist.github.com/303249 if (!Date.parse || "Date.parse is buggy") { // XXX global assignment won't work in embeddings that use // an alternate object for the context. Date = (function(NativeDate) { // Date.length === 7 function Date(Y, M, D, h, m, s, ms) { var length = arguments.length; if (this instanceof NativeDate) { var date = length == 1 && String(Y) === Y ? // isString(Y) // We explicitly pass it through parse: new NativeDate(Date.parse(Y)) : // We have to manually make calls depending on argument // length here 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(); // Prevent mixups with unfixed Date object date.constructor = Date; return date; } return NativeDate.apply(this, arguments); }; // 15.9.1.15 Date Time String Format. var isoDateExpression = new RegExp("^" + "(d{4}|[+-]d{6})" + // four-digit year capture or sign + // 6-digit extended year "(?:-(d{2})" + // optional month capture "(?:-(d{2})" + // optional day capture "(?:" + // capture hours:minutes:seconds.milliseconds "T(d{2})" + // hours capture ":(d{2})" + // minutes capture "(?:" + // optional :seconds.milliseconds ":(d{2})" + // seconds capture "(?:(.d{1,}))?" + // milliseconds capture ")?" + "(" + // capture UTC offset component "Z|" + // UTC capture "(?:" + // offset specifier +/-hours:minutes "([-+])" + // sign capture "(d{2})" + // hours offset capture ":(d{2})" + // minutes offset capture ")" + ")?)?)?)?" + "$"); 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) ); } function toUTC(t) { return Number(new NativeDate(1970, 0, 1, 0, 0, 0, t)); } // Copy any custom methods a 3rd party library may have added for (var key in NativeDate) { Date[key] = NativeDate[key]; } // Copy "native" methods explicitly; they may be non-enumerable Date.now = NativeDate.now; Date.UTC = NativeDate.UTC; Date.prototype = NativeDate.prototype; Date.prototype.constructor = Date; // Upgrade Date.parse to handle simplified ISO 8601 strings Date.parse = function parse(string) { var match = isoDateExpression.exec(string); if (match) { // parse months, days, hours, minutes, seconds, and milliseconds // provide default values if necessary // parse the UTC offset component 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 = Math.floor(Number(match[7] || 0) * 1000), // When time zone is missed, local offset should be used // (ES 5.1 bug) // see https://bugs.ecmascript.org/show_bug.cgi?id=112 isLocalTime = Boolean(match[4] && !match[8]), 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 < 1000 && month > -1 && month < 12 && hourOffset < 24 && minuteOffset < 60 && // detect invalid offsets 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 ) * 1000 + millisecond; if (isLocalTime) { result = toUTC(result); } if (-8.64e15 <= result && result <= 8.64e15) { return result; } } return NaN; } return NativeDate.parse.apply(this, arguments); }; return Date; })(Date); } // ES5 15.9.4.4 // http://es5.github.com/#x15.9.4.4 if (!Date.now) { Date.now = function now() { return new Date().getTime(); }; } // // Number // ====== // // ES5.1 15.7.4.5 // http://es5.github.com/#x15.7.4.5 if (!Number.prototype.toFixed || (0.00008).toFixed(3) !== '0.000' || (0.9).toFixed(0) === '0' || (1.255).toFixed(2) !== '1.25' || (1000000000000000128).toFixed(0) !== "1000000000000000128") { // Hide these variables and functions (function () { var base, size, data, i; base = 1e7; size = 6; data = [0, 0, 0, 0, 0, 0]; function multiply(n, c) { var i = -1; while (++i < size) { c += n * data[i]; data[i] = c % base; c = Math.floor(c / base); } } function divide(n) { var i = size, c = 0; while (--i >= 0) { c += data[i]; data[i] = Math.floor(c / n); c = (c % n) * base; } } function toString() { var i = size; var s = ''; while (--i >= 0) { if (s !== '' || i === 0 || data[i] !== 0) { var t = String(data[i]); if (s === '') { s = t; } else { s += '0000000'.slice(0, 7 - t.length) + t; } } } return s; } function pow(x, n, acc) { return (n === 0 ? acc : (n % 2 === 1 ? pow(x, n - 1, acc * x) : pow(x * x, n / 2, acc))); } function log(x) { var n = 0; while (x >= 4096) { n += 12; x /= 4096; } while (x >= 2) { n += 1; x /= 2; } return n; } Number.prototype.toFixed = function (fractionDigits) { var f, x, s, m, e, z, j, k; // Test for NaN and round fractionDigits down f = Number(fractionDigits); f = f !== f ? 0 : Math.floor(f); if (f < 0 || f > 20) { throw new RangeError("Number.toFixed called with invalid number of decimals"); } x = Number(this); // Test for NaN if (x !== x) { return "NaN"; } // If it is too big or small, return the string value of the number if (x <= -1e21 || x >= 1e21) { return String(x); } s = ""; if (x < 0) { s = "-"; x = -x; } m = "0"; if (x > 1e-21) { // 1e-21 < x < 1e21 // -70 < log2(x) < 70 e = log(x * pow(2, 69, 1)) - 69; z = (e < 0 ? x * pow(2, -e, 1) : x / pow(2, e, 1)); z *= 0x10000000000000; // Math.pow(2, 52); e = 52 - e; // -18 < e < 122 // x = z / 2 ^ e if (e > 0) { multiply(0, z); j = f; while (j >= 7) { multiply(1e7, 0); j -= 7; } multiply(pow(10, j, 1), 0); j = e - 1; while (j >= 23) { divide(1 << 23); j -= 23; } divide(1 << j); multiply(1, 1); divide(2); m = toString(); } else { multiply(0, z); multiply(1 << (-e), 0); m = toString() + '0.00000000000000000000'.slice(2, 2 + f); } } if (f > 0) { k = m.length; if (k <= f) { m = s + '0.0000000000000000000'.slice(0, f - k + 2) + m; } else { m = s + m.slice(0, k - f) + '.' + m.slice(k - f); } } else { m = s + m; } return m; } }()); } // // String // ====== // // ES5 15.5.4.14 // http://es5.github.com/#x15.5.4.14 // [bugfix, IE lt 9, firefox 4, Konqueror, Opera, obscure browsers] // Many browsers do not split properly with regular expressions or they // do not perform the split correctly under obscure conditions. // See http://blog.stevenlevithan.com/archives/cross-browser-split // I've tested in many browsers and this seems to cover the deviant ones: //    'ab'.split(/(?:ab)*/) should be ["", ""], not [""] //    '.'.split(/(.?)(.?)/) should be ["", ".", "", ""], not ["", ""] //    'tesst'.split(/(s)*/) should be ["t", undefined, "e", "s", "t"], not //       [undefined, "t", undefined, "e", ...] //    ''.split(/.?/) should be [], not [""] //    '.'.split(/()()/) should be ["."], not ["", "", "."] var string_split = String.prototype.split; if ( 'ab'.split(/(?:ab)*/).length !== 2 || '.'.split(/(.?)(.?)/).length !== 4 || 'tesst'.split(/(s)*/)[1] === "t" || ''.split(/.?/).length || '.'.split(/()()/).length > 1 ) { (function () { var compliantExecNpcg = /()??/.exec("")[1] === void 0; // NPCG: nonparticipating capturing group String.prototype.split = function (separator, limit) { var string = this; if (separator === void 0 && limit === 0) return []; // If `separator` is not a regex, use native split if (Object.prototype.toString.call(separator) !== "[object RegExp]") { return string_split.apply(this, arguments); } var output = [], flags = (separator.ignoreCase ? "i" : "") + (separator.multiline  ? "m" : "") + (separator.extended   ? "x" : "") + // Proposed for ES6 (separator.sticky     ? "y" : ""), // Firefox 3+ lastLastIndex = 0, // Make `global` and avoid `lastIndex` issues by working with a copy separator = new RegExp(separator.source, flags + "g"), separator2, match, lastIndex, lastLength; string += ""; // Type-convert if (!compliantExecNpcg) { // Doesn't need flags gy, but they don't hurt separator2 = new RegExp("^" + separator.source + "$(?!s)", flags); } /* Values for `limit`, per the spec: * If undefined: 4294967295 // Math.pow(2, 32) - 1 * If 0, Infinity, or NaN: 0 * If positive number: limit = Math.floor(limit); if (limit > 4294967295) limit -= 4294967296; * If negative number: 4294967296 - Math.floor(Math.abs(limit)) * If other: Type-convert, then use the above rules */ limit = limit === void 0 ? -1 >>> 0 : // Math.pow(2, 32) - 1 limit >>> 0; // ToUint32(limit) while (match = separator.exec(string)) { // `separator.lastIndex` is not reliable cross-browser lastIndex = match.index + match[0].length; if (lastIndex > lastLastIndex) { output.push(string.slice(lastLastIndex, match.index)); // Fix browsers whose `exec` methods don't consistently return `undefined` for // nonparticipating capturing groups if (!compliantExecNpcg && match.length > 1) { match[0].replace(separator2, function () { for (var i = 1; i < arguments.length - 2; i++) { if (arguments[i] === void 0) { match[i] = void 0; } } }); } if (match.length > 1 && match.index < string.length) { Array.prototype.push.apply(output, match.slice(1)); } lastLength = match[0].length; lastLastIndex = lastIndex; if (output.length >= limit) { break; } } if (separator.lastIndex === match.index) { separator.lastIndex++; // Avoid an infinite loop } } if (lastLastIndex === string.length) { if (lastLength || !separator.test("")) { output.push(""); } } else { output.push(string.slice(lastLastIndex)); } return output.length > limit ? output.slice(0, limit) : output; }; }()); // [bugfix, chrome] // If separator is undefined, then the result array contains just one String, // which is the this value (converted to a String). If limit is not undefined, // then the output array is truncated so that it contains no more than limit // elements. // "0".split(undefined, 0) -> [] } else if ("0".split(void 0, 0).length) { String.prototype.split = function(separator, limit) { if (separator === void 0 && limit === 0) return []; return string_split.apply(this, arguments); } } // ECMA-262, 3rd B.2.3 // Note an ECMAScript standart, although ECMAScript 3rd Edition has a // non-normative section suggesting uniform semantics and it should be // normalized across all browsers // [bugfix, IE lt 9] IE < 9 substr() with negative value not working in IE if ("".substr && "0b".substr(-1) !== "b") { var string_substr = String.prototype.substr; /** *  Get the substring of a string *  @param  {integer}  start   where to start the substring *  @param  {integer}  length  how many characters to return *  @return {string} */ String.prototype.substr = function(start, length) { return string_substr.call( this, start < 0 ? ((start = this.length + start) < 0 ? 0 : start) : start, length ); } } // ES5 15.5.4.20 // http://es5.github.com/#x15.5.4.20 var ws = "x09x0Ax0Bx0Cx0Dx20xA0u1680u180Eu2000u2001u2002u2003" + "u2004u2005u2006u2007u2008u2009u200Au202Fu205Fu3000u2028" + "u2029uFEFF"; if (!String.prototype.trim || ws.trim()) { // http://blog.stevenlevithan.com/archives/faster-trim-javascript // http://perfectionkills.com/whitespace-deviations/ ws = "[" + ws + "]"; var trimBeginRegexp = new RegExp("^" + ws + ws + "*"), trimEndRegexp = new RegExp(ws + ws + "*$"); String.prototype.trim = function trim() { if (this === void 0 || this === null) { throw new TypeError("can't convert "+this+" to object"); } return String(this) .replace(trimBeginRegexp, "") .replace(trimEndRegexp, ""); }; } // // Util // ====== // // ES5 9.4 // http://es5.github.com/#x9.4 // http://jsperf.com/to-integer function toInteger(n) { n = +n; if (n !== n) { // isNaN 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(); } // ES5 9.9 // http://es5.github.com/#x9.9 var toObject = function (o) { if (o == null) { // this matches both null and undefined throw new TypeError("can't convert "+o+" to object"); } return Object(o); }; }); </ins>

<!DOCTYPE html> <ins> <!--[if IE]><![endif]--> </ins> <html> <head> <meta charset="utf-8">

<script type="text/javascript" src="//use.typekit.net/vqa1hcx.js"></script> <script type="text/javascript">try{Typekit.load();}catch(e){}</script> <ins> <!--[if lte IE 8]> <script type="text/javascript" src="/react/js/es5-shim.js"></script> <script type="text/javascript" src="/react/js/es5-sham.js"></script> <![endif]--> </ins> <script type="text/javascript" src="/react/js/codemirror.js"></script> <script type="text/javascript" src="/react/js/javascript.js"></script> <script type="text/javascript" src="/react/js/react.min.js"></script>


Question:
When using ReactLink with checkboxes or dropdowns, the state should not be bound to 'value', but to 'checked' and 'selected' instead.
I guess it's not obvious what the API should be here. I suppose the most obvious way is to do but keep as-is (and should still not work). Any opinions?
Either or change to do the same thing as ?

'radio': true }; <del> function _assertLink(input) { </del> <ins> function _assertSingleLink(input) { invariant( input.props.checkedLink == null || input.props.valueLink == null, 'Cannot provide a checkedLink and a valueLink. If you want to use ' + 'checkedLink, you probably don't want to use valueLink and vice versa.' ); } function _assertValueLink(input) { _assertSingleLink(input); </ins> invariant( input.props.value == null && input.props.onChange == null, 'Cannot provide a valueLink and a value or onChange event. If you want ' +

); } <ins> function _assertCheckedLink(input) { _assertSingleLink(input); invariant( input.props.checked == null && input.props.onChange == null, 'Cannot provide a checkedLink and a checked property or onChange event. ' + 'If you want to use checked or onChange, you probably don't want to ' + 'use checkedLink' ); } </ins> /** * @param {SyntheticEvent} e change event to handle */

} /** <ins> * @param {SyntheticEvent} e change event to handle */ function _handleLinkedCheckChange(e) { /*jshint validthis:true */ this.props.checkedLink.requestChange(e.target.checked); } /** </ins> * Provide a linked `value` attribute for controlled forms. You should not use * this outside of the ReactDOM controlled form components. */

); } } <ins> }, checked: function(props, propName, componentName) { if (__DEV__) { if (props[propName] && !props.onChange && !props.readOnly && !props.disabled) { console.warn( 'You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.' ); } } </ins> } } },

*/ getValue: function(input) { if (input.props.valueLink) { <del> _assertLink(input); </del> <ins> _assertValueLink(input); </ins> return input.props.valueLink.value; } return input.props.value;

/** * @param {ReactComponent} input Form component <ins> * @return {*} current checked status of the input either from checked prop *             or link. */ getChecked: function(input) { if (input.props.checkedLink) { _assertCheckedLink(input); return input.props.checkedLink.value; } return input.props.checked; }, /** * @param {ReactComponent} input Form component </ins> * @return {function} change callback either from onChange prop or link. */ getOnChange: function(input) { if (input.props.valueLink) { <del> _assertLink(input); </del> <ins> _assertValueLink(input); </ins> return _handleLinkedValueChange; <ins> } else if (input.props.checkedLink) { _assertCheckedLink(input); return _handleLinkedCheckChange; </ins> } return input.props.onChange; }

props.defaultChecked = null; props.defaultValue = null; <del> props.checked = this.props.checked != null ? this.props.checked : this.state.checked; </del> var value = LinkedValueUtils.getValue(this); props.value = value != null ? value : this.state.value; <ins> var checked = LinkedValueUtils.getChecked(this); props.checked = checked != null ? checked : this.state.checked; </ins> props.onChange = this._handleChange; return input(props, this.props.children);

expect(React.renderComponent.bind(React, instance, node)).toThrow(); }); <ins> it('should support checkedLink', function() { var container = document.createElement('div'); var link = new ReactLink(true, mocks.getMockFunction()); var instance = <input type="checkbox" checkedLink={link} />; React.renderComponent(instance, container); expect(instance.getDOMNode().checked).toBe(true); expect(link.value).toBe(true); expect(link.requestChange.mock.calls.length).toBe(0); instance.getDOMNode().checked = false; ReactTestUtils.Simulate.click(instance.getDOMNode()); expect(link.requestChange.mock.calls.length).toBe(1); expect(link.requestChange.mock.calls[0][0]).toEqual(false); }); it('should warn with checked and no onChange handler', function() { var oldWarn = console.warn; try { console.warn = mocks.getMockFunction(); var node = document.createElement('div'); var link = new ReactLink(true, mocks.getMockFunction()); React.renderComponent(<input type="checkbox" checkedLink={link} />, node); expect(console.warn.mock.calls.length).toBe(0); React.renderComponent( <input type="checkbox" checked="false" onChange={mocks.getMockFunction()} />, node ); expect(console.warn.mock.calls.length).toBe(0); React.renderComponent( <input type="checkbox" checked="false" readOnly={true} />, node ); expect(console.warn.mock.calls.length).toBe(0); React.renderComponent(<input type="checkbox" checked="false" />, node); expect(console.warn.mock.calls.length).toBe(1); React.renderComponent( <input type="checkbox" checked="false" readOnly={false} />, node ); expect(console.warn.mock.calls.length).toBe(2); } finally { console.warn = oldWarn; } }); it('should throw if both checked and checkedLink are provided', function() { // Silences console.error messages // ReactErrorUtils.guard is applied to all methods of a React component // and calls console.error in __DEV__ (true for test environment) spyOn(console, 'error'); var node = document.createElement('div'); var link = new ReactLink(true, mocks.getMockFunction()); var instance = <input type="checkbox" checkedLink={link} />; expect(React.renderComponent.bind(React, instance, node)).not.toThrow(); instance = <input type="checkbox" checkedLink={link} checked="false" />; expect(React.renderComponent.bind(React, instance, node)).toThrow(); instance = <input type="checkbox" checkedLink={link} onChange={emptyFunction} />; expect(React.renderComponent.bind(React, instance, node)).toThrow(); }); it('should throw if both checkedLink and valueLink are provided', function() { // Silences console.error messages // ReactErrorUtils.guard is applied to all methods of a React component // and calls console.error in __DEV__ (true for test environment) spyOn(console, 'error'); var node = document.createElement('div'); var link = new ReactLink(true, mocks.getMockFunction()); var instance = <input type="checkbox" checkedLink={link} />; expect(React.renderComponent.bind(React, instance, node)).not.toThrow(); instance = <input type="checkbox" valueLink={link} />; expect(React.renderComponent.bind(React, instance, node)).not.toThrow(); instance = <input type="checkbox" checkedLink={link} valueLink={emptyFunction} />; expect(React.renderComponent.bind(React, instance, node)).toThrow(); }); </ins> });


Question:
Consider this example: If is false or undefined, will be and will throw
Want to take a go at fixing this? I think it would be a good opportunity to learn a bit more about a constrained subset of internals.
yea - i'll give it a shot :)

var children = {}; var childMapping = ReactTransitionKeySet.getChildMapping(sourceChildren); var transitionConfig = this.getTransitionConfig(); var currentKeys = ReactTransitionKeySet.mergeKeySets( this._transitionGroupCurrentKeys,

* in `next` in a reasonable order. */ mergeKeySets: function(prev, next) { <ins> prev = prev || {}; next = next || {}; </ins> var keySet = {}; var prevKeys = Object.keys(prev).concat([MERGE_KEY_SETS_TAIL_SENTINEL]); var nextKeys = Object.keys(next).concat([MERGE_KEY_SETS_TAIL_SENTINEL]);

// Most of the real functionality is covered in other unit tests, this just // makes sure we're wired up correctly. describe('ReactTransitionGroup', function() { <ins> var container; </ins> beforeEach(function() { React = require('React'); ReactTransitionGroup = require('ReactTransitionGroup'); mocks = require('mocks'); <ins> container = document.createElement('div'); </ins> }); it('should warn after time with no transitionend', function() { <del> var container; var a; container = document.createElement('div'); a = React.renderComponent( </del> <ins> var a = React.renderComponent( </ins> <ReactTransitionGroup transitionName="yolo"> <span key="one" id="one" /> </ReactTransitionGroup>,

}); it('should keep both sets of DOM nodes around', function() { <del> var container = document.createElement('div'); </del> var a = React.renderComponent( <ReactTransitionGroup transitionName="yolo"> <span key="one" id="one" />

expect(a.getDOMNode().childNodes[0].id).toBe('two'); expect(a.getDOMNode().childNodes[1].id).toBe('one'); }); <ins> describe('with an undefined child', function () { it('should fail silently', function () { var a = React.renderComponent( <ReactTransitionGroup transitionName="yolo"> </ReactTransitionGroup>, container ); }); }); </ins> });

five: true }); }); <ins> it('should support mergeKeySets with undefined input', function () { var prev = { one: true, two: true }; var next = undefined; expect(ReactTransitionKeySet.mergeKeySets(prev, next)).toEqual({ one: true, two: true }); prev = undefined; next = { three: true, four: true }; expect(ReactTransitionKeySet.mergeKeySets(prev, next)).toEqual({ three: true, four: true }); }); </ins> });


Question:
I'd rather do it , if you don't mind.
I think we should do both. I think a forced clean should force clean all of the build artifacts (of which .module-cache is a part of).
can we distinguish between and ?
In what situation would you want to clean but not remove ?
I'm actually not aware of any other use cases for so maybe this is fine. But it still means we need to tell people to do if they encounter problems that might be fixed by doing so, whereas gives us a way to get the same effect with no verbal communication.
I'm going to do it. I think we should probably also do .
Closed by .

var getDebugConfig = function() { return { "debug": true, <ins> "commonerConfig": grunt.config.data.pkg.commonerConfig, </ins> "constants": { "__VERSION__": grunt.config.data.pkg.version, "__DEV__": true

return { "debug": true, "mocking": true, <ins> "commonerConfig": grunt.config.data.pkg.commonerConfig, </ins> "constants": { "__VERSION__": grunt.config.data.pkg.version, "__DEV__": true

getConfig: function() { return { "debug": false, <ins> "commonerConfig": grunt.config.data.pkg.commonerConfig, </ins> "constants": { "__VERSION__": grunt.config.data.pkg.version, "__DEV__": false

"engines": { "node": ">=0.10.0" }, <del> "preferGlobal": true </del> <ins> "preferGlobal": true, "commonerConfig": { "version": 1 } </ins> }