diff options
author | Matt A. Tobin <mattatobin@localhost.localdomain> | 2018-02-02 04:16:08 -0500 |
---|---|---|
committer | Matt A. Tobin <mattatobin@localhost.localdomain> | 2018-02-02 04:16:08 -0500 |
commit | 5f8de423f190bbb79a62f804151bc24824fa32d8 (patch) | |
tree | 10027f336435511475e392454359edea8e25895d /devtools/client/shared/vendor | |
parent | 49ee0794b5d912db1f95dce6eb52d781dc210db5 (diff) | |
download | UXP-5f8de423f190bbb79a62f804151bc24824fa32d8.tar UXP-5f8de423f190bbb79a62f804151bc24824fa32d8.tar.gz UXP-5f8de423f190bbb79a62f804151bc24824fa32d8.tar.lz UXP-5f8de423f190bbb79a62f804151bc24824fa32d8.tar.xz UXP-5f8de423f190bbb79a62f804151bc24824fa32d8.zip |
Add m-esr52 at 52.6.0
Diffstat (limited to 'devtools/client/shared/vendor')
25 files changed, 68969 insertions, 0 deletions
diff --git a/devtools/client/shared/vendor/D3_LICENSE b/devtools/client/shared/vendor/D3_LICENSE new file mode 100644 index 000000000..fb7d95d70 --- /dev/null +++ b/devtools/client/shared/vendor/D3_LICENSE @@ -0,0 +1,26 @@ +Copyright (c) 2014, Michael Bostock +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* The name Michael Bostock may not be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL MICHAEL BOSTOCK BE LIABLE FOR ANY DIRECT, +INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/devtools/client/shared/vendor/DAGRE_D3_LICENSE b/devtools/client/shared/vendor/DAGRE_D3_LICENSE new file mode 100644 index 000000000..1d64ed68c --- /dev/null +++ b/devtools/client/shared/vendor/DAGRE_D3_LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2013 Chris Pettitt + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/devtools/client/shared/vendor/REACT_REDUX_LICENSE b/devtools/client/shared/vendor/REACT_REDUX_LICENSE new file mode 100644 index 000000000..af2353dca --- /dev/null +++ b/devtools/client/shared/vendor/REACT_REDUX_LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Dan Abramov + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/devtools/client/shared/vendor/REACT_REDUX_UPGRADING b/devtools/client/shared/vendor/REACT_REDUX_UPGRADING new file mode 100644 index 000000000..7739751db --- /dev/null +++ b/devtools/client/shared/vendor/REACT_REDUX_UPGRADING @@ -0,0 +1,9 @@ +"react-redux" uses UMD style loading to work in many different environments. +It assumes that "react" and "redux" are both included via `require("react")` +as in node or browserify, but the paths to our react and redux installation are different. + +If upgrading react-redux, define the correct paths and replace the require statements +for the module.exports case with the correct paths. + +Path to react: "devtools/client/shared/vendor/react" +Path to redux: "devtools/client/shared/vendor/redux" diff --git a/devtools/client/shared/vendor/REACT_UPGRADING b/devtools/client/shared/vendor/REACT_UPGRADING new file mode 100644 index 000000000..a82b4fa8c --- /dev/null +++ b/devtools/client/shared/vendor/REACT_UPGRADING @@ -0,0 +1,54 @@ +We use a version of React that has a few minor tweaks. We want to use +an un-minified production version anyway, and because of all of this +you need to build React yourself to upgrade it for devtools. + +First, clone the repo and get ready to build it. Replace `<version>` +with the version tag you are targetting: + +* git clone https://github.com/facebook/react.git +* cd react +* git checkout <version> +* In `src/addons/ReactWithAddons.js`, move the + `React.addons.TestUtils = ...` line outside of the `if` + block to force it be include in the production build + +Next, build React: + +* npm install +* grunt build + +Unfortunately, you need to manually patch the generated JS file. We +need to force React to always create HTML elements, and we do this by +changing all `document.createElement` calls to `createElementNS`. It's +much easier to do this on the generated file to make sure you update +all dependencies as well. + +Open `build/react-with-addons.js` and search for all +`document.createElement` calls and replace them with +`document.createElementNS('http://www.w3.org/1999/xhtml', ...)`. Note +that some code is `ownerDocument.createElement` so don't do a blind +search/replace. There is only about ~12 places to change. + +Now move into our repo (note the naming of `react-dev.js`, it's the dev version): + +* cp build/react-with-addons.js <gecko-dev>/devtools/client/shared/vendor/react-dev.js + +Now we need to generate a production version of React: + +* NODE_ENV=production grunt build + +Unfortunately, you need to manually replace all the `createElement` +calls in this version again. We know this is not ideal but WE NEED TO +MOVE OFF XUL and we don't need to do this anymore once that happens. + +After patching `build/react-with-addons.js` again, copy the production +version over: + +* cp build/react-with-addons.js <gecko-dev>/devtools/client/shared/vendor/react.js + +You also need to copy the ReactDOM package. It requires React, so +right now we are just manually changing the path from `react` to +`devtools/client/shared/vendor/react`. + +* cp build/react-dom.js <gecko-dev>/devtools/client/shared/vendor/react-dom.js +* (change `require('react')` at the top of the file to the right path) diff --git a/devtools/client/shared/vendor/REACT_VIRTUALIZED_UPGRADING b/devtools/client/shared/vendor/REACT_VIRTUALIZED_UPGRADING new file mode 100644 index 000000000..50e0c1817 --- /dev/null +++ b/devtools/client/shared/vendor/REACT_VIRTUALIZED_UPGRADING @@ -0,0 +1,14 @@ +"react-virtualized" uses UMD style loading to work in many different environments. +It assumes that "react", "react-addons-shallow-compare", and "react-dom" are all included +separately via require statements. The paths to our installations are different. + +If upgrading: + +- Define the correct paths for React, etc and replace the require statements for the + module.exports case with the correct paths. +- Replace any references to React.addons.shallowCompare with the webpack module id. +- To support use in XUL documents, replace calls to createElement with + createElementNS("http://www.w3.org/1999/xhtml", but make sure that you aren't replacing + any calls to React.createElement. +- Also required for XUL, replace document.head and document.body with + document.firstElementChild diff --git a/devtools/client/shared/vendor/REDUX_LICENSE b/devtools/client/shared/vendor/REDUX_LICENSE new file mode 100644 index 000000000..af2353dca --- /dev/null +++ b/devtools/client/shared/vendor/REDUX_LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Dan Abramov + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/devtools/client/shared/vendor/REDUX_UPGRADING b/devtools/client/shared/vendor/REDUX_UPGRADING new file mode 100644 index 000000000..fbbbfc8e3 --- /dev/null +++ b/devtools/client/shared/vendor/REDUX_UPGRADING @@ -0,0 +1,10 @@ +REDUX_UPGRADING + +Current version of redux : 3.3.0 + +1 - grab the unminified version of redux on npm. For release 3.3.0 for instance, +https://npmcdn.com/redux@3.3.0/dist/redux.js + +2 - replace the content of devtools/client/shared/vendor + +3 - update the current version in this file
\ No newline at end of file diff --git a/devtools/client/shared/vendor/RESELECT_LICENSE b/devtools/client/shared/vendor/RESELECT_LICENSE new file mode 100644 index 000000000..1ca1e449f --- /dev/null +++ b/devtools/client/shared/vendor/RESELECT_LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015-2016 Reselect Contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/devtools/client/shared/vendor/RESELECT_UPGRADING b/devtools/client/shared/vendor/RESELECT_UPGRADING new file mode 100644 index 000000000..b846d05be --- /dev/null +++ b/devtools/client/shared/vendor/RESELECT_UPGRADING @@ -0,0 +1,7 @@ +Follow these steps when adding/upgrading the reselect.js module: + +1. git clone https://github.com/reactjs/reselect - clone the repo +2. npm install - compile the sources to a compiled JS module file +3. cp dist/reselect.js $DEST_DIR - copy the compiled file to Firefox source tree + +The package version used it currently 2.5.4 (last update in bug 1310573) diff --git a/devtools/client/shared/vendor/d3.js b/devtools/client/shared/vendor/d3.js new file mode 100644 index 000000000..2f645354c --- /dev/null +++ b/devtools/client/shared/vendor/d3.js @@ -0,0 +1,9275 @@ +!function() { + var d3 = { + version: "3.4.2" + }; + if (!Date.now) Date.now = function() { + return +new Date(); + }; + var d3_arraySlice = [].slice, d3_array = function(list) { + return d3_arraySlice.call(list); + }; + var d3_document = document, d3_documentElement = d3_document.documentElement, d3_window = window; + try { + d3_array(d3_documentElement.childNodes)[0].nodeType; + } catch (e) { + d3_array = function(list) { + var i = list.length, array = new Array(i); + while (i--) array[i] = list[i]; + return array; + }; + } + try { + d3_document.createElement("div").style.setProperty("opacity", 0, ""); + } catch (error) { + var d3_element_prototype = d3_window.Element.prototype, d3_element_setAttribute = d3_element_prototype.setAttribute, d3_element_setAttributeNS = d3_element_prototype.setAttributeNS, d3_style_prototype = d3_window.CSSStyleDeclaration.prototype, d3_style_setProperty = d3_style_prototype.setProperty; + d3_element_prototype.setAttribute = function(name, value) { + d3_element_setAttribute.call(this, name, value + ""); + }; + d3_element_prototype.setAttributeNS = function(space, local, value) { + d3_element_setAttributeNS.call(this, space, local, value + ""); + }; + d3_style_prototype.setProperty = function(name, value, priority) { + d3_style_setProperty.call(this, name, value + "", priority); + }; + } + d3.ascending = function(a, b) { + return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN; + }; + d3.descending = function(a, b) { + return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN; + }; + d3.min = function(array, f) { + var i = -1, n = array.length, a, b; + if (arguments.length === 1) { + while (++i < n && !((a = array[i]) != null && a <= a)) a = undefined; + while (++i < n) if ((b = array[i]) != null && a > b) a = b; + } else { + while (++i < n && !((a = f.call(array, array[i], i)) != null && a <= a)) a = undefined; + while (++i < n) if ((b = f.call(array, array[i], i)) != null && a > b) a = b; + } + return a; + }; + d3.max = function(array, f) { + var i = -1, n = array.length, a, b; + if (arguments.length === 1) { + while (++i < n && !((a = array[i]) != null && a <= a)) a = undefined; + while (++i < n) if ((b = array[i]) != null && b > a) a = b; + } else { + while (++i < n && !((a = f.call(array, array[i], i)) != null && a <= a)) a = undefined; + while (++i < n) if ((b = f.call(array, array[i], i)) != null && b > a) a = b; + } + return a; + }; + d3.extent = function(array, f) { + var i = -1, n = array.length, a, b, c; + if (arguments.length === 1) { + while (++i < n && !((a = c = array[i]) != null && a <= a)) a = c = undefined; + while (++i < n) if ((b = array[i]) != null) { + if (a > b) a = b; + if (c < b) c = b; + } + } else { + while (++i < n && !((a = c = f.call(array, array[i], i)) != null && a <= a)) a = undefined; + while (++i < n) if ((b = f.call(array, array[i], i)) != null) { + if (a > b) a = b; + if (c < b) c = b; + } + } + return [ a, c ]; + }; + d3.sum = function(array, f) { + var s = 0, n = array.length, a, i = -1; + if (arguments.length === 1) { + while (++i < n) if (!isNaN(a = +array[i])) s += a; + } else { + while (++i < n) if (!isNaN(a = +f.call(array, array[i], i))) s += a; + } + return s; + }; + function d3_number(x) { + return x != null && !isNaN(x); + } + d3.mean = function(array, f) { + var n = array.length, a, m = 0, i = -1, j = 0; + if (arguments.length === 1) { + while (++i < n) if (d3_number(a = array[i])) m += (a - m) / ++j; + } else { + while (++i < n) if (d3_number(a = f.call(array, array[i], i))) m += (a - m) / ++j; + } + return j ? m : undefined; + }; + d3.quantile = function(values, p) { + var H = (values.length - 1) * p + 1, h = Math.floor(H), v = +values[h - 1], e = H - h; + return e ? v + e * (values[h] - v) : v; + }; + d3.median = function(array, f) { + if (arguments.length > 1) array = array.map(f); + array = array.filter(d3_number); + return array.length ? d3.quantile(array.sort(d3.ascending), .5) : undefined; + }; + d3.bisector = function(f) { + return { + left: function(a, x, lo, hi) { + if (arguments.length < 3) lo = 0; + if (arguments.length < 4) hi = a.length; + while (lo < hi) { + var mid = lo + hi >>> 1; + if (f.call(a, a[mid], mid) < x) lo = mid + 1; else hi = mid; + } + return lo; + }, + right: function(a, x, lo, hi) { + if (arguments.length < 3) lo = 0; + if (arguments.length < 4) hi = a.length; + while (lo < hi) { + var mid = lo + hi >>> 1; + if (x < f.call(a, a[mid], mid)) hi = mid; else lo = mid + 1; + } + return lo; + } + }; + }; + var d3_bisector = d3.bisector(function(d) { + return d; + }); + d3.bisectLeft = d3_bisector.left; + d3.bisect = d3.bisectRight = d3_bisector.right; + d3.shuffle = function(array) { + var m = array.length, t, i; + while (m) { + i = Math.random() * m-- | 0; + t = array[m], array[m] = array[i], array[i] = t; + } + return array; + }; + d3.permute = function(array, indexes) { + var i = indexes.length, permutes = new Array(i); + while (i--) permutes[i] = array[indexes[i]]; + return permutes; + }; + d3.pairs = function(array) { + var i = 0, n = array.length - 1, p0, p1 = array[0], pairs = new Array(n < 0 ? 0 : n); + while (i < n) pairs[i] = [ p0 = p1, p1 = array[++i] ]; + return pairs; + }; + d3.zip = function() { + if (!(n = arguments.length)) return []; + for (var i = -1, m = d3.min(arguments, d3_zipLength), zips = new Array(m); ++i < m; ) { + for (var j = -1, n, zip = zips[i] = new Array(n); ++j < n; ) { + zip[j] = arguments[j][i]; + } + } + return zips; + }; + function d3_zipLength(d) { + return d.length; + } + d3.transpose = function(matrix) { + return d3.zip.apply(d3, matrix); + }; + d3.keys = function(map) { + var keys = []; + for (var key in map) keys.push(key); + return keys; + }; + d3.values = function(map) { + var values = []; + for (var key in map) values.push(map[key]); + return values; + }; + d3.entries = function(map) { + var entries = []; + for (var key in map) entries.push({ + key: key, + value: map[key] + }); + return entries; + }; + d3.merge = function(arrays) { + var n = arrays.length, m, i = -1, j = 0, merged, array; + while (++i < n) j += arrays[i].length; + merged = new Array(j); + while (--n >= 0) { + array = arrays[n]; + m = array.length; + while (--m >= 0) { + merged[--j] = array[m]; + } + } + return merged; + }; + var abs = Math.abs; + d3.range = function(start, stop, step) { + if (arguments.length < 3) { + step = 1; + if (arguments.length < 2) { + stop = start; + start = 0; + } + } + if ((stop - start) / step === Infinity) throw new Error("infinite range"); + var range = [], k = d3_range_integerScale(abs(step)), i = -1, j; + start *= k, stop *= k, step *= k; + if (step < 0) while ((j = start + step * ++i) > stop) range.push(j / k); else while ((j = start + step * ++i) < stop) range.push(j / k); + return range; + }; + function d3_range_integerScale(x) { + var k = 1; + while (x * k % 1) k *= 10; + return k; + } + function d3_class(ctor, properties) { + try { + for (var key in properties) { + Object.defineProperty(ctor.prototype, key, { + value: properties[key], + enumerable: false + }); + } + } catch (e) { + ctor.prototype = properties; + } + } + d3.map = function(object) { + var map = new d3_Map(); + if (object instanceof d3_Map) object.forEach(function(key, value) { + map.set(key, value); + }); else for (var key in object) map.set(key, object[key]); + return map; + }; + function d3_Map() {} + d3_class(d3_Map, { + has: d3_map_has, + get: function(key) { + return this[d3_map_prefix + key]; + }, + set: function(key, value) { + return this[d3_map_prefix + key] = value; + }, + remove: d3_map_remove, + keys: d3_map_keys, + values: function() { + var values = []; + this.forEach(function(key, value) { + values.push(value); + }); + return values; + }, + entries: function() { + var entries = []; + this.forEach(function(key, value) { + entries.push({ + key: key, + value: value + }); + }); + return entries; + }, + size: d3_map_size, + empty: d3_map_empty, + forEach: function(f) { + for (var key in this) if (key.charCodeAt(0) === d3_map_prefixCode) f.call(this, key.substring(1), this[key]); + } + }); + var d3_map_prefix = "\x00", d3_map_prefixCode = d3_map_prefix.charCodeAt(0); + function d3_map_has(key) { + return d3_map_prefix + key in this; + } + function d3_map_remove(key) { + key = d3_map_prefix + key; + return key in this && delete this[key]; + } + function d3_map_keys() { + var keys = []; + this.forEach(function(key) { + keys.push(key); + }); + return keys; + } + function d3_map_size() { + var size = 0; + for (var key in this) if (key.charCodeAt(0) === d3_map_prefixCode) ++size; + return size; + } + function d3_map_empty() { + for (var key in this) if (key.charCodeAt(0) === d3_map_prefixCode) return false; + return true; + } + d3.nest = function() { + var nest = {}, keys = [], sortKeys = [], sortValues, rollup; + function map(mapType, array, depth) { + if (depth >= keys.length) return rollup ? rollup.call(nest, array) : sortValues ? array.sort(sortValues) : array; + var i = -1, n = array.length, key = keys[depth++], keyValue, object, setter, valuesByKey = new d3_Map(), values; + while (++i < n) { + if (values = valuesByKey.get(keyValue = key(object = array[i]))) { + values.push(object); + } else { + valuesByKey.set(keyValue, [ object ]); + } + } + if (mapType) { + object = mapType(); + setter = function(keyValue, values) { + object.set(keyValue, map(mapType, values, depth)); + }; + } else { + object = {}; + setter = function(keyValue, values) { + object[keyValue] = map(mapType, values, depth); + }; + } + valuesByKey.forEach(setter); + return object; + } + function entries(map, depth) { + if (depth >= keys.length) return map; + var array = [], sortKey = sortKeys[depth++]; + map.forEach(function(key, keyMap) { + array.push({ + key: key, + values: entries(keyMap, depth) + }); + }); + return sortKey ? array.sort(function(a, b) { + return sortKey(a.key, b.key); + }) : array; + } + nest.map = function(array, mapType) { + return map(mapType, array, 0); + }; + nest.entries = function(array) { + return entries(map(d3.map, array, 0), 0); + }; + nest.key = function(d) { + keys.push(d); + return nest; + }; + nest.sortKeys = function(order) { + sortKeys[keys.length - 1] = order; + return nest; + }; + nest.sortValues = function(order) { + sortValues = order; + return nest; + }; + nest.rollup = function(f) { + rollup = f; + return nest; + }; + return nest; + }; + d3.set = function(array) { + var set = new d3_Set(); + if (array) for (var i = 0, n = array.length; i < n; ++i) set.add(array[i]); + return set; + }; + function d3_Set() {} + d3_class(d3_Set, { + has: d3_map_has, + add: function(value) { + this[d3_map_prefix + value] = true; + return value; + }, + remove: function(value) { + value = d3_map_prefix + value; + return value in this && delete this[value]; + }, + values: d3_map_keys, + size: d3_map_size, + empty: d3_map_empty, + forEach: function(f) { + for (var value in this) if (value.charCodeAt(0) === d3_map_prefixCode) f.call(this, value.substring(1)); + } + }); + d3.behavior = {}; + d3.rebind = function(target, source) { + var i = 1, n = arguments.length, method; + while (++i < n) target[method = arguments[i]] = d3_rebind(target, source, source[method]); + return target; + }; + function d3_rebind(target, source, method) { + return function() { + var value = method.apply(source, arguments); + return value === source ? target : value; + }; + } + function d3_vendorSymbol(object, name) { + if (name in object) return name; + name = name.charAt(0).toUpperCase() + name.substring(1); + for (var i = 0, n = d3_vendorPrefixes.length; i < n; ++i) { + var prefixName = d3_vendorPrefixes[i] + name; + if (prefixName in object) return prefixName; + } + } + var d3_vendorPrefixes = [ "webkit", "ms", "moz", "Moz", "o", "O" ]; + function d3_noop() {} + d3.dispatch = function() { + var dispatch = new d3_dispatch(), i = -1, n = arguments.length; + while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch); + return dispatch; + }; + function d3_dispatch() {} + d3_dispatch.prototype.on = function(type, listener) { + var i = type.indexOf("."), name = ""; + if (i >= 0) { + name = type.substring(i + 1); + type = type.substring(0, i); + } + if (type) return arguments.length < 2 ? this[type].on(name) : this[type].on(name, listener); + if (arguments.length === 2) { + if (listener == null) for (type in this) { + if (this.hasOwnProperty(type)) this[type].on(name, null); + } + return this; + } + }; + function d3_dispatch_event(dispatch) { + var listeners = [], listenerByName = new d3_Map(); + function event() { + var z = listeners, i = -1, n = z.length, l; + while (++i < n) if (l = z[i].on) l.apply(this, arguments); + return dispatch; + } + event.on = function(name, listener) { + var l = listenerByName.get(name), i; + if (arguments.length < 2) return l && l.on; + if (l) { + l.on = null; + listeners = listeners.slice(0, i = listeners.indexOf(l)).concat(listeners.slice(i + 1)); + listenerByName.remove(name); + } + if (listener) listeners.push(listenerByName.set(name, { + on: listener + })); + return dispatch; + }; + return event; + } + d3.event = null; + function d3_eventPreventDefault() { + d3.event.preventDefault(); + } + function d3_eventSource() { + var e = d3.event, s; + while (s = e.sourceEvent) e = s; + return e; + } + function d3_eventDispatch(target) { + var dispatch = new d3_dispatch(), i = 0, n = arguments.length; + while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch); + dispatch.of = function(thiz, argumentz) { + return function(e1) { + try { + var e0 = e1.sourceEvent = d3.event; + e1.target = target; + d3.event = e1; + dispatch[e1.type].apply(thiz, argumentz); + } finally { + d3.event = e0; + } + }; + }; + return dispatch; + } + d3.requote = function(s) { + return s.replace(d3_requote_re, "\\$&"); + }; + var d3_requote_re = /[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g; + var d3_subclass = {}.__proto__ ? function(object, prototype) { + object.__proto__ = prototype; + } : function(object, prototype) { + for (var property in prototype) object[property] = prototype[property]; + }; + function d3_selection(groups) { + d3_subclass(groups, d3_selectionPrototype); + return groups; + } + var d3_select = function(s, n) { + return n.querySelector(s); + }, d3_selectAll = function(s, n) { + return n.querySelectorAll(s); + }, d3_selectMatcher = d3_documentElement[d3_vendorSymbol(d3_documentElement, "matchesSelector")], d3_selectMatches = function(n, s) { + return d3_selectMatcher.call(n, s); + }; + if (typeof Sizzle === "function") { + d3_select = function(s, n) { + return Sizzle(s, n)[0] || null; + }; + d3_selectAll = function(s, n) { + return Sizzle.uniqueSort(Sizzle(s, n)); + }; + d3_selectMatches = Sizzle.matchesSelector; + } + d3.selection = function() { + return d3_selectionRoot; + }; + var d3_selectionPrototype = d3.selection.prototype = []; + d3_selectionPrototype.select = function(selector) { + var subgroups = [], subgroup, subnode, group, node; + selector = d3_selection_selector(selector); + for (var j = -1, m = this.length; ++j < m; ) { + subgroups.push(subgroup = []); + subgroup.parentNode = (group = this[j]).parentNode; + for (var i = -1, n = group.length; ++i < n; ) { + if (node = group[i]) { + subgroup.push(subnode = selector.call(node, node.__data__, i, j)); + if (subnode && "__data__" in node) subnode.__data__ = node.__data__; + } else { + subgroup.push(null); + } + } + } + return d3_selection(subgroups); + }; + function d3_selection_selector(selector) { + return typeof selector === "function" ? selector : function() { + return d3_select(selector, this); + }; + } + d3_selectionPrototype.selectAll = function(selector) { + var subgroups = [], subgroup, node; + selector = d3_selection_selectorAll(selector); + for (var j = -1, m = this.length; ++j < m; ) { + for (var group = this[j], i = -1, n = group.length; ++i < n; ) { + if (node = group[i]) { + subgroups.push(subgroup = d3_array(selector.call(node, node.__data__, i, j))); + subgroup.parentNode = node; + } + } + } + return d3_selection(subgroups); + }; + function d3_selection_selectorAll(selector) { + return typeof selector === "function" ? selector : function() { + return d3_selectAll(selector, this); + }; + } + var d3_nsPrefix = { + svg: "http://www.w3.org/2000/svg", + xhtml: "http://www.w3.org/1999/xhtml", + xlink: "http://www.w3.org/1999/xlink", + xml: "http://www.w3.org/XML/1998/namespace", + xmlns: "http://www.w3.org/2000/xmlns/" + }; + d3.ns = { + prefix: d3_nsPrefix, + qualify: function(name) { + var i = name.indexOf(":"), prefix = name; + if (i >= 0) { + prefix = name.substring(0, i); + name = name.substring(i + 1); + } + return d3_nsPrefix.hasOwnProperty(prefix) ? { + space: d3_nsPrefix[prefix], + local: name + } : name; + } + }; + d3_selectionPrototype.attr = function(name, value) { + if (arguments.length < 2) { + if (typeof name === "string") { + var node = this.node(); + name = d3.ns.qualify(name); + return name.local ? node.getAttributeNS(name.space, name.local) : node.getAttribute(name); + } + for (value in name) this.each(d3_selection_attr(value, name[value])); + return this; + } + return this.each(d3_selection_attr(name, value)); + }; + function d3_selection_attr(name, value) { + name = d3.ns.qualify(name); + function attrNull() { + this.removeAttribute(name); + } + function attrNullNS() { + this.removeAttributeNS(name.space, name.local); + } + function attrConstant() { + this.setAttribute(name, value); + } + function attrConstantNS() { + this.setAttributeNS(name.space, name.local, value); + } + function attrFunction() { + var x = value.apply(this, arguments); + if (x == null) this.removeAttribute(name); else this.setAttribute(name, x); + } + function attrFunctionNS() { + var x = value.apply(this, arguments); + if (x == null) this.removeAttributeNS(name.space, name.local); else this.setAttributeNS(name.space, name.local, x); + } + return value == null ? name.local ? attrNullNS : attrNull : typeof value === "function" ? name.local ? attrFunctionNS : attrFunction : name.local ? attrConstantNS : attrConstant; + } + function d3_collapse(s) { + return s.trim().replace(/\s+/g, " "); + } + d3_selectionPrototype.classed = function(name, value) { + if (arguments.length < 2) { + if (typeof name === "string") { + var node = this.node(), n = (name = d3_selection_classes(name)).length, i = -1; + if (value = node.classList) { + while (++i < n) if (!value.contains(name[i])) return false; + } else { + value = node.getAttribute("class"); + while (++i < n) if (!d3_selection_classedRe(name[i]).test(value)) return false; + } + return true; + } + for (value in name) this.each(d3_selection_classed(value, name[value])); + return this; + } + return this.each(d3_selection_classed(name, value)); + }; + function d3_selection_classedRe(name) { + return new RegExp("(?:^|\\s+)" + d3.requote(name) + "(?:\\s+|$)", "g"); + } + function d3_selection_classes(name) { + return name.trim().split(/^|\s+/); + } + function d3_selection_classed(name, value) { + name = d3_selection_classes(name).map(d3_selection_classedName); + var n = name.length; + function classedConstant() { + var i = -1; + while (++i < n) name[i](this, value); + } + function classedFunction() { + var i = -1, x = value.apply(this, arguments); + while (++i < n) name[i](this, x); + } + return typeof value === "function" ? classedFunction : classedConstant; + } + function d3_selection_classedName(name) { + var re = d3_selection_classedRe(name); + return function(node, value) { + if (c = node.classList) return value ? c.add(name) : c.remove(name); + var c = node.getAttribute("class") || ""; + if (value) { + re.lastIndex = 0; + if (!re.test(c)) node.setAttribute("class", d3_collapse(c + " " + name)); + } else { + node.setAttribute("class", d3_collapse(c.replace(re, " "))); + } + }; + } + d3_selectionPrototype.style = function(name, value, priority) { + var n = arguments.length; + if (n < 3) { + if (typeof name !== "string") { + if (n < 2) value = ""; + for (priority in name) this.each(d3_selection_style(priority, name[priority], value)); + return this; + } + if (n < 2) return d3_window.getComputedStyle(this.node(), null).getPropertyValue(name); + priority = ""; + } + return this.each(d3_selection_style(name, value, priority)); + }; + function d3_selection_style(name, value, priority) { + function styleNull() { + this.style.removeProperty(name); + } + function styleConstant() { + this.style.setProperty(name, value, priority); + } + function styleFunction() { + var x = value.apply(this, arguments); + if (x == null) this.style.removeProperty(name); else this.style.setProperty(name, x, priority); + } + return value == null ? styleNull : typeof value === "function" ? styleFunction : styleConstant; + } + d3_selectionPrototype.property = function(name, value) { + if (arguments.length < 2) { + if (typeof name === "string") return this.node()[name]; + for (value in name) this.each(d3_selection_property(value, name[value])); + return this; + } + return this.each(d3_selection_property(name, value)); + }; + function d3_selection_property(name, value) { + function propertyNull() { + delete this[name]; + } + function propertyConstant() { + this[name] = value; + } + function propertyFunction() { + var x = value.apply(this, arguments); + if (x == null) delete this[name]; else this[name] = x; + } + return value == null ? propertyNull : typeof value === "function" ? propertyFunction : propertyConstant; + } + d3_selectionPrototype.text = function(value) { + return arguments.length ? this.each(typeof value === "function" ? function() { + var v = value.apply(this, arguments); + this.textContent = v == null ? "" : v; + } : value == null ? function() { + this.textContent = ""; + } : function() { + this.textContent = value; + }) : this.node().textContent; + }; + d3_selectionPrototype.html = function(value) { + return arguments.length ? this.each(typeof value === "function" ? function() { + var v = value.apply(this, arguments); + this.innerHTML = v == null ? "" : v; + } : value == null ? function() { + this.innerHTML = ""; + } : function() { + this.innerHTML = value; + }) : this.node().innerHTML; + }; + d3_selectionPrototype.append = function(name) { + name = d3_selection_creator(name); + return this.select(function() { + return this.appendChild(name.apply(this, arguments)); + }); + }; + function d3_selection_creator(name) { + return typeof name === "function" ? name : (name = d3.ns.qualify(name)).local ? function() { + return this.ownerDocument.createElementNS(name.space, name.local); + } : function() { + return this.ownerDocument.createElementNS(this.namespaceURI, name); + }; + } + d3_selectionPrototype.insert = function(name, before) { + name = d3_selection_creator(name); + before = d3_selection_selector(before); + return this.select(function() { + return this.insertBefore(name.apply(this, arguments), before.apply(this, arguments) || null); + }); + }; + d3_selectionPrototype.remove = function() { + return this.each(function() { + var parent = this.parentNode; + if (parent) parent.removeChild(this); + }); + }; + d3_selectionPrototype.data = function(value, key) { + var i = -1, n = this.length, group, node; + if (!arguments.length) { + value = new Array(n = (group = this[0]).length); + while (++i < n) { + if (node = group[i]) { + value[i] = node.__data__; + } + } + return value; + } + function bind(group, groupData) { + var i, n = group.length, m = groupData.length, n0 = Math.min(n, m), updateNodes = new Array(m), enterNodes = new Array(m), exitNodes = new Array(n), node, nodeData; + if (key) { + var nodeByKeyValue = new d3_Map(), dataByKeyValue = new d3_Map(), keyValues = [], keyValue; + for (i = -1; ++i < n; ) { + keyValue = key.call(node = group[i], node.__data__, i); + if (nodeByKeyValue.has(keyValue)) { + exitNodes[i] = node; + } else { + nodeByKeyValue.set(keyValue, node); + } + keyValues.push(keyValue); + } + for (i = -1; ++i < m; ) { + keyValue = key.call(groupData, nodeData = groupData[i], i); + if (node = nodeByKeyValue.get(keyValue)) { + updateNodes[i] = node; + node.__data__ = nodeData; + } else if (!dataByKeyValue.has(keyValue)) { + enterNodes[i] = d3_selection_dataNode(nodeData); + } + dataByKeyValue.set(keyValue, nodeData); + nodeByKeyValue.remove(keyValue); + } + for (i = -1; ++i < n; ) { + if (nodeByKeyValue.has(keyValues[i])) { + exitNodes[i] = group[i]; + } + } + } else { + for (i = -1; ++i < n0; ) { + node = group[i]; + nodeData = groupData[i]; + if (node) { + node.__data__ = nodeData; + updateNodes[i] = node; + } else { + enterNodes[i] = d3_selection_dataNode(nodeData); + } + } + for (;i < m; ++i) { + enterNodes[i] = d3_selection_dataNode(groupData[i]); + } + for (;i < n; ++i) { + exitNodes[i] = group[i]; + } + } + enterNodes.update = updateNodes; + enterNodes.parentNode = updateNodes.parentNode = exitNodes.parentNode = group.parentNode; + enter.push(enterNodes); + update.push(updateNodes); + exit.push(exitNodes); + } + var enter = d3_selection_enter([]), update = d3_selection([]), exit = d3_selection([]); + if (typeof value === "function") { + while (++i < n) { + bind(group = this[i], value.call(group, group.parentNode.__data__, i)); + } + } else { + while (++i < n) { + bind(group = this[i], value); + } + } + update.enter = function() { + return enter; + }; + update.exit = function() { + return exit; + }; + return update; + }; + function d3_selection_dataNode(data) { + return { + __data__: data + }; + } + d3_selectionPrototype.datum = function(value) { + return arguments.length ? this.property("__data__", value) : this.property("__data__"); + }; + d3_selectionPrototype.filter = function(filter) { + var subgroups = [], subgroup, group, node; + if (typeof filter !== "function") filter = d3_selection_filter(filter); + for (var j = 0, m = this.length; j < m; j++) { + subgroups.push(subgroup = []); + subgroup.parentNode = (group = this[j]).parentNode; + for (var i = 0, n = group.length; i < n; i++) { + if ((node = group[i]) && filter.call(node, node.__data__, i, j)) { + subgroup.push(node); + } + } + } + return d3_selection(subgroups); + }; + function d3_selection_filter(selector) { + return function() { + return d3_selectMatches(this, selector); + }; + } + d3_selectionPrototype.order = function() { + for (var j = -1, m = this.length; ++j < m; ) { + for (var group = this[j], i = group.length - 1, next = group[i], node; --i >= 0; ) { + if (node = group[i]) { + if (next && next !== node.nextSibling) next.parentNode.insertBefore(node, next); + next = node; + } + } + } + return this; + }; + d3_selectionPrototype.sort = function(comparator) { + comparator = d3_selection_sortComparator.apply(this, arguments); + for (var j = -1, m = this.length; ++j < m; ) this[j].sort(comparator); + return this.order(); + }; + function d3_selection_sortComparator(comparator) { + if (!arguments.length) comparator = d3.ascending; + return function(a, b) { + return a && b ? comparator(a.__data__, b.__data__) : !a - !b; + }; + } + d3_selectionPrototype.each = function(callback) { + return d3_selection_each(this, function(node, i, j) { + callback.call(node, node.__data__, i, j); + }); + }; + function d3_selection_each(groups, callback) { + for (var j = 0, m = groups.length; j < m; j++) { + for (var group = groups[j], i = 0, n = group.length, node; i < n; i++) { + if (node = group[i]) callback(node, i, j); + } + } + return groups; + } + d3_selectionPrototype.call = function(callback) { + var args = d3_array(arguments); + callback.apply(args[0] = this, args); + return this; + }; + d3_selectionPrototype.empty = function() { + return !this.node(); + }; + d3_selectionPrototype.node = function() { + for (var j = 0, m = this.length; j < m; j++) { + for (var group = this[j], i = 0, n = group.length; i < n; i++) { + var node = group[i]; + if (node) return node; + } + } + return null; + }; + d3_selectionPrototype.size = function() { + var n = 0; + this.each(function() { + ++n; + }); + return n; + }; + function d3_selection_enter(selection) { + d3_subclass(selection, d3_selection_enterPrototype); + return selection; + } + var d3_selection_enterPrototype = []; + d3.selection.enter = d3_selection_enter; + d3.selection.enter.prototype = d3_selection_enterPrototype; + d3_selection_enterPrototype.append = d3_selectionPrototype.append; + d3_selection_enterPrototype.empty = d3_selectionPrototype.empty; + d3_selection_enterPrototype.node = d3_selectionPrototype.node; + d3_selection_enterPrototype.call = d3_selectionPrototype.call; + d3_selection_enterPrototype.size = d3_selectionPrototype.size; + d3_selection_enterPrototype.select = function(selector) { + var subgroups = [], subgroup, subnode, upgroup, group, node; + for (var j = -1, m = this.length; ++j < m; ) { + upgroup = (group = this[j]).update; + subgroups.push(subgroup = []); + subgroup.parentNode = group.parentNode; + for (var i = -1, n = group.length; ++i < n; ) { + if (node = group[i]) { + subgroup.push(upgroup[i] = subnode = selector.call(group.parentNode, node.__data__, i, j)); + subnode.__data__ = node.__data__; + } else { + subgroup.push(null); + } + } + } + return d3_selection(subgroups); + }; + d3_selection_enterPrototype.insert = function(name, before) { + if (arguments.length < 2) before = d3_selection_enterInsertBefore(this); + return d3_selectionPrototype.insert.call(this, name, before); + }; + function d3_selection_enterInsertBefore(enter) { + var i0, j0; + return function(d, i, j) { + var group = enter[j].update, n = group.length, node; + if (j != j0) j0 = j, i0 = 0; + if (i >= i0) i0 = i + 1; + while (!(node = group[i0]) && ++i0 < n) ; + return node; + }; + } + d3_selectionPrototype.transition = function() { + var id = d3_transitionInheritId || ++d3_transitionId, subgroups = [], subgroup, node, transition = d3_transitionInherit || { + time: Date.now(), + ease: d3_ease_cubicInOut, + delay: 0, + duration: 250 + }; + for (var j = -1, m = this.length; ++j < m; ) { + subgroups.push(subgroup = []); + for (var group = this[j], i = -1, n = group.length; ++i < n; ) { + if (node = group[i]) d3_transitionNode(node, i, id, transition); + subgroup.push(node); + } + } + return d3_transition(subgroups, id); + }; + d3_selectionPrototype.interrupt = function() { + return this.each(d3_selection_interrupt); + }; + function d3_selection_interrupt() { + var lock = this.__transition__; + if (lock) ++lock.active; + } + d3.select = function(node) { + var group = [ typeof node === "string" ? d3_select(node, d3_document) : node ]; + group.parentNode = d3_documentElement; + return d3_selection([ group ]); + }; + d3.selectAll = function(nodes) { + var group = d3_array(typeof nodes === "string" ? d3_selectAll(nodes, d3_document) : nodes); + group.parentNode = d3_documentElement; + return d3_selection([ group ]); + }; + var d3_selectionRoot = d3.select(d3_documentElement); + d3_selectionPrototype.on = function(type, listener, capture) { + var n = arguments.length; + if (n < 3) { + if (typeof type !== "string") { + if (n < 2) listener = false; + for (capture in type) this.each(d3_selection_on(capture, type[capture], listener)); + return this; + } + if (n < 2) return (n = this.node()["__on" + type]) && n._; + capture = false; + } + return this.each(d3_selection_on(type, listener, capture)); + }; + function d3_selection_on(type, listener, capture) { + var name = "__on" + type, i = type.indexOf("."), wrap = d3_selection_onListener; + if (i > 0) type = type.substring(0, i); + var filter = d3_selection_onFilters.get(type); + if (filter) type = filter, wrap = d3_selection_onFilter; + function onRemove() { + var l = this[name]; + if (l) { + this.removeEventListener(type, l, l.$); + delete this[name]; + } + } + function onAdd() { + var l = wrap(listener, d3_array(arguments)); + onRemove.call(this); + this.addEventListener(type, this[name] = l, l.$ = capture); + l._ = listener; + } + function removeAll() { + var re = new RegExp("^__on([^.]+)" + d3.requote(type) + "$"), match; + for (var name in this) { + if (match = name.match(re)) { + var l = this[name]; + this.removeEventListener(match[1], l, l.$); + delete this[name]; + } + } + } + return i ? listener ? onAdd : onRemove : listener ? d3_noop : removeAll; + } + var d3_selection_onFilters = d3.map({ + mouseenter: "mouseover", + mouseleave: "mouseout" + }); + d3_selection_onFilters.forEach(function(k) { + if ("on" + k in d3_document) d3_selection_onFilters.remove(k); + }); + function d3_selection_onListener(listener, argumentz) { + return function(e) { + var o = d3.event; + d3.event = e; + argumentz[0] = this.__data__; + try { + listener.apply(this, argumentz); + } finally { + d3.event = o; + } + }; + } + function d3_selection_onFilter(listener, argumentz) { + var l = d3_selection_onListener(listener, argumentz); + return function(e) { + var target = this, related = e.relatedTarget; + if (!related || related !== target && !(related.compareDocumentPosition(target) & 8)) { + l.call(target, e); + } + }; + } + var d3_event_dragSelect = "onselectstart" in d3_document ? null : d3_vendorSymbol(d3_documentElement.style, "userSelect"), d3_event_dragId = 0; + function d3_event_dragSuppress() { + var name = ".dragsuppress-" + ++d3_event_dragId, click = "click" + name, w = d3.select(d3_window).on("touchmove" + name, d3_eventPreventDefault).on("dragstart" + name, d3_eventPreventDefault).on("selectstart" + name, d3_eventPreventDefault); + if (d3_event_dragSelect) { + var style = d3_documentElement.style, select = style[d3_event_dragSelect]; + style[d3_event_dragSelect] = "none"; + } + return function(suppressClick) { + w.on(name, null); + if (d3_event_dragSelect) style[d3_event_dragSelect] = select; + if (suppressClick) { + function off() { + w.on(click, null); + } + w.on(click, function() { + d3_eventPreventDefault(); + off(); + }, true); + setTimeout(off, 0); + } + }; + } + d3.mouse = function(container) { + return d3_mousePoint(container, d3_eventSource()); + }; + var d3_mouse_bug44083 = /WebKit/.test(d3_window.navigator.userAgent) ? -1 : 0; + function d3_mousePoint(container, e) { + if (e.changedTouches) e = e.changedTouches[0]; + var svg = container.ownerSVGElement || container; + if (svg.createSVGPoint) { + var point = svg.createSVGPoint(); + if (d3_mouse_bug44083 < 0 && (d3_window.scrollX || d3_window.scrollY)) { + svg = d3.select("body").append("svg").style({ + position: "absolute", + top: 0, + left: 0, + margin: 0, + padding: 0, + border: "none" + }, "important"); + var ctm = svg[0][0].getScreenCTM(); + d3_mouse_bug44083 = !(ctm.f || ctm.e); + svg.remove(); + } + if (d3_mouse_bug44083) point.x = e.pageX, point.y = e.pageY; else point.x = e.clientX, + point.y = e.clientY; + point = point.matrixTransform(container.getScreenCTM().inverse()); + return [ point.x, point.y ]; + } + var rect = container.getBoundingClientRect(); + return [ e.clientX - rect.left - container.clientLeft, e.clientY - rect.top - container.clientTop ]; + } + d3.touches = function(container, touches) { + if (arguments.length < 2) touches = d3_eventSource().touches; + return touches ? d3_array(touches).map(function(touch) { + var point = d3_mousePoint(container, touch); + point.identifier = touch.identifier; + return point; + }) : []; + }; + d3.behavior.drag = function() { + var event = d3_eventDispatch(drag, "drag", "dragstart", "dragend"), origin = null, mousedown = dragstart(d3_noop, d3.mouse, "mousemove", "mouseup"), touchstart = dragstart(touchid, touchposition, "touchmove", "touchend"); + function drag() { + this.on("mousedown.drag", mousedown).on("touchstart.drag", touchstart); + } + function touchid() { + return d3.event.changedTouches[0].identifier; + } + function touchposition(parent, id) { + return d3.touches(parent).filter(function(p) { + return p.identifier === id; + })[0]; + } + function dragstart(id, position, move, end) { + return function() { + var target = this, parent = target.parentNode, event_ = event.of(target, arguments), eventTarget = d3.event.target, eventId = id(), drag = eventId == null ? "drag" : "drag-" + eventId, origin_ = position(parent, eventId), dragged = 0, offset, w = d3.select(d3_window).on(move + "." + drag, moved).on(end + "." + drag, ended), dragRestore = d3_event_dragSuppress(); + if (origin) { + offset = origin.apply(target, arguments); + offset = [ offset.x - origin_[0], offset.y - origin_[1] ]; + } else { + offset = [ 0, 0 ]; + } + event_({ + type: "dragstart" + }); + function moved() { + var p = position(parent, eventId), dx = p[0] - origin_[0], dy = p[1] - origin_[1]; + dragged |= dx | dy; + origin_ = p; + event_({ + type: "drag", + x: p[0] + offset[0], + y: p[1] + offset[1], + dx: dx, + dy: dy + }); + } + function ended() { + w.on(move + "." + drag, null).on(end + "." + drag, null); + dragRestore(dragged && d3.event.target === eventTarget); + event_({ + type: "dragend" + }); + } + }; + } + drag.origin = function(x) { + if (!arguments.length) return origin; + origin = x; + return drag; + }; + return d3.rebind(drag, event, "on"); + }; + var π = Math.PI, τ = 2 * π, halfπ = π / 2, ε = 1e-6, ε2 = ε * ε, d3_radians = π / 180, d3_degrees = 180 / π; + function d3_sgn(x) { + return x > 0 ? 1 : x < 0 ? -1 : 0; + } + function d3_cross2d(a, b, c) { + return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]); + } + function d3_acos(x) { + return x > 1 ? 0 : x < -1 ? π : Math.acos(x); + } + function d3_asin(x) { + return x > 1 ? halfπ : x < -1 ? -halfπ : Math.asin(x); + } + function d3_sinh(x) { + return ((x = Math.exp(x)) - 1 / x) / 2; + } + function d3_cosh(x) { + return ((x = Math.exp(x)) + 1 / x) / 2; + } + function d3_tanh(x) { + return ((x = Math.exp(2 * x)) - 1) / (x + 1); + } + function d3_haversin(x) { + return (x = Math.sin(x / 2)) * x; + } + var ρ = Math.SQRT2, ρ2 = 2, ρ4 = 4; + d3.interpolateZoom = function(p0, p1) { + var ux0 = p0[0], uy0 = p0[1], w0 = p0[2], ux1 = p1[0], uy1 = p1[1], w1 = p1[2]; + var dx = ux1 - ux0, dy = uy1 - uy0, d2 = dx * dx + dy * dy, d1 = Math.sqrt(d2), b0 = (w1 * w1 - w0 * w0 + ρ4 * d2) / (2 * w0 * ρ2 * d1), b1 = (w1 * w1 - w0 * w0 - ρ4 * d2) / (2 * w1 * ρ2 * d1), r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0), r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1), dr = r1 - r0, S = (dr || Math.log(w1 / w0)) / ρ; + function interpolate(t) { + var s = t * S; + if (dr) { + var coshr0 = d3_cosh(r0), u = w0 / (ρ2 * d1) * (coshr0 * d3_tanh(ρ * s + r0) - d3_sinh(r0)); + return [ ux0 + u * dx, uy0 + u * dy, w0 * coshr0 / d3_cosh(ρ * s + r0) ]; + } + return [ ux0 + t * dx, uy0 + t * dy, w0 * Math.exp(ρ * s) ]; + } + interpolate.duration = S * 1e3; + return interpolate; + }; + d3.behavior.zoom = function() { + var view = { + x: 0, + y: 0, + k: 1 + }, translate0, center, size = [ 960, 500 ], scaleExtent = d3_behavior_zoomInfinity, mousedown = "mousedown.zoom", mousemove = "mousemove.zoom", mouseup = "mouseup.zoom", mousewheelTimer, touchstart = "touchstart.zoom", touchtime, event = d3_eventDispatch(zoom, "zoomstart", "zoom", "zoomend"), x0, x1, y0, y1; + function zoom(g) { + g.on(mousedown, mousedowned).on(d3_behavior_zoomWheel + ".zoom", mousewheeled).on(mousemove, mousewheelreset).on("dblclick.zoom", dblclicked).on(touchstart, touchstarted); + } + zoom.event = function(g) { + g.each(function() { + var event_ = event.of(this, arguments), view1 = view; + if (d3_transitionInheritId) { + d3.select(this).transition().each("start.zoom", function() { + view = this.__chart__ || { + x: 0, + y: 0, + k: 1 + }; + zoomstarted(event_); + }).tween("zoom:zoom", function() { + var dx = size[0], dy = size[1], cx = dx / 2, cy = dy / 2, i = d3.interpolateZoom([ (cx - view.x) / view.k, (cy - view.y) / view.k, dx / view.k ], [ (cx - view1.x) / view1.k, (cy - view1.y) / view1.k, dx / view1.k ]); + return function(t) { + var l = i(t), k = dx / l[2]; + this.__chart__ = view = { + x: cx - l[0] * k, + y: cy - l[1] * k, + k: k + }; + zoomed(event_); + }; + }).each("end.zoom", function() { + zoomended(event_); + }); + } else { + this.__chart__ = view; + zoomstarted(event_); + zoomed(event_); + zoomended(event_); + } + }); + }; + zoom.translate = function(_) { + if (!arguments.length) return [ view.x, view.y ]; + view = { + x: +_[0], + y: +_[1], + k: view.k + }; + rescale(); + return zoom; + }; + zoom.scale = function(_) { + if (!arguments.length) return view.k; + view = { + x: view.x, + y: view.y, + k: +_ + }; + rescale(); + return zoom; + }; + zoom.scaleExtent = function(_) { + if (!arguments.length) return scaleExtent; + scaleExtent = _ == null ? d3_behavior_zoomInfinity : [ +_[0], +_[1] ]; + return zoom; + }; + zoom.center = function(_) { + if (!arguments.length) return center; + center = _ && [ +_[0], +_[1] ]; + return zoom; + }; + zoom.size = function(_) { + if (!arguments.length) return size; + size = _ && [ +_[0], +_[1] ]; + return zoom; + }; + zoom.x = function(z) { + if (!arguments.length) return x1; + x1 = z; + x0 = z.copy(); + view = { + x: 0, + y: 0, + k: 1 + }; + return zoom; + }; + zoom.y = function(z) { + if (!arguments.length) return y1; + y1 = z; + y0 = z.copy(); + view = { + x: 0, + y: 0, + k: 1 + }; + return zoom; + }; + function location(p) { + return [ (p[0] - view.x) / view.k, (p[1] - view.y) / view.k ]; + } + function point(l) { + return [ l[0] * view.k + view.x, l[1] * view.k + view.y ]; + } + function scaleTo(s) { + view.k = Math.max(scaleExtent[0], Math.min(scaleExtent[1], s)); + } + function translateTo(p, l) { + l = point(l); + view.x += p[0] - l[0]; + view.y += p[1] - l[1]; + } + function rescale() { + if (x1) x1.domain(x0.range().map(function(x) { + return (x - view.x) / view.k; + }).map(x0.invert)); + if (y1) y1.domain(y0.range().map(function(y) { + return (y - view.y) / view.k; + }).map(y0.invert)); + } + function zoomstarted(event) { + event({ + type: "zoomstart" + }); + } + function zoomed(event) { + rescale(); + event({ + type: "zoom", + scale: view.k, + translate: [ view.x, view.y ] + }); + } + function zoomended(event) { + event({ + type: "zoomend" + }); + } + function mousedowned() { + var target = this, event_ = event.of(target, arguments), eventTarget = d3.event.target, dragged = 0, w = d3.select(d3_window).on(mousemove, moved).on(mouseup, ended), l = location(d3.mouse(target)), dragRestore = d3_event_dragSuppress(); + d3_selection_interrupt.call(target); + zoomstarted(event_); + function moved() { + dragged = 1; + translateTo(d3.mouse(target), l); + zoomed(event_); + } + function ended() { + w.on(mousemove, d3_window === target ? mousewheelreset : null).on(mouseup, null); + dragRestore(dragged && d3.event.target === eventTarget); + zoomended(event_); + } + } + function touchstarted() { + var target = this, event_ = event.of(target, arguments), locations0 = {}, distance0 = 0, scale0, eventId = d3.event.changedTouches[0].identifier, touchmove = "touchmove.zoom-" + eventId, touchend = "touchend.zoom-" + eventId, w = d3.select(d3_window).on(touchmove, moved).on(touchend, ended), t = d3.select(target).on(mousedown, null).on(touchstart, started), dragRestore = d3_event_dragSuppress(); + d3_selection_interrupt.call(target); + started(); + zoomstarted(event_); + function relocate() { + var touches = d3.touches(target); + scale0 = view.k; + touches.forEach(function(t) { + if (t.identifier in locations0) locations0[t.identifier] = location(t); + }); + return touches; + } + function started() { + var changed = d3.event.changedTouches; + for (var i = 0, n = changed.length; i < n; ++i) { + locations0[changed[i].identifier] = null; + } + var touches = relocate(), now = Date.now(); + if (touches.length === 1) { + if (now - touchtime < 500) { + var p = touches[0], l = locations0[p.identifier]; + scaleTo(view.k * 2); + translateTo(p, l); + d3_eventPreventDefault(); + zoomed(event_); + } + touchtime = now; + } else if (touches.length > 1) { + var p = touches[0], q = touches[1], dx = p[0] - q[0], dy = p[1] - q[1]; + distance0 = dx * dx + dy * dy; + } + } + function moved() { + var touches = d3.touches(target), p0, l0, p1, l1; + for (var i = 0, n = touches.length; i < n; ++i, l1 = null) { + p1 = touches[i]; + if (l1 = locations0[p1.identifier]) { + if (l0) break; + p0 = p1, l0 = l1; + } + } + if (l1) { + var distance1 = (distance1 = p1[0] - p0[0]) * distance1 + (distance1 = p1[1] - p0[1]) * distance1, scale1 = distance0 && Math.sqrt(distance1 / distance0); + p0 = [ (p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2 ]; + l0 = [ (l0[0] + l1[0]) / 2, (l0[1] + l1[1]) / 2 ]; + scaleTo(scale1 * scale0); + } + touchtime = null; + translateTo(p0, l0); + zoomed(event_); + } + function ended() { + if (d3.event.touches.length) { + var changed = d3.event.changedTouches; + for (var i = 0, n = changed.length; i < n; ++i) { + delete locations0[changed[i].identifier]; + } + for (var identifier in locations0) { + return void relocate(); + } + } + w.on(touchmove, null).on(touchend, null); + t.on(mousedown, mousedowned).on(touchstart, touchstarted); + dragRestore(); + zoomended(event_); + } + } + function mousewheeled() { + var event_ = event.of(this, arguments); + if (mousewheelTimer) clearTimeout(mousewheelTimer); else d3_selection_interrupt.call(this), + zoomstarted(event_); + mousewheelTimer = setTimeout(function() { + mousewheelTimer = null; + zoomended(event_); + }, 50); + d3_eventPreventDefault(); + var point = center || d3.mouse(this); + if (!translate0) translate0 = location(point); + scaleTo(Math.pow(2, d3_behavior_zoomDelta() * .002) * view.k); + translateTo(point, translate0); + zoomed(event_); + } + function mousewheelreset() { + translate0 = null; + } + function dblclicked() { + var event_ = event.of(this, arguments), p = d3.mouse(this), l = location(p), k = Math.log(view.k) / Math.LN2; + zoomstarted(event_); + scaleTo(Math.pow(2, d3.event.shiftKey ? Math.ceil(k) - 1 : Math.floor(k) + 1)); + translateTo(p, l); + zoomed(event_); + zoomended(event_); + } + return d3.rebind(zoom, event, "on"); + }; + var d3_behavior_zoomInfinity = [ 0, Infinity ]; + var d3_behavior_zoomDelta, d3_behavior_zoomWheel = "onwheel" in d3_document ? (d3_behavior_zoomDelta = function() { + return -d3.event.deltaY * (d3.event.deltaMode ? 120 : 1); + }, "wheel") : "onmousewheel" in d3_document ? (d3_behavior_zoomDelta = function() { + return d3.event.wheelDelta; + }, "mousewheel") : (d3_behavior_zoomDelta = function() { + return -d3.event.detail; + }, "MozMousePixelScroll"); + function d3_Color() {} + d3_Color.prototype.toString = function() { + return this.rgb() + ""; + }; + d3.hsl = function(h, s, l) { + return arguments.length === 1 ? h instanceof d3_Hsl ? d3_hsl(h.h, h.s, h.l) : d3_rgb_parse("" + h, d3_rgb_hsl, d3_hsl) : d3_hsl(+h, +s, +l); + }; + function d3_hsl(h, s, l) { + return new d3_Hsl(h, s, l); + } + function d3_Hsl(h, s, l) { + this.h = h; + this.s = s; + this.l = l; + } + var d3_hslPrototype = d3_Hsl.prototype = new d3_Color(); + d3_hslPrototype.brighter = function(k) { + k = Math.pow(.7, arguments.length ? k : 1); + return d3_hsl(this.h, this.s, this.l / k); + }; + d3_hslPrototype.darker = function(k) { + k = Math.pow(.7, arguments.length ? k : 1); + return d3_hsl(this.h, this.s, k * this.l); + }; + d3_hslPrototype.rgb = function() { + return d3_hsl_rgb(this.h, this.s, this.l); + }; + function d3_hsl_rgb(h, s, l) { + var m1, m2; + h = isNaN(h) ? 0 : (h %= 360) < 0 ? h + 360 : h; + s = isNaN(s) ? 0 : s < 0 ? 0 : s > 1 ? 1 : s; + l = l < 0 ? 0 : l > 1 ? 1 : l; + m2 = l <= .5 ? l * (1 + s) : l + s - l * s; + m1 = 2 * l - m2; + function v(h) { + if (h > 360) h -= 360; else if (h < 0) h += 360; + if (h < 60) return m1 + (m2 - m1) * h / 60; + if (h < 180) return m2; + if (h < 240) return m1 + (m2 - m1) * (240 - h) / 60; + return m1; + } + function vv(h) { + return Math.round(v(h) * 255); + } + return d3_rgb(vv(h + 120), vv(h), vv(h - 120)); + } + d3.hcl = function(h, c, l) { + return arguments.length === 1 ? h instanceof d3_Hcl ? d3_hcl(h.h, h.c, h.l) : h instanceof d3_Lab ? d3_lab_hcl(h.l, h.a, h.b) : d3_lab_hcl((h = d3_rgb_lab((h = d3.rgb(h)).r, h.g, h.b)).l, h.a, h.b) : d3_hcl(+h, +c, +l); + }; + function d3_hcl(h, c, l) { + return new d3_Hcl(h, c, l); + } + function d3_Hcl(h, c, l) { + this.h = h; + this.c = c; + this.l = l; + } + var d3_hclPrototype = d3_Hcl.prototype = new d3_Color(); + d3_hclPrototype.brighter = function(k) { + return d3_hcl(this.h, this.c, Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1))); + }; + d3_hclPrototype.darker = function(k) { + return d3_hcl(this.h, this.c, Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1))); + }; + d3_hclPrototype.rgb = function() { + return d3_hcl_lab(this.h, this.c, this.l).rgb(); + }; + function d3_hcl_lab(h, c, l) { + if (isNaN(h)) h = 0; + if (isNaN(c)) c = 0; + return d3_lab(l, Math.cos(h *= d3_radians) * c, Math.sin(h) * c); + } + d3.lab = function(l, a, b) { + return arguments.length === 1 ? l instanceof d3_Lab ? d3_lab(l.l, l.a, l.b) : l instanceof d3_Hcl ? d3_hcl_lab(l.l, l.c, l.h) : d3_rgb_lab((l = d3.rgb(l)).r, l.g, l.b) : d3_lab(+l, +a, +b); + }; + function d3_lab(l, a, b) { + return new d3_Lab(l, a, b); + } + function d3_Lab(l, a, b) { + this.l = l; + this.a = a; + this.b = b; + } + var d3_lab_K = 18; + var d3_lab_X = .95047, d3_lab_Y = 1, d3_lab_Z = 1.08883; + var d3_labPrototype = d3_Lab.prototype = new d3_Color(); + d3_labPrototype.brighter = function(k) { + return d3_lab(Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1)), this.a, this.b); + }; + d3_labPrototype.darker = function(k) { + return d3_lab(Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1)), this.a, this.b); + }; + d3_labPrototype.rgb = function() { + return d3_lab_rgb(this.l, this.a, this.b); + }; + function d3_lab_rgb(l, a, b) { + var y = (l + 16) / 116, x = y + a / 500, z = y - b / 200; + x = d3_lab_xyz(x) * d3_lab_X; + y = d3_lab_xyz(y) * d3_lab_Y; + z = d3_lab_xyz(z) * d3_lab_Z; + return d3_rgb(d3_xyz_rgb(3.2404542 * x - 1.5371385 * y - .4985314 * z), d3_xyz_rgb(-.969266 * x + 1.8760108 * y + .041556 * z), d3_xyz_rgb(.0556434 * x - .2040259 * y + 1.0572252 * z)); + } + function d3_lab_hcl(l, a, b) { + return l > 0 ? d3_hcl(Math.atan2(b, a) * d3_degrees, Math.sqrt(a * a + b * b), l) : d3_hcl(NaN, NaN, l); + } + function d3_lab_xyz(x) { + return x > .206893034 ? x * x * x : (x - 4 / 29) / 7.787037; + } + function d3_xyz_lab(x) { + return x > .008856 ? Math.pow(x, 1 / 3) : 7.787037 * x + 4 / 29; + } + function d3_xyz_rgb(r) { + return Math.round(255 * (r <= .00304 ? 12.92 * r : 1.055 * Math.pow(r, 1 / 2.4) - .055)); + } + d3.rgb = function(r, g, b) { + return arguments.length === 1 ? r instanceof d3_Rgb ? d3_rgb(r.r, r.g, r.b) : d3_rgb_parse("" + r, d3_rgb, d3_hsl_rgb) : d3_rgb(~~r, ~~g, ~~b); + }; + function d3_rgbNumber(value) { + return d3_rgb(value >> 16, value >> 8 & 255, value & 255); + } + function d3_rgbString(value) { + return d3_rgbNumber(value) + ""; + } + function d3_rgb(r, g, b) { + return new d3_Rgb(r, g, b); + } + function d3_Rgb(r, g, b) { + this.r = r; + this.g = g; + this.b = b; + } + var d3_rgbPrototype = d3_Rgb.prototype = new d3_Color(); + d3_rgbPrototype.brighter = function(k) { + k = Math.pow(.7, arguments.length ? k : 1); + var r = this.r, g = this.g, b = this.b, i = 30; + if (!r && !g && !b) return d3_rgb(i, i, i); + if (r && r < i) r = i; + if (g && g < i) g = i; + if (b && b < i) b = i; + return d3_rgb(Math.min(255, ~~(r / k)), Math.min(255, ~~(g / k)), Math.min(255, ~~(b / k))); + }; + d3_rgbPrototype.darker = function(k) { + k = Math.pow(.7, arguments.length ? k : 1); + return d3_rgb(~~(k * this.r), ~~(k * this.g), ~~(k * this.b)); + }; + d3_rgbPrototype.hsl = function() { + return d3_rgb_hsl(this.r, this.g, this.b); + }; + d3_rgbPrototype.toString = function() { + return "#" + d3_rgb_hex(this.r) + d3_rgb_hex(this.g) + d3_rgb_hex(this.b); + }; + function d3_rgb_hex(v) { + return v < 16 ? "0" + Math.max(0, v).toString(16) : Math.min(255, v).toString(16); + } + function d3_rgb_parse(format, rgb, hsl) { + var r = 0, g = 0, b = 0, m1, m2, name; + m1 = /([a-z]+)\((.*)\)/i.exec(format); + if (m1) { + m2 = m1[2].split(","); + switch (m1[1]) { + case "hsl": + { + return hsl(parseFloat(m2[0]), parseFloat(m2[1]) / 100, parseFloat(m2[2]) / 100); + } + + case "rgb": + { + return rgb(d3_rgb_parseNumber(m2[0]), d3_rgb_parseNumber(m2[1]), d3_rgb_parseNumber(m2[2])); + } + } + } + if (name = d3_rgb_names.get(format)) return rgb(name.r, name.g, name.b); + if (format != null && format.charAt(0) === "#") { + if (format.length === 4) { + r = format.charAt(1); + r += r; + g = format.charAt(2); + g += g; + b = format.charAt(3); + b += b; + } else if (format.length === 7) { + r = format.substring(1, 3); + g = format.substring(3, 5); + b = format.substring(5, 7); + } + r = parseInt(r, 16); + g = parseInt(g, 16); + b = parseInt(b, 16); + } + return rgb(r, g, b); + } + function d3_rgb_hsl(r, g, b) { + var min = Math.min(r /= 255, g /= 255, b /= 255), max = Math.max(r, g, b), d = max - min, h, s, l = (max + min) / 2; + if (d) { + s = l < .5 ? d / (max + min) : d / (2 - max - min); + if (r == max) h = (g - b) / d + (g < b ? 6 : 0); else if (g == max) h = (b - r) / d + 2; else h = (r - g) / d + 4; + h *= 60; + } else { + h = NaN; + s = l > 0 && l < 1 ? 0 : h; + } + return d3_hsl(h, s, l); + } + function d3_rgb_lab(r, g, b) { + r = d3_rgb_xyz(r); + g = d3_rgb_xyz(g); + b = d3_rgb_xyz(b); + var x = d3_xyz_lab((.4124564 * r + .3575761 * g + .1804375 * b) / d3_lab_X), y = d3_xyz_lab((.2126729 * r + .7151522 * g + .072175 * b) / d3_lab_Y), z = d3_xyz_lab((.0193339 * r + .119192 * g + .9503041 * b) / d3_lab_Z); + return d3_lab(116 * y - 16, 500 * (x - y), 200 * (y - z)); + } + function d3_rgb_xyz(r) { + return (r /= 255) <= .04045 ? r / 12.92 : Math.pow((r + .055) / 1.055, 2.4); + } + function d3_rgb_parseNumber(c) { + var f = parseFloat(c); + return c.charAt(c.length - 1) === "%" ? Math.round(f * 2.55) : f; + } + var d3_rgb_names = d3.map({ + aliceblue: 15792383, + antiquewhite: 16444375, + aqua: 65535, + aquamarine: 8388564, + azure: 15794175, + beige: 16119260, + bisque: 16770244, + black: 0, + blanchedalmond: 16772045, + blue: 255, + blueviolet: 9055202, + brown: 10824234, + burlywood: 14596231, + cadetblue: 6266528, + chartreuse: 8388352, + chocolate: 13789470, + coral: 16744272, + cornflowerblue: 6591981, + cornsilk: 16775388, + crimson: 14423100, + cyan: 65535, + darkblue: 139, + darkcyan: 35723, + darkgoldenrod: 12092939, + darkgray: 11119017, + darkgreen: 25600, + darkgrey: 11119017, + darkkhaki: 12433259, + darkmagenta: 9109643, + darkolivegreen: 5597999, + darkorange: 16747520, + darkorchid: 10040012, + darkred: 9109504, + darksalmon: 15308410, + darkseagreen: 9419919, + darkslateblue: 4734347, + darkslategray: 3100495, + darkslategrey: 3100495, + darkturquoise: 52945, + darkviolet: 9699539, + deeppink: 16716947, + deepskyblue: 49151, + dimgray: 6908265, + dimgrey: 6908265, + dodgerblue: 2003199, + firebrick: 11674146, + floralwhite: 16775920, + forestgreen: 2263842, + fuchsia: 16711935, + gainsboro: 14474460, + ghostwhite: 16316671, + gold: 16766720, + goldenrod: 14329120, + gray: 8421504, + green: 32768, + greenyellow: 11403055, + grey: 8421504, + honeydew: 15794160, + hotpink: 16738740, + indianred: 13458524, + indigo: 4915330, + ivory: 16777200, + khaki: 15787660, + lavender: 15132410, + lavenderblush: 16773365, + lawngreen: 8190976, + lemonchiffon: 16775885, + lightblue: 11393254, + lightcoral: 15761536, + lightcyan: 14745599, + lightgoldenrodyellow: 16448210, + lightgray: 13882323, + lightgreen: 9498256, + lightgrey: 13882323, + lightpink: 16758465, + lightsalmon: 16752762, + lightseagreen: 2142890, + lightskyblue: 8900346, + lightslategray: 7833753, + lightslategrey: 7833753, + lightsteelblue: 11584734, + lightyellow: 16777184, + lime: 65280, + limegreen: 3329330, + linen: 16445670, + magenta: 16711935, + maroon: 8388608, + mediumaquamarine: 6737322, + mediumblue: 205, + mediumorchid: 12211667, + mediumpurple: 9662683, + mediumseagreen: 3978097, + mediumslateblue: 8087790, + mediumspringgreen: 64154, + mediumturquoise: 4772300, + mediumvioletred: 13047173, + midnightblue: 1644912, + mintcream: 16121850, + mistyrose: 16770273, + moccasin: 16770229, + navajowhite: 16768685, + navy: 128, + oldlace: 16643558, + olive: 8421376, + olivedrab: 7048739, + orange: 16753920, + orangered: 16729344, + orchid: 14315734, + palegoldenrod: 15657130, + palegreen: 10025880, + paleturquoise: 11529966, + palevioletred: 14381203, + papayawhip: 16773077, + peachpuff: 16767673, + peru: 13468991, + pink: 16761035, + plum: 14524637, + powderblue: 11591910, + purple: 8388736, + red: 16711680, + rosybrown: 12357519, + royalblue: 4286945, + saddlebrown: 9127187, + salmon: 16416882, + sandybrown: 16032864, + seagreen: 3050327, + seashell: 16774638, + sienna: 10506797, + silver: 12632256, + skyblue: 8900331, + slateblue: 6970061, + slategray: 7372944, + slategrey: 7372944, + snow: 16775930, + springgreen: 65407, + steelblue: 4620980, + tan: 13808780, + teal: 32896, + thistle: 14204888, + tomato: 16737095, + turquoise: 4251856, + violet: 15631086, + wheat: 16113331, + white: 16777215, + whitesmoke: 16119285, + yellow: 16776960, + yellowgreen: 10145074 + }); + d3_rgb_names.forEach(function(key, value) { + d3_rgb_names.set(key, d3_rgbNumber(value)); + }); + function d3_functor(v) { + return typeof v === "function" ? v : function() { + return v; + }; + } + d3.functor = d3_functor; + function d3_identity(d) { + return d; + } + d3.xhr = d3_xhrType(d3_identity); + function d3_xhrType(response) { + return function(url, mimeType, callback) { + if (arguments.length === 2 && typeof mimeType === "function") callback = mimeType, + mimeType = null; + return d3_xhr(url, mimeType, response, callback); + }; + } + function d3_xhr(url, mimeType, response, callback) { + var xhr = {}, dispatch = d3.dispatch("beforesend", "progress", "load", "error"), headers = {}, request = new XMLHttpRequest(), responseType = null; + if (d3_window.XDomainRequest && !("withCredentials" in request) && /^(http(s)?:)?\/\//.test(url)) request = new XDomainRequest(); + "onload" in request ? request.onload = request.onerror = respond : request.onreadystatechange = function() { + request.readyState > 3 && respond(); + }; + function respond() { + var status = request.status, result; + if (!status && request.responseText || status >= 200 && status < 300 || status === 304) { + try { + result = response.call(xhr, request); + } catch (e) { + dispatch.error.call(xhr, e); + return; + } + dispatch.load.call(xhr, result); + } else { + dispatch.error.call(xhr, request); + } + } + request.onprogress = function(event) { + var o = d3.event; + d3.event = event; + try { + dispatch.progress.call(xhr, request); + } finally { + d3.event = o; + } + }; + xhr.header = function(name, value) { + name = (name + "").toLowerCase(); + if (arguments.length < 2) return headers[name]; + if (value == null) delete headers[name]; else headers[name] = value + ""; + return xhr; + }; + xhr.mimeType = function(value) { + if (!arguments.length) return mimeType; + mimeType = value == null ? null : value + ""; + return xhr; + }; + xhr.responseType = function(value) { + if (!arguments.length) return responseType; + responseType = value; + return xhr; + }; + xhr.response = function(value) { + response = value; + return xhr; + }; + [ "get", "post" ].forEach(function(method) { + xhr[method] = function() { + return xhr.send.apply(xhr, [ method ].concat(d3_array(arguments))); + }; + }); + xhr.send = function(method, data, callback) { + if (arguments.length === 2 && typeof data === "function") callback = data, data = null; + request.open(method, url, true); + if (mimeType != null && !("accept" in headers)) headers["accept"] = mimeType + ",*/*"; + if (request.setRequestHeader) for (var name in headers) request.setRequestHeader(name, headers[name]); + if (mimeType != null && request.overrideMimeType) request.overrideMimeType(mimeType); + if (responseType != null) request.responseType = responseType; + if (callback != null) xhr.on("error", callback).on("load", function(request) { + callback(null, request); + }); + dispatch.beforesend.call(xhr, request); + request.send(data == null ? null : data); + return xhr; + }; + xhr.abort = function() { + request.abort(); + return xhr; + }; + d3.rebind(xhr, dispatch, "on"); + return callback == null ? xhr : xhr.get(d3_xhr_fixCallback(callback)); + } + function d3_xhr_fixCallback(callback) { + return callback.length === 1 ? function(error, request) { + callback(error == null ? request : null); + } : callback; + } + d3.dsv = function(delimiter, mimeType) { + var reFormat = new RegExp('["' + delimiter + "\n]"), delimiterCode = delimiter.charCodeAt(0); + function dsv(url, row, callback) { + if (arguments.length < 3) callback = row, row = null; + var xhr = d3_xhr(url, mimeType, row == null ? response : typedResponse(row), callback); + xhr.row = function(_) { + return arguments.length ? xhr.response((row = _) == null ? response : typedResponse(_)) : row; + }; + return xhr; + } + function response(request) { + return dsv.parse(request.responseText); + } + function typedResponse(f) { + return function(request) { + return dsv.parse(request.responseText, f); + }; + } + dsv.parse = function(text, f) { + var o; + return dsv.parseRows(text, function(row, i) { + if (o) return o(row, i - 1); + var a = new Function("d", "return {" + row.map(function(name, i) { + return JSON.stringify(name) + ": d[" + i + "]"; + }).join(",") + "}"); + o = f ? function(row, i) { + return f(a(row), i); + } : a; + }); + }; + dsv.parseRows = function(text, f) { + var EOL = {}, EOF = {}, rows = [], N = text.length, I = 0, n = 0, t, eol; + function token() { + if (I >= N) return EOF; + if (eol) return eol = false, EOL; + var j = I; + if (text.charCodeAt(j) === 34) { + var i = j; + while (i++ < N) { + if (text.charCodeAt(i) === 34) { + if (text.charCodeAt(i + 1) !== 34) break; + ++i; + } + } + I = i + 2; + var c = text.charCodeAt(i + 1); + if (c === 13) { + eol = true; + if (text.charCodeAt(i + 2) === 10) ++I; + } else if (c === 10) { + eol = true; + } + return text.substring(j + 1, i).replace(/""/g, '"'); + } + while (I < N) { + var c = text.charCodeAt(I++), k = 1; + if (c === 10) eol = true; else if (c === 13) { + eol = true; + if (text.charCodeAt(I) === 10) ++I, ++k; + } else if (c !== delimiterCode) continue; + return text.substring(j, I - k); + } + return text.substring(j); + } + while ((t = token()) !== EOF) { + var a = []; + while (t !== EOL && t !== EOF) { + a.push(t); + t = token(); + } + if (f && !(a = f(a, n++))) continue; + rows.push(a); + } + return rows; + }; + dsv.format = function(rows) { + if (Array.isArray(rows[0])) return dsv.formatRows(rows); + var fieldSet = new d3_Set(), fields = []; + rows.forEach(function(row) { + for (var field in row) { + if (!fieldSet.has(field)) { + fields.push(fieldSet.add(field)); + } + } + }); + return [ fields.map(formatValue).join(delimiter) ].concat(rows.map(function(row) { + return fields.map(function(field) { + return formatValue(row[field]); + }).join(delimiter); + })).join("\n"); + }; + dsv.formatRows = function(rows) { + return rows.map(formatRow).join("\n"); + }; + function formatRow(row) { + return row.map(formatValue).join(delimiter); + } + function formatValue(text) { + return reFormat.test(text) ? '"' + text.replace(/\"/g, '""') + '"' : text; + } + return dsv; + }; + d3.csv = d3.dsv(",", "text/csv"); + d3.tsv = d3.dsv(" ", "text/tab-separated-values"); + var d3_timer_queueHead, d3_timer_queueTail, d3_timer_interval, d3_timer_timeout, d3_timer_active, d3_timer_frame = d3_window[d3_vendorSymbol(d3_window, "requestAnimationFrame")] || function(callback) { + setTimeout(callback, 17); + }; + d3.timer = function(callback, delay, then) { + var n = arguments.length; + if (n < 2) delay = 0; + if (n < 3) then = Date.now(); + var time = then + delay, timer = { + c: callback, + t: time, + f: false, + n: null + }; + if (d3_timer_queueTail) d3_timer_queueTail.n = timer; else d3_timer_queueHead = timer; + d3_timer_queueTail = timer; + if (!d3_timer_interval) { + d3_timer_timeout = clearTimeout(d3_timer_timeout); + d3_timer_interval = 1; + d3_timer_frame(d3_timer_step); + } + }; + function d3_timer_step() { + var now = d3_timer_mark(), delay = d3_timer_sweep() - now; + if (delay > 24) { + if (isFinite(delay)) { + clearTimeout(d3_timer_timeout); + d3_timer_timeout = setTimeout(d3_timer_step, delay); + } + d3_timer_interval = 0; + } else { + d3_timer_interval = 1; + d3_timer_frame(d3_timer_step); + } + } + d3.timer.flush = function() { + d3_timer_mark(); + d3_timer_sweep(); + }; + function d3_timer_mark() { + var now = Date.now(); + d3_timer_active = d3_timer_queueHead; + while (d3_timer_active) { + if (now >= d3_timer_active.t) d3_timer_active.f = d3_timer_active.c(now - d3_timer_active.t); + d3_timer_active = d3_timer_active.n; + } + return now; + } + function d3_timer_sweep() { + var t0, t1 = d3_timer_queueHead, time = Infinity; + while (t1) { + if (t1.f) { + t1 = t0 ? t0.n = t1.n : d3_timer_queueHead = t1.n; + } else { + if (t1.t < time) time = t1.t; + t1 = (t0 = t1).n; + } + } + d3_timer_queueTail = t0; + return time; + } + function d3_format_precision(x, p) { + return p - (x ? Math.ceil(Math.log(x) / Math.LN10) : 1); + } + d3.round = function(x, n) { + return n ? Math.round(x * (n = Math.pow(10, n))) / n : Math.round(x); + }; + var d3_formatPrefixes = [ "y", "z", "a", "f", "p", "n", "µ", "m", "", "k", "M", "G", "T", "P", "E", "Z", "Y" ].map(d3_formatPrefix); + d3.formatPrefix = function(value, precision) { + var i = 0; + if (value) { + if (value < 0) value *= -1; + if (precision) value = d3.round(value, d3_format_precision(value, precision)); + i = 1 + Math.floor(1e-12 + Math.log(value) / Math.LN10); + i = Math.max(-24, Math.min(24, Math.floor((i <= 0 ? i + 1 : i - 1) / 3) * 3)); + } + return d3_formatPrefixes[8 + i / 3]; + }; + function d3_formatPrefix(d, i) { + var k = Math.pow(10, abs(8 - i) * 3); + return { + scale: i > 8 ? function(d) { + return d / k; + } : function(d) { + return d * k; + }, + symbol: d + }; + } + function d3_locale_numberFormat(locale) { + var locale_decimal = locale.decimal, locale_thousands = locale.thousands, locale_grouping = locale.grouping, locale_currency = locale.currency, formatGroup = locale_grouping ? function(value) { + var i = value.length, t = [], j = 0, g = locale_grouping[0]; + while (i > 0 && g > 0) { + t.push(value.substring(i -= g, i + g)); + g = locale_grouping[j = (j + 1) % locale_grouping.length]; + } + return t.reverse().join(locale_thousands); + } : d3_identity; + return function(specifier) { + var match = d3_format_re.exec(specifier), fill = match[1] || " ", align = match[2] || ">", sign = match[3] || "", symbol = match[4] || "", zfill = match[5], width = +match[6], comma = match[7], precision = match[8], type = match[9], scale = 1, prefix = "", suffix = "", integer = false; + if (precision) precision = +precision.substring(1); + if (zfill || fill === "0" && align === "=") { + zfill = fill = "0"; + align = "="; + if (comma) width -= Math.floor((width - 1) / 4); + } + switch (type) { + case "n": + comma = true; + type = "g"; + break; + + case "%": + scale = 100; + suffix = "%"; + type = "f"; + break; + + case "p": + scale = 100; + suffix = "%"; + type = "r"; + break; + + case "b": + case "o": + case "x": + case "X": + if (symbol === "#") prefix = "0" + type.toLowerCase(); + + case "c": + case "d": + integer = true; + precision = 0; + break; + + case "s": + scale = -1; + type = "r"; + break; + } + if (symbol === "$") prefix = locale_currency[0], suffix = locale_currency[1]; + if (type == "r" && !precision) type = "g"; + if (precision != null) { + if (type == "g") precision = Math.max(1, Math.min(21, precision)); else if (type == "e" || type == "f") precision = Math.max(0, Math.min(20, precision)); + } + type = d3_format_types.get(type) || d3_format_typeDefault; + var zcomma = zfill && comma; + return function(value) { + var fullSuffix = suffix; + if (integer && value % 1) return ""; + var negative = value < 0 || value === 0 && 1 / value < 0 ? (value = -value, "-") : sign; + if (scale < 0) { + var unit = d3.formatPrefix(value, precision); + value = unit.scale(value); + fullSuffix = unit.symbol + suffix; + } else { + value *= scale; + } + value = type(value, precision); + var i = value.lastIndexOf("."), before = i < 0 ? value : value.substring(0, i), after = i < 0 ? "" : locale_decimal + value.substring(i + 1); + if (!zfill && comma) before = formatGroup(before); + var length = prefix.length + before.length + after.length + (zcomma ? 0 : negative.length), padding = length < width ? new Array(length = width - length + 1).join(fill) : ""; + if (zcomma) before = formatGroup(padding + before); + negative += prefix; + value = before + after; + return (align === "<" ? negative + value + padding : align === ">" ? padding + negative + value : align === "^" ? padding.substring(0, length >>= 1) + negative + value + padding.substring(length) : negative + (zcomma ? value : padding + value)) + fullSuffix; + }; + }; + } + var d3_format_re = /(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i; + var d3_format_types = d3.map({ + b: function(x) { + return x.toString(2); + }, + c: function(x) { + return String.fromCharCode(x); + }, + o: function(x) { + return x.toString(8); + }, + x: function(x) { + return x.toString(16); + }, + X: function(x) { + return x.toString(16).toUpperCase(); + }, + g: function(x, p) { + return x.toPrecision(p); + }, + e: function(x, p) { + return x.toExponential(p); + }, + f: function(x, p) { + return x.toFixed(p); + }, + r: function(x, p) { + return (x = d3.round(x, d3_format_precision(x, p))).toFixed(Math.max(0, Math.min(20, d3_format_precision(x * (1 + 1e-15), p)))); + } + }); + function d3_format_typeDefault(x) { + return x + ""; + } + var d3_time = d3.time = {}, d3_date = Date; + function d3_date_utc() { + this._ = new Date(arguments.length > 1 ? Date.UTC.apply(this, arguments) : arguments[0]); + } + d3_date_utc.prototype = { + getDate: function() { + return this._.getUTCDate(); + }, + getDay: function() { + return this._.getUTCDay(); + }, + getFullYear: function() { + return this._.getUTCFullYear(); + }, + getHours: function() { + return this._.getUTCHours(); + }, + getMilliseconds: function() { + return this._.getUTCMilliseconds(); + }, + getMinutes: function() { + return this._.getUTCMinutes(); + }, + getMonth: function() { + return this._.getUTCMonth(); + }, + getSeconds: function() { + return this._.getUTCSeconds(); + }, + getTime: function() { + return this._.getTime(); + }, + getTimezoneOffset: function() { + return 0; + }, + valueOf: function() { + return this._.valueOf(); + }, + setDate: function() { + d3_time_prototype.setUTCDate.apply(this._, arguments); + }, + setDay: function() { + d3_time_prototype.setUTCDay.apply(this._, arguments); + }, + setFullYear: function() { + d3_time_prototype.setUTCFullYear.apply(this._, arguments); + }, + setHours: function() { + d3_time_prototype.setUTCHours.apply(this._, arguments); + }, + setMilliseconds: function() { + d3_time_prototype.setUTCMilliseconds.apply(this._, arguments); + }, + setMinutes: function() { + d3_time_prototype.setUTCMinutes.apply(this._, arguments); + }, + setMonth: function() { + d3_time_prototype.setUTCMonth.apply(this._, arguments); + }, + setSeconds: function() { + d3_time_prototype.setUTCSeconds.apply(this._, arguments); + }, + setTime: function() { + d3_time_prototype.setTime.apply(this._, arguments); + } + }; + var d3_time_prototype = Date.prototype; + function d3_time_interval(local, step, number) { + function round(date) { + var d0 = local(date), d1 = offset(d0, 1); + return date - d0 < d1 - date ? d0 : d1; + } + function ceil(date) { + step(date = local(new d3_date(date - 1)), 1); + return date; + } + function offset(date, k) { + step(date = new d3_date(+date), k); + return date; + } + function range(t0, t1, dt) { + var time = ceil(t0), times = []; + if (dt > 1) { + while (time < t1) { + if (!(number(time) % dt)) times.push(new Date(+time)); + step(time, 1); + } + } else { + while (time < t1) times.push(new Date(+time)), step(time, 1); + } + return times; + } + function range_utc(t0, t1, dt) { + try { + d3_date = d3_date_utc; + var utc = new d3_date_utc(); + utc._ = t0; + return range(utc, t1, dt); + } finally { + d3_date = Date; + } + } + local.floor = local; + local.round = round; + local.ceil = ceil; + local.offset = offset; + local.range = range; + var utc = local.utc = d3_time_interval_utc(local); + utc.floor = utc; + utc.round = d3_time_interval_utc(round); + utc.ceil = d3_time_interval_utc(ceil); + utc.offset = d3_time_interval_utc(offset); + utc.range = range_utc; + return local; + } + function d3_time_interval_utc(method) { + return function(date, k) { + try { + d3_date = d3_date_utc; + var utc = new d3_date_utc(); + utc._ = date; + return method(utc, k)._; + } finally { + d3_date = Date; + } + }; + } + d3_time.year = d3_time_interval(function(date) { + date = d3_time.day(date); + date.setMonth(0, 1); + return date; + }, function(date, offset) { + date.setFullYear(date.getFullYear() + offset); + }, function(date) { + return date.getFullYear(); + }); + d3_time.years = d3_time.year.range; + d3_time.years.utc = d3_time.year.utc.range; + d3_time.day = d3_time_interval(function(date) { + var day = new d3_date(2e3, 0); + day.setFullYear(date.getFullYear(), date.getMonth(), date.getDate()); + return day; + }, function(date, offset) { + date.setDate(date.getDate() + offset); + }, function(date) { + return date.getDate() - 1; + }); + d3_time.days = d3_time.day.range; + d3_time.days.utc = d3_time.day.utc.range; + d3_time.dayOfYear = function(date) { + var year = d3_time.year(date); + return Math.floor((date - year - (date.getTimezoneOffset() - year.getTimezoneOffset()) * 6e4) / 864e5); + }; + [ "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday" ].forEach(function(day, i) { + i = 7 - i; + var interval = d3_time[day] = d3_time_interval(function(date) { + (date = d3_time.day(date)).setDate(date.getDate() - (date.getDay() + i) % 7); + return date; + }, function(date, offset) { + date.setDate(date.getDate() + Math.floor(offset) * 7); + }, function(date) { + var day = d3_time.year(date).getDay(); + return Math.floor((d3_time.dayOfYear(date) + (day + i) % 7) / 7) - (day !== i); + }); + d3_time[day + "s"] = interval.range; + d3_time[day + "s"].utc = interval.utc.range; + d3_time[day + "OfYear"] = function(date) { + var day = d3_time.year(date).getDay(); + return Math.floor((d3_time.dayOfYear(date) + (day + i) % 7) / 7); + }; + }); + d3_time.week = d3_time.sunday; + d3_time.weeks = d3_time.sunday.range; + d3_time.weeks.utc = d3_time.sunday.utc.range; + d3_time.weekOfYear = d3_time.sundayOfYear; + function d3_locale_timeFormat(locale) { + var locale_dateTime = locale.dateTime, locale_date = locale.date, locale_time = locale.time, locale_periods = locale.periods, locale_days = locale.days, locale_shortDays = locale.shortDays, locale_months = locale.months, locale_shortMonths = locale.shortMonths; + function d3_time_format(template) { + var n = template.length; + function format(date) { + var string = [], i = -1, j = 0, c, p, f; + while (++i < n) { + if (template.charCodeAt(i) === 37) { + string.push(template.substring(j, i)); + if ((p = d3_time_formatPads[c = template.charAt(++i)]) != null) c = template.charAt(++i); + if (f = d3_time_formats[c]) c = f(date, p == null ? c === "e" ? " " : "0" : p); + string.push(c); + j = i + 1; + } + } + string.push(template.substring(j, i)); + return string.join(""); + } + format.parse = function(string) { + var d = { + y: 1900, + m: 0, + d: 1, + H: 0, + M: 0, + S: 0, + L: 0, + Z: null + }, i = d3_time_parse(d, template, string, 0); + if (i != string.length) return null; + if ("p" in d) d.H = d.H % 12 + d.p * 12; + var localZ = d.Z != null && d3_date !== d3_date_utc, date = new (localZ ? d3_date_utc : d3_date)(); + if ("j" in d) date.setFullYear(d.y, 0, d.j); else if ("w" in d && ("W" in d || "U" in d)) { + date.setFullYear(d.y, 0, 1); + date.setFullYear(d.y, 0, "W" in d ? (d.w + 6) % 7 + d.W * 7 - (date.getDay() + 5) % 7 : d.w + d.U * 7 - (date.getDay() + 6) % 7); + } else date.setFullYear(d.y, d.m, d.d); + date.setHours(d.H + Math.floor(d.Z / 100), d.M + d.Z % 100, d.S, d.L); + return localZ ? date._ : date; + }; + format.toString = function() { + return template; + }; + return format; + } + function d3_time_parse(date, template, string, j) { + var c, p, t, i = 0, n = template.length, m = string.length; + while (i < n) { + if (j >= m) return -1; + c = template.charCodeAt(i++); + if (c === 37) { + t = template.charAt(i++); + p = d3_time_parsers[t in d3_time_formatPads ? template.charAt(i++) : t]; + if (!p || (j = p(date, string, j)) < 0) return -1; + } else if (c != string.charCodeAt(j++)) { + return -1; + } + } + return j; + } + d3_time_format.utc = function(template) { + var local = d3_time_format(template); + function format(date) { + try { + d3_date = d3_date_utc; + var utc = new d3_date(); + utc._ = date; + return local(utc); + } finally { + d3_date = Date; + } + } + format.parse = function(string) { + try { + d3_date = d3_date_utc; + var date = local.parse(string); + return date && date._; + } finally { + d3_date = Date; + } + }; + format.toString = local.toString; + return format; + }; + d3_time_format.multi = d3_time_format.utc.multi = d3_time_formatMulti; + var d3_time_periodLookup = d3.map(), d3_time_dayRe = d3_time_formatRe(locale_days), d3_time_dayLookup = d3_time_formatLookup(locale_days), d3_time_dayAbbrevRe = d3_time_formatRe(locale_shortDays), d3_time_dayAbbrevLookup = d3_time_formatLookup(locale_shortDays), d3_time_monthRe = d3_time_formatRe(locale_months), d3_time_monthLookup = d3_time_formatLookup(locale_months), d3_time_monthAbbrevRe = d3_time_formatRe(locale_shortMonths), d3_time_monthAbbrevLookup = d3_time_formatLookup(locale_shortMonths); + locale_periods.forEach(function(p, i) { + d3_time_periodLookup.set(p.toLowerCase(), i); + }); + var d3_time_formats = { + a: function(d) { + return locale_shortDays[d.getDay()]; + }, + A: function(d) { + return locale_days[d.getDay()]; + }, + b: function(d) { + return locale_shortMonths[d.getMonth()]; + }, + B: function(d) { + return locale_months[d.getMonth()]; + }, + c: d3_time_format(locale_dateTime), + d: function(d, p) { + return d3_time_formatPad(d.getDate(), p, 2); + }, + e: function(d, p) { + return d3_time_formatPad(d.getDate(), p, 2); + }, + H: function(d, p) { + return d3_time_formatPad(d.getHours(), p, 2); + }, + I: function(d, p) { + return d3_time_formatPad(d.getHours() % 12 || 12, p, 2); + }, + j: function(d, p) { + return d3_time_formatPad(1 + d3_time.dayOfYear(d), p, 3); + }, + L: function(d, p) { + return d3_time_formatPad(d.getMilliseconds(), p, 3); + }, + m: function(d, p) { + return d3_time_formatPad(d.getMonth() + 1, p, 2); + }, + M: function(d, p) { + return d3_time_formatPad(d.getMinutes(), p, 2); + }, + p: function(d) { + return locale_periods[+(d.getHours() >= 12)]; + }, + S: function(d, p) { + return d3_time_formatPad(d.getSeconds(), p, 2); + }, + U: function(d, p) { + return d3_time_formatPad(d3_time.sundayOfYear(d), p, 2); + }, + w: function(d) { + return d.getDay(); + }, + W: function(d, p) { + return d3_time_formatPad(d3_time.mondayOfYear(d), p, 2); + }, + x: d3_time_format(locale_date), + X: d3_time_format(locale_time), + y: function(d, p) { + return d3_time_formatPad(d.getFullYear() % 100, p, 2); + }, + Y: function(d, p) { + return d3_time_formatPad(d.getFullYear() % 1e4, p, 4); + }, + Z: d3_time_zone, + "%": function() { + return "%"; + } + }; + var d3_time_parsers = { + a: d3_time_parseWeekdayAbbrev, + A: d3_time_parseWeekday, + b: d3_time_parseMonthAbbrev, + B: d3_time_parseMonth, + c: d3_time_parseLocaleFull, + d: d3_time_parseDay, + e: d3_time_parseDay, + H: d3_time_parseHour24, + I: d3_time_parseHour24, + j: d3_time_parseDayOfYear, + L: d3_time_parseMilliseconds, + m: d3_time_parseMonthNumber, + M: d3_time_parseMinutes, + p: d3_time_parseAmPm, + S: d3_time_parseSeconds, + U: d3_time_parseWeekNumberSunday, + w: d3_time_parseWeekdayNumber, + W: d3_time_parseWeekNumberMonday, + x: d3_time_parseLocaleDate, + X: d3_time_parseLocaleTime, + y: d3_time_parseYear, + Y: d3_time_parseFullYear, + Z: d3_time_parseZone, + "%": d3_time_parseLiteralPercent + }; + function d3_time_parseWeekdayAbbrev(date, string, i) { + d3_time_dayAbbrevRe.lastIndex = 0; + var n = d3_time_dayAbbrevRe.exec(string.substring(i)); + return n ? (date.w = d3_time_dayAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; + } + function d3_time_parseWeekday(date, string, i) { + d3_time_dayRe.lastIndex = 0; + var n = d3_time_dayRe.exec(string.substring(i)); + return n ? (date.w = d3_time_dayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; + } + function d3_time_parseMonthAbbrev(date, string, i) { + d3_time_monthAbbrevRe.lastIndex = 0; + var n = d3_time_monthAbbrevRe.exec(string.substring(i)); + return n ? (date.m = d3_time_monthAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; + } + function d3_time_parseMonth(date, string, i) { + d3_time_monthRe.lastIndex = 0; + var n = d3_time_monthRe.exec(string.substring(i)); + return n ? (date.m = d3_time_monthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; + } + function d3_time_parseLocaleFull(date, string, i) { + return d3_time_parse(date, d3_time_formats.c.toString(), string, i); + } + function d3_time_parseLocaleDate(date, string, i) { + return d3_time_parse(date, d3_time_formats.x.toString(), string, i); + } + function d3_time_parseLocaleTime(date, string, i) { + return d3_time_parse(date, d3_time_formats.X.toString(), string, i); + } + function d3_time_parseAmPm(date, string, i) { + var n = d3_time_periodLookup.get(string.substring(i, i += 2).toLowerCase()); + return n == null ? -1 : (date.p = n, i); + } + return d3_time_format; + } + var d3_time_formatPads = { + "-": "", + _: " ", + "0": "0" + }, d3_time_numberRe = /^\s*\d+/, d3_time_percentRe = /^%/; + function d3_time_formatPad(value, fill, width) { + var sign = value < 0 ? "-" : "", string = (sign ? -value : value) + "", length = string.length; + return sign + (length < width ? new Array(width - length + 1).join(fill) + string : string); + } + function d3_time_formatRe(names) { + return new RegExp("^(?:" + names.map(d3.requote).join("|") + ")", "i"); + } + function d3_time_formatLookup(names) { + var map = new d3_Map(), i = -1, n = names.length; + while (++i < n) map.set(names[i].toLowerCase(), i); + return map; + } + function d3_time_parseWeekdayNumber(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.substring(i, i + 1)); + return n ? (date.w = +n[0], i + n[0].length) : -1; + } + function d3_time_parseWeekNumberSunday(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.substring(i)); + return n ? (date.U = +n[0], i + n[0].length) : -1; + } + function d3_time_parseWeekNumberMonday(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.substring(i)); + return n ? (date.W = +n[0], i + n[0].length) : -1; + } + function d3_time_parseFullYear(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.substring(i, i + 4)); + return n ? (date.y = +n[0], i + n[0].length) : -1; + } + function d3_time_parseYear(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.substring(i, i + 2)); + return n ? (date.y = d3_time_expandYear(+n[0]), i + n[0].length) : -1; + } + function d3_time_parseZone(date, string, i) { + return /^[+-]\d{4}$/.test(string = string.substring(i, i + 5)) ? (date.Z = +string, + i + 5) : -1; + } + function d3_time_expandYear(d) { + return d + (d > 68 ? 1900 : 2e3); + } + function d3_time_parseMonthNumber(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.substring(i, i + 2)); + return n ? (date.m = n[0] - 1, i + n[0].length) : -1; + } + function d3_time_parseDay(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.substring(i, i + 2)); + return n ? (date.d = +n[0], i + n[0].length) : -1; + } + function d3_time_parseDayOfYear(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.substring(i, i + 3)); + return n ? (date.j = +n[0], i + n[0].length) : -1; + } + function d3_time_parseHour24(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.substring(i, i + 2)); + return n ? (date.H = +n[0], i + n[0].length) : -1; + } + function d3_time_parseMinutes(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.substring(i, i + 2)); + return n ? (date.M = +n[0], i + n[0].length) : -1; + } + function d3_time_parseSeconds(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.substring(i, i + 2)); + return n ? (date.S = +n[0], i + n[0].length) : -1; + } + function d3_time_parseMilliseconds(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.substring(i, i + 3)); + return n ? (date.L = +n[0], i + n[0].length) : -1; + } + function d3_time_zone(d) { + var z = d.getTimezoneOffset(), zs = z > 0 ? "-" : "+", zh = ~~(abs(z) / 60), zm = abs(z) % 60; + return zs + d3_time_formatPad(zh, "0", 2) + d3_time_formatPad(zm, "0", 2); + } + function d3_time_parseLiteralPercent(date, string, i) { + d3_time_percentRe.lastIndex = 0; + var n = d3_time_percentRe.exec(string.substring(i, i + 1)); + return n ? i + n[0].length : -1; + } + function d3_time_formatMulti(formats) { + var n = formats.length, i = -1; + while (++i < n) formats[i][0] = this(formats[i][0]); + return function(date) { + var i = 0, f = formats[i]; + while (!f[1](date)) f = formats[++i]; + return f[0](date); + }; + } + d3.locale = function(locale) { + return { + numberFormat: d3_locale_numberFormat(locale), + timeFormat: d3_locale_timeFormat(locale) + }; + }; + var d3_locale_enUS = d3.locale({ + decimal: ".", + thousands: ",", + grouping: [ 3 ], + currency: [ "$", "" ], + dateTime: "%a %b %e %X %Y", + date: "%m/%d/%Y", + time: "%H:%M:%S", + periods: [ "AM", "PM" ], + days: [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], + shortDays: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], + months: [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], + shortMonths: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ] + }); + d3.format = d3_locale_enUS.numberFormat; + d3.geo = {}; + function d3_adder() {} + d3_adder.prototype = { + s: 0, + t: 0, + add: function(y) { + d3_adderSum(y, this.t, d3_adderTemp); + d3_adderSum(d3_adderTemp.s, this.s, this); + if (this.s) this.t += d3_adderTemp.t; else this.s = d3_adderTemp.t; + }, + reset: function() { + this.s = this.t = 0; + }, + valueOf: function() { + return this.s; + } + }; + var d3_adderTemp = new d3_adder(); + function d3_adderSum(a, b, o) { + var x = o.s = a + b, bv = x - a, av = x - bv; + o.t = a - av + (b - bv); + } + d3.geo.stream = function(object, listener) { + if (object && d3_geo_streamObjectType.hasOwnProperty(object.type)) { + d3_geo_streamObjectType[object.type](object, listener); + } else { + d3_geo_streamGeometry(object, listener); + } + }; + function d3_geo_streamGeometry(geometry, listener) { + if (geometry && d3_geo_streamGeometryType.hasOwnProperty(geometry.type)) { + d3_geo_streamGeometryType[geometry.type](geometry, listener); + } + } + var d3_geo_streamObjectType = { + Feature: function(feature, listener) { + d3_geo_streamGeometry(feature.geometry, listener); + }, + FeatureCollection: function(object, listener) { + var features = object.features, i = -1, n = features.length; + while (++i < n) d3_geo_streamGeometry(features[i].geometry, listener); + } + }; + var d3_geo_streamGeometryType = { + Sphere: function(object, listener) { + listener.sphere(); + }, + Point: function(object, listener) { + object = object.coordinates; + listener.point(object[0], object[1], object[2]); + }, + MultiPoint: function(object, listener) { + var coordinates = object.coordinates, i = -1, n = coordinates.length; + while (++i < n) object = coordinates[i], listener.point(object[0], object[1], object[2]); + }, + LineString: function(object, listener) { + d3_geo_streamLine(object.coordinates, listener, 0); + }, + MultiLineString: function(object, listener) { + var coordinates = object.coordinates, i = -1, n = coordinates.length; + while (++i < n) d3_geo_streamLine(coordinates[i], listener, 0); + }, + Polygon: function(object, listener) { + d3_geo_streamPolygon(object.coordinates, listener); + }, + MultiPolygon: function(object, listener) { + var coordinates = object.coordinates, i = -1, n = coordinates.length; + while (++i < n) d3_geo_streamPolygon(coordinates[i], listener); + }, + GeometryCollection: function(object, listener) { + var geometries = object.geometries, i = -1, n = geometries.length; + while (++i < n) d3_geo_streamGeometry(geometries[i], listener); + } + }; + function d3_geo_streamLine(coordinates, listener, closed) { + var i = -1, n = coordinates.length - closed, coordinate; + listener.lineStart(); + while (++i < n) coordinate = coordinates[i], listener.point(coordinate[0], coordinate[1], coordinate[2]); + listener.lineEnd(); + } + function d3_geo_streamPolygon(coordinates, listener) { + var i = -1, n = coordinates.length; + listener.polygonStart(); + while (++i < n) d3_geo_streamLine(coordinates[i], listener, 1); + listener.polygonEnd(); + } + d3.geo.area = function(object) { + d3_geo_areaSum = 0; + d3.geo.stream(object, d3_geo_area); + return d3_geo_areaSum; + }; + var d3_geo_areaSum, d3_geo_areaRingSum = new d3_adder(); + var d3_geo_area = { + sphere: function() { + d3_geo_areaSum += 4 * π; + }, + point: d3_noop, + lineStart: d3_noop, + lineEnd: d3_noop, + polygonStart: function() { + d3_geo_areaRingSum.reset(); + d3_geo_area.lineStart = d3_geo_areaRingStart; + }, + polygonEnd: function() { + var area = 2 * d3_geo_areaRingSum; + d3_geo_areaSum += area < 0 ? 4 * π + area : area; + d3_geo_area.lineStart = d3_geo_area.lineEnd = d3_geo_area.point = d3_noop; + } + }; + function d3_geo_areaRingStart() { + var λ00, φ00, λ0, cosφ0, sinφ0; + d3_geo_area.point = function(λ, φ) { + d3_geo_area.point = nextPoint; + λ0 = (λ00 = λ) * d3_radians, cosφ0 = Math.cos(φ = (φ00 = φ) * d3_radians / 2 + π / 4), + sinφ0 = Math.sin(φ); + }; + function nextPoint(λ, φ) { + λ *= d3_radians; + φ = φ * d3_radians / 2 + π / 4; + var dλ = λ - λ0, cosφ = Math.cos(φ), sinφ = Math.sin(φ), k = sinφ0 * sinφ, u = cosφ0 * cosφ + k * Math.cos(dλ), v = k * Math.sin(dλ); + d3_geo_areaRingSum.add(Math.atan2(v, u)); + λ0 = λ, cosφ0 = cosφ, sinφ0 = sinφ; + } + d3_geo_area.lineEnd = function() { + nextPoint(λ00, φ00); + }; + } + function d3_geo_cartesian(spherical) { + var λ = spherical[0], φ = spherical[1], cosφ = Math.cos(φ); + return [ cosφ * Math.cos(λ), cosφ * Math.sin(λ), Math.sin(φ) ]; + } + function d3_geo_cartesianDot(a, b) { + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; + } + function d3_geo_cartesianCross(a, b) { + return [ a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0] ]; + } + function d3_geo_cartesianAdd(a, b) { + a[0] += b[0]; + a[1] += b[1]; + a[2] += b[2]; + } + function d3_geo_cartesianScale(vector, k) { + return [ vector[0] * k, vector[1] * k, vector[2] * k ]; + } + function d3_geo_cartesianNormalize(d) { + var l = Math.sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]); + d[0] /= l; + d[1] /= l; + d[2] /= l; + } + function d3_geo_spherical(cartesian) { + return [ Math.atan2(cartesian[1], cartesian[0]), d3_asin(cartesian[2]) ]; + } + function d3_geo_sphericalEqual(a, b) { + return abs(a[0] - b[0]) < ε && abs(a[1] - b[1]) < ε; + } + d3.geo.bounds = function() { + var λ0, φ0, λ1, φ1, λ_, λ__, φ__, p0, dλSum, ranges, range; + var bound = { + point: point, + lineStart: lineStart, + lineEnd: lineEnd, + polygonStart: function() { + bound.point = ringPoint; + bound.lineStart = ringStart; + bound.lineEnd = ringEnd; + dλSum = 0; + d3_geo_area.polygonStart(); + }, + polygonEnd: function() { + d3_geo_area.polygonEnd(); + bound.point = point; + bound.lineStart = lineStart; + bound.lineEnd = lineEnd; + if (d3_geo_areaRingSum < 0) λ0 = -(λ1 = 180), φ0 = -(φ1 = 90); else if (dλSum > ε) φ1 = 90; else if (dλSum < -ε) φ0 = -90; + range[0] = λ0, range[1] = λ1; + } + }; + function point(λ, φ) { + ranges.push(range = [ λ0 = λ, λ1 = λ ]); + if (φ < φ0) φ0 = φ; + if (φ > φ1) φ1 = φ; + } + function linePoint(λ, φ) { + var p = d3_geo_cartesian([ λ * d3_radians, φ * d3_radians ]); + if (p0) { + var normal = d3_geo_cartesianCross(p0, p), equatorial = [ normal[1], -normal[0], 0 ], inflection = d3_geo_cartesianCross(equatorial, normal); + d3_geo_cartesianNormalize(inflection); + inflection = d3_geo_spherical(inflection); + var dλ = λ - λ_, s = dλ > 0 ? 1 : -1, λi = inflection[0] * d3_degrees * s, antimeridian = abs(dλ) > 180; + if (antimeridian ^ (s * λ_ < λi && λi < s * λ)) { + var φi = inflection[1] * d3_degrees; + if (φi > φ1) φ1 = φi; + } else if (λi = (λi + 360) % 360 - 180, antimeridian ^ (s * λ_ < λi && λi < s * λ)) { + var φi = -inflection[1] * d3_degrees; + if (φi < φ0) φ0 = φi; + } else { + if (φ < φ0) φ0 = φ; + if (φ > φ1) φ1 = φ; + } + if (antimeridian) { + if (λ < λ_) { + if (angle(λ0, λ) > angle(λ0, λ1)) λ1 = λ; + } else { + if (angle(λ, λ1) > angle(λ0, λ1)) λ0 = λ; + } + } else { + if (λ1 >= λ0) { + if (λ < λ0) λ0 = λ; + if (λ > λ1) λ1 = λ; + } else { + if (λ > λ_) { + if (angle(λ0, λ) > angle(λ0, λ1)) λ1 = λ; + } else { + if (angle(λ, λ1) > angle(λ0, λ1)) λ0 = λ; + } + } + } + } else { + point(λ, φ); + } + p0 = p, λ_ = λ; + } + function lineStart() { + bound.point = linePoint; + } + function lineEnd() { + range[0] = λ0, range[1] = λ1; + bound.point = point; + p0 = null; + } + function ringPoint(λ, φ) { + if (p0) { + var dλ = λ - λ_; + dλSum += abs(dλ) > 180 ? dλ + (dλ > 0 ? 360 : -360) : dλ; + } else λ__ = λ, φ__ = φ; + d3_geo_area.point(λ, φ); + linePoint(λ, φ); + } + function ringStart() { + d3_geo_area.lineStart(); + } + function ringEnd() { + ringPoint(λ__, φ__); + d3_geo_area.lineEnd(); + if (abs(dλSum) > ε) λ0 = -(λ1 = 180); + range[0] = λ0, range[1] = λ1; + p0 = null; + } + function angle(λ0, λ1) { + return (λ1 -= λ0) < 0 ? λ1 + 360 : λ1; + } + function compareRanges(a, b) { + return a[0] - b[0]; + } + function withinRange(x, range) { + return range[0] <= range[1] ? range[0] <= x && x <= range[1] : x < range[0] || range[1] < x; + } + return function(feature) { + φ1 = λ1 = -(λ0 = φ0 = Infinity); + ranges = []; + d3.geo.stream(feature, bound); + var n = ranges.length; + if (n) { + ranges.sort(compareRanges); + for (var i = 1, a = ranges[0], b, merged = [ a ]; i < n; ++i) { + b = ranges[i]; + if (withinRange(b[0], a) || withinRange(b[1], a)) { + if (angle(a[0], b[1]) > angle(a[0], a[1])) a[1] = b[1]; + if (angle(b[0], a[1]) > angle(a[0], a[1])) a[0] = b[0]; + } else { + merged.push(a = b); + } + } + var best = -Infinity, dλ; + for (var n = merged.length - 1, i = 0, a = merged[n], b; i <= n; a = b, ++i) { + b = merged[i]; + if ((dλ = angle(a[1], b[0])) > best) best = dλ, λ0 = b[0], λ1 = a[1]; + } + } + ranges = range = null; + return λ0 === Infinity || φ0 === Infinity ? [ [ NaN, NaN ], [ NaN, NaN ] ] : [ [ λ0, φ0 ], [ λ1, φ1 ] ]; + }; + }(); + d3.geo.centroid = function(object) { + d3_geo_centroidW0 = d3_geo_centroidW1 = d3_geo_centroidX0 = d3_geo_centroidY0 = d3_geo_centroidZ0 = d3_geo_centroidX1 = d3_geo_centroidY1 = d3_geo_centroidZ1 = d3_geo_centroidX2 = d3_geo_centroidY2 = d3_geo_centroidZ2 = 0; + d3.geo.stream(object, d3_geo_centroid); + var x = d3_geo_centroidX2, y = d3_geo_centroidY2, z = d3_geo_centroidZ2, m = x * x + y * y + z * z; + if (m < ε2) { + x = d3_geo_centroidX1, y = d3_geo_centroidY1, z = d3_geo_centroidZ1; + if (d3_geo_centroidW1 < ε) x = d3_geo_centroidX0, y = d3_geo_centroidY0, z = d3_geo_centroidZ0; + m = x * x + y * y + z * z; + if (m < ε2) return [ NaN, NaN ]; + } + return [ Math.atan2(y, x) * d3_degrees, d3_asin(z / Math.sqrt(m)) * d3_degrees ]; + }; + var d3_geo_centroidW0, d3_geo_centroidW1, d3_geo_centroidX0, d3_geo_centroidY0, d3_geo_centroidZ0, d3_geo_centroidX1, d3_geo_centroidY1, d3_geo_centroidZ1, d3_geo_centroidX2, d3_geo_centroidY2, d3_geo_centroidZ2; + var d3_geo_centroid = { + sphere: d3_noop, + point: d3_geo_centroidPoint, + lineStart: d3_geo_centroidLineStart, + lineEnd: d3_geo_centroidLineEnd, + polygonStart: function() { + d3_geo_centroid.lineStart = d3_geo_centroidRingStart; + }, + polygonEnd: function() { + d3_geo_centroid.lineStart = d3_geo_centroidLineStart; + } + }; + function d3_geo_centroidPoint(λ, φ) { + λ *= d3_radians; + var cosφ = Math.cos(φ *= d3_radians); + d3_geo_centroidPointXYZ(cosφ * Math.cos(λ), cosφ * Math.sin(λ), Math.sin(φ)); + } + function d3_geo_centroidPointXYZ(x, y, z) { + ++d3_geo_centroidW0; + d3_geo_centroidX0 += (x - d3_geo_centroidX0) / d3_geo_centroidW0; + d3_geo_centroidY0 += (y - d3_geo_centroidY0) / d3_geo_centroidW0; + d3_geo_centroidZ0 += (z - d3_geo_centroidZ0) / d3_geo_centroidW0; + } + function d3_geo_centroidLineStart() { + var x0, y0, z0; + d3_geo_centroid.point = function(λ, φ) { + λ *= d3_radians; + var cosφ = Math.cos(φ *= d3_radians); + x0 = cosφ * Math.cos(λ); + y0 = cosφ * Math.sin(λ); + z0 = Math.sin(φ); + d3_geo_centroid.point = nextPoint; + d3_geo_centroidPointXYZ(x0, y0, z0); + }; + function nextPoint(λ, φ) { + λ *= d3_radians; + var cosφ = Math.cos(φ *= d3_radians), x = cosφ * Math.cos(λ), y = cosφ * Math.sin(λ), z = Math.sin(φ), w = Math.atan2(Math.sqrt((w = y0 * z - z0 * y) * w + (w = z0 * x - x0 * z) * w + (w = x0 * y - y0 * x) * w), x0 * x + y0 * y + z0 * z); + d3_geo_centroidW1 += w; + d3_geo_centroidX1 += w * (x0 + (x0 = x)); + d3_geo_centroidY1 += w * (y0 + (y0 = y)); + d3_geo_centroidZ1 += w * (z0 + (z0 = z)); + d3_geo_centroidPointXYZ(x0, y0, z0); + } + } + function d3_geo_centroidLineEnd() { + d3_geo_centroid.point = d3_geo_centroidPoint; + } + function d3_geo_centroidRingStart() { + var λ00, φ00, x0, y0, z0; + d3_geo_centroid.point = function(λ, φ) { + λ00 = λ, φ00 = φ; + d3_geo_centroid.point = nextPoint; + λ *= d3_radians; + var cosφ = Math.cos(φ *= d3_radians); + x0 = cosφ * Math.cos(λ); + y0 = cosφ * Math.sin(λ); + z0 = Math.sin(φ); + d3_geo_centroidPointXYZ(x0, y0, z0); + }; + d3_geo_centroid.lineEnd = function() { + nextPoint(λ00, φ00); + d3_geo_centroid.lineEnd = d3_geo_centroidLineEnd; + d3_geo_centroid.point = d3_geo_centroidPoint; + }; + function nextPoint(λ, φ) { + λ *= d3_radians; + var cosφ = Math.cos(φ *= d3_radians), x = cosφ * Math.cos(λ), y = cosφ * Math.sin(λ), z = Math.sin(φ), cx = y0 * z - z0 * y, cy = z0 * x - x0 * z, cz = x0 * y - y0 * x, m = Math.sqrt(cx * cx + cy * cy + cz * cz), u = x0 * x + y0 * y + z0 * z, v = m && -d3_acos(u) / m, w = Math.atan2(m, u); + d3_geo_centroidX2 += v * cx; + d3_geo_centroidY2 += v * cy; + d3_geo_centroidZ2 += v * cz; + d3_geo_centroidW1 += w; + d3_geo_centroidX1 += w * (x0 + (x0 = x)); + d3_geo_centroidY1 += w * (y0 + (y0 = y)); + d3_geo_centroidZ1 += w * (z0 + (z0 = z)); + d3_geo_centroidPointXYZ(x0, y0, z0); + } + } + function d3_true() { + return true; + } + function d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener) { + var subject = [], clip = []; + segments.forEach(function(segment) { + if ((n = segment.length - 1) <= 0) return; + var n, p0 = segment[0], p1 = segment[n]; + if (d3_geo_sphericalEqual(p0, p1)) { + listener.lineStart(); + for (var i = 0; i < n; ++i) listener.point((p0 = segment[i])[0], p0[1]); + listener.lineEnd(); + return; + } + var a = new d3_geo_clipPolygonIntersection(p0, segment, null, true), b = new d3_geo_clipPolygonIntersection(p0, null, a, false); + a.o = b; + subject.push(a); + clip.push(b); + a = new d3_geo_clipPolygonIntersection(p1, segment, null, false); + b = new d3_geo_clipPolygonIntersection(p1, null, a, true); + a.o = b; + subject.push(a); + clip.push(b); + }); + clip.sort(compare); + d3_geo_clipPolygonLinkCircular(subject); + d3_geo_clipPolygonLinkCircular(clip); + if (!subject.length) return; + for (var i = 0, entry = clipStartInside, n = clip.length; i < n; ++i) { + clip[i].e = entry = !entry; + } + var start = subject[0], points, point; + while (1) { + var current = start, isSubject = true; + while (current.v) if ((current = current.n) === start) return; + points = current.z; + listener.lineStart(); + do { + current.v = current.o.v = true; + if (current.e) { + if (isSubject) { + for (var i = 0, n = points.length; i < n; ++i) listener.point((point = points[i])[0], point[1]); + } else { + interpolate(current.x, current.n.x, 1, listener); + } + current = current.n; + } else { + if (isSubject) { + points = current.p.z; + for (var i = points.length - 1; i >= 0; --i) listener.point((point = points[i])[0], point[1]); + } else { + interpolate(current.x, current.p.x, -1, listener); + } + current = current.p; + } + current = current.o; + points = current.z; + isSubject = !isSubject; + } while (!current.v); + listener.lineEnd(); + } + } + function d3_geo_clipPolygonLinkCircular(array) { + if (!(n = array.length)) return; + var n, i = 0, a = array[0], b; + while (++i < n) { + a.n = b = array[i]; + b.p = a; + a = b; + } + a.n = b = array[0]; + b.p = a; + } + function d3_geo_clipPolygonIntersection(point, points, other, entry) { + this.x = point; + this.z = points; + this.o = other; + this.e = entry; + this.v = false; + this.n = this.p = null; + } + function d3_geo_clip(pointVisible, clipLine, interpolate, clipStart) { + return function(rotate, listener) { + var line = clipLine(listener), rotatedClipStart = rotate.invert(clipStart[0], clipStart[1]); + var clip = { + point: point, + lineStart: lineStart, + lineEnd: lineEnd, + polygonStart: function() { + clip.point = pointRing; + clip.lineStart = ringStart; + clip.lineEnd = ringEnd; + segments = []; + polygon = []; + listener.polygonStart(); + }, + polygonEnd: function() { + clip.point = point; + clip.lineStart = lineStart; + clip.lineEnd = lineEnd; + segments = d3.merge(segments); + var clipStartInside = d3_geo_pointInPolygon(rotatedClipStart, polygon); + if (segments.length) { + d3_geo_clipPolygon(segments, d3_geo_clipSort, clipStartInside, interpolate, listener); + } else if (clipStartInside) { + listener.lineStart(); + interpolate(null, null, 1, listener); + listener.lineEnd(); + } + listener.polygonEnd(); + segments = polygon = null; + }, + sphere: function() { + listener.polygonStart(); + listener.lineStart(); + interpolate(null, null, 1, listener); + listener.lineEnd(); + listener.polygonEnd(); + } + }; + function point(λ, φ) { + var point = rotate(λ, φ); + if (pointVisible(λ = point[0], φ = point[1])) listener.point(λ, φ); + } + function pointLine(λ, φ) { + var point = rotate(λ, φ); + line.point(point[0], point[1]); + } + function lineStart() { + clip.point = pointLine; + line.lineStart(); + } + function lineEnd() { + clip.point = point; + line.lineEnd(); + } + var segments; + var buffer = d3_geo_clipBufferListener(), ringListener = clipLine(buffer), polygon, ring; + function pointRing(λ, φ) { + ring.push([ λ, φ ]); + var point = rotate(λ, φ); + ringListener.point(point[0], point[1]); + } + function ringStart() { + ringListener.lineStart(); + ring = []; + } + function ringEnd() { + pointRing(ring[0][0], ring[0][1]); + ringListener.lineEnd(); + var clean = ringListener.clean(), ringSegments = buffer.buffer(), segment, n = ringSegments.length; + ring.pop(); + polygon.push(ring); + ring = null; + if (!n) return; + if (clean & 1) { + segment = ringSegments[0]; + var n = segment.length - 1, i = -1, point; + listener.lineStart(); + while (++i < n) listener.point((point = segment[i])[0], point[1]); + listener.lineEnd(); + return; + } + if (n > 1 && clean & 2) ringSegments.push(ringSegments.pop().concat(ringSegments.shift())); + segments.push(ringSegments.filter(d3_geo_clipSegmentLength1)); + } + return clip; + }; + } + function d3_geo_clipSegmentLength1(segment) { + return segment.length > 1; + } + function d3_geo_clipBufferListener() { + var lines = [], line; + return { + lineStart: function() { + lines.push(line = []); + }, + point: function(λ, φ) { + line.push([ λ, φ ]); + }, + lineEnd: d3_noop, + buffer: function() { + var buffer = lines; + lines = []; + line = null; + return buffer; + }, + rejoin: function() { + if (lines.length > 1) lines.push(lines.pop().concat(lines.shift())); + } + }; + } + function d3_geo_clipSort(a, b) { + return ((a = a.x)[0] < 0 ? a[1] - halfπ - ε : halfπ - a[1]) - ((b = b.x)[0] < 0 ? b[1] - halfπ - ε : halfπ - b[1]); + } + function d3_geo_pointInPolygon(point, polygon) { + var meridian = point[0], parallel = point[1], meridianNormal = [ Math.sin(meridian), -Math.cos(meridian), 0 ], polarAngle = 0, winding = 0; + d3_geo_areaRingSum.reset(); + for (var i = 0, n = polygon.length; i < n; ++i) { + var ring = polygon[i], m = ring.length; + if (!m) continue; + var point0 = ring[0], λ0 = point0[0], φ0 = point0[1] / 2 + π / 4, sinφ0 = Math.sin(φ0), cosφ0 = Math.cos(φ0), j = 1; + while (true) { + if (j === m) j = 0; + point = ring[j]; + var λ = point[0], φ = point[1] / 2 + π / 4, sinφ = Math.sin(φ), cosφ = Math.cos(φ), dλ = λ - λ0, antimeridian = abs(dλ) > π, k = sinφ0 * sinφ; + d3_geo_areaRingSum.add(Math.atan2(k * Math.sin(dλ), cosφ0 * cosφ + k * Math.cos(dλ))); + polarAngle += antimeridian ? dλ + (dλ >= 0 ? τ : -τ) : dλ; + if (antimeridian ^ λ0 >= meridian ^ λ >= meridian) { + var arc = d3_geo_cartesianCross(d3_geo_cartesian(point0), d3_geo_cartesian(point)); + d3_geo_cartesianNormalize(arc); + var intersection = d3_geo_cartesianCross(meridianNormal, arc); + d3_geo_cartesianNormalize(intersection); + var φarc = (antimeridian ^ dλ >= 0 ? -1 : 1) * d3_asin(intersection[2]); + if (parallel > φarc || parallel === φarc && (arc[0] || arc[1])) { + winding += antimeridian ^ dλ >= 0 ? 1 : -1; + } + } + if (!j++) break; + λ0 = λ, sinφ0 = sinφ, cosφ0 = cosφ, point0 = point; + } + } + return (polarAngle < -ε || polarAngle < ε && d3_geo_areaRingSum < 0) ^ winding & 1; + } + var d3_geo_clipAntimeridian = d3_geo_clip(d3_true, d3_geo_clipAntimeridianLine, d3_geo_clipAntimeridianInterpolate, [ -π, -π / 2 ]); + function d3_geo_clipAntimeridianLine(listener) { + var λ0 = NaN, φ0 = NaN, sλ0 = NaN, clean; + return { + lineStart: function() { + listener.lineStart(); + clean = 1; + }, + point: function(λ1, φ1) { + var sλ1 = λ1 > 0 ? π : -π, dλ = abs(λ1 - λ0); + if (abs(dλ - π) < ε) { + listener.point(λ0, φ0 = (φ0 + φ1) / 2 > 0 ? halfπ : -halfπ); + listener.point(sλ0, φ0); + listener.lineEnd(); + listener.lineStart(); + listener.point(sλ1, φ0); + listener.point(λ1, φ0); + clean = 0; + } else if (sλ0 !== sλ1 && dλ >= π) { + if (abs(λ0 - sλ0) < ε) λ0 -= sλ0 * ε; + if (abs(λ1 - sλ1) < ε) λ1 -= sλ1 * ε; + φ0 = d3_geo_clipAntimeridianIntersect(λ0, φ0, λ1, φ1); + listener.point(sλ0, φ0); + listener.lineEnd(); + listener.lineStart(); + listener.point(sλ1, φ0); + clean = 0; + } + listener.point(λ0 = λ1, φ0 = φ1); + sλ0 = sλ1; + }, + lineEnd: function() { + listener.lineEnd(); + λ0 = φ0 = NaN; + }, + clean: function() { + return 2 - clean; + } + }; + } + function d3_geo_clipAntimeridianIntersect(λ0, φ0, λ1, φ1) { + var cosφ0, cosφ1, sinλ0_λ1 = Math.sin(λ0 - λ1); + return abs(sinλ0_λ1) > ε ? Math.atan((Math.sin(φ0) * (cosφ1 = Math.cos(φ1)) * Math.sin(λ1) - Math.sin(φ1) * (cosφ0 = Math.cos(φ0)) * Math.sin(λ0)) / (cosφ0 * cosφ1 * sinλ0_λ1)) : (φ0 + φ1) / 2; + } + function d3_geo_clipAntimeridianInterpolate(from, to, direction, listener) { + var φ; + if (from == null) { + φ = direction * halfπ; + listener.point(-π, φ); + listener.point(0, φ); + listener.point(π, φ); + listener.point(π, 0); + listener.point(π, -φ); + listener.point(0, -φ); + listener.point(-π, -φ); + listener.point(-π, 0); + listener.point(-π, φ); + } else if (abs(from[0] - to[0]) > ε) { + var s = from[0] < to[0] ? π : -π; + φ = direction * s / 2; + listener.point(-s, φ); + listener.point(0, φ); + listener.point(s, φ); + } else { + listener.point(to[0], to[1]); + } + } + function d3_geo_clipCircle(radius) { + var cr = Math.cos(radius), smallRadius = cr > 0, notHemisphere = abs(cr) > ε, interpolate = d3_geo_circleInterpolate(radius, 6 * d3_radians); + return d3_geo_clip(visible, clipLine, interpolate, smallRadius ? [ 0, -radius ] : [ -π, radius - π ]); + function visible(λ, φ) { + return Math.cos(λ) * Math.cos(φ) > cr; + } + function clipLine(listener) { + var point0, c0, v0, v00, clean; + return { + lineStart: function() { + v00 = v0 = false; + clean = 1; + }, + point: function(λ, φ) { + var point1 = [ λ, φ ], point2, v = visible(λ, φ), c = smallRadius ? v ? 0 : code(λ, φ) : v ? code(λ + (λ < 0 ? π : -π), φ) : 0; + if (!point0 && (v00 = v0 = v)) listener.lineStart(); + if (v !== v0) { + point2 = intersect(point0, point1); + if (d3_geo_sphericalEqual(point0, point2) || d3_geo_sphericalEqual(point1, point2)) { + point1[0] += ε; + point1[1] += ε; + v = visible(point1[0], point1[1]); + } + } + if (v !== v0) { + clean = 0; + if (v) { + listener.lineStart(); + point2 = intersect(point1, point0); + listener.point(point2[0], point2[1]); + } else { + point2 = intersect(point0, point1); + listener.point(point2[0], point2[1]); + listener.lineEnd(); + } + point0 = point2; + } else if (notHemisphere && point0 && smallRadius ^ v) { + var t; + if (!(c & c0) && (t = intersect(point1, point0, true))) { + clean = 0; + if (smallRadius) { + listener.lineStart(); + listener.point(t[0][0], t[0][1]); + listener.point(t[1][0], t[1][1]); + listener.lineEnd(); + } else { + listener.point(t[1][0], t[1][1]); + listener.lineEnd(); + listener.lineStart(); + listener.point(t[0][0], t[0][1]); + } + } + } + if (v && (!point0 || !d3_geo_sphericalEqual(point0, point1))) { + listener.point(point1[0], point1[1]); + } + point0 = point1, v0 = v, c0 = c; + }, + lineEnd: function() { + if (v0) listener.lineEnd(); + point0 = null; + }, + clean: function() { + return clean | (v00 && v0) << 1; + } + }; + } + function intersect(a, b, two) { + var pa = d3_geo_cartesian(a), pb = d3_geo_cartesian(b); + var n1 = [ 1, 0, 0 ], n2 = d3_geo_cartesianCross(pa, pb), n2n2 = d3_geo_cartesianDot(n2, n2), n1n2 = n2[0], determinant = n2n2 - n1n2 * n1n2; + if (!determinant) return !two && a; + var c1 = cr * n2n2 / determinant, c2 = -cr * n1n2 / determinant, n1xn2 = d3_geo_cartesianCross(n1, n2), A = d3_geo_cartesianScale(n1, c1), B = d3_geo_cartesianScale(n2, c2); + d3_geo_cartesianAdd(A, B); + var u = n1xn2, w = d3_geo_cartesianDot(A, u), uu = d3_geo_cartesianDot(u, u), t2 = w * w - uu * (d3_geo_cartesianDot(A, A) - 1); + if (t2 < 0) return; + var t = Math.sqrt(t2), q = d3_geo_cartesianScale(u, (-w - t) / uu); + d3_geo_cartesianAdd(q, A); + q = d3_geo_spherical(q); + if (!two) return q; + var λ0 = a[0], λ1 = b[0], φ0 = a[1], φ1 = b[1], z; + if (λ1 < λ0) z = λ0, λ0 = λ1, λ1 = z; + var δλ = λ1 - λ0, polar = abs(δλ - π) < ε, meridian = polar || δλ < ε; + if (!polar && φ1 < φ0) z = φ0, φ0 = φ1, φ1 = z; + if (meridian ? polar ? φ0 + φ1 > 0 ^ q[1] < (abs(q[0] - λ0) < ε ? φ0 : φ1) : φ0 <= q[1] && q[1] <= φ1 : δλ > π ^ (λ0 <= q[0] && q[0] <= λ1)) { + var q1 = d3_geo_cartesianScale(u, (-w + t) / uu); + d3_geo_cartesianAdd(q1, A); + return [ q, d3_geo_spherical(q1) ]; + } + } + function code(λ, φ) { + var r = smallRadius ? radius : π - radius, code = 0; + if (λ < -r) code |= 1; else if (λ > r) code |= 2; + if (φ < -r) code |= 4; else if (φ > r) code |= 8; + return code; + } + } + function d3_geom_clipLine(x0, y0, x1, y1) { + return function(line) { + var a = line.a, b = line.b, ax = a.x, ay = a.y, bx = b.x, by = b.y, t0 = 0, t1 = 1, dx = bx - ax, dy = by - ay, r; + r = x0 - ax; + if (!dx && r > 0) return; + r /= dx; + if (dx < 0) { + if (r < t0) return; + if (r < t1) t1 = r; + } else if (dx > 0) { + if (r > t1) return; + if (r > t0) t0 = r; + } + r = x1 - ax; + if (!dx && r < 0) return; + r /= dx; + if (dx < 0) { + if (r > t1) return; + if (r > t0) t0 = r; + } else if (dx > 0) { + if (r < t0) return; + if (r < t1) t1 = r; + } + r = y0 - ay; + if (!dy && r > 0) return; + r /= dy; + if (dy < 0) { + if (r < t0) return; + if (r < t1) t1 = r; + } else if (dy > 0) { + if (r > t1) return; + if (r > t0) t0 = r; + } + r = y1 - ay; + if (!dy && r < 0) return; + r /= dy; + if (dy < 0) { + if (r > t1) return; + if (r > t0) t0 = r; + } else if (dy > 0) { + if (r < t0) return; + if (r < t1) t1 = r; + } + if (t0 > 0) line.a = { + x: ax + t0 * dx, + y: ay + t0 * dy + }; + if (t1 < 1) line.b = { + x: ax + t1 * dx, + y: ay + t1 * dy + }; + return line; + }; + } + var d3_geo_clipExtentMAX = 1e9; + d3.geo.clipExtent = function() { + var x0, y0, x1, y1, stream, clip, clipExtent = { + stream: function(output) { + if (stream) stream.valid = false; + stream = clip(output); + stream.valid = true; + return stream; + }, + extent: function(_) { + if (!arguments.length) return [ [ x0, y0 ], [ x1, y1 ] ]; + clip = d3_geo_clipExtent(x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1]); + if (stream) stream.valid = false, stream = null; + return clipExtent; + } + }; + return clipExtent.extent([ [ 0, 0 ], [ 960, 500 ] ]); + }; + function d3_geo_clipExtent(x0, y0, x1, y1) { + return function(listener) { + var listener_ = listener, bufferListener = d3_geo_clipBufferListener(), clipLine = d3_geom_clipLine(x0, y0, x1, y1), segments, polygon, ring; + var clip = { + point: point, + lineStart: lineStart, + lineEnd: lineEnd, + polygonStart: function() { + listener = bufferListener; + segments = []; + polygon = []; + clean = true; + }, + polygonEnd: function() { + listener = listener_; + segments = d3.merge(segments); + var clipStartInside = insidePolygon([ x0, y1 ]), inside = clean && clipStartInside, visible = segments.length; + if (inside || visible) { + listener.polygonStart(); + if (inside) { + listener.lineStart(); + interpolate(null, null, 1, listener); + listener.lineEnd(); + } + if (visible) { + d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener); + } + listener.polygonEnd(); + } + segments = polygon = ring = null; + } + }; + function insidePolygon(p) { + var wn = 0, n = polygon.length, y = p[1]; + for (var i = 0; i < n; ++i) { + for (var j = 1, v = polygon[i], m = v.length, a = v[0], b; j < m; ++j) { + b = v[j]; + if (a[1] <= y) { + if (b[1] > y && d3_cross2d(a, b, p) > 0) ++wn; + } else { + if (b[1] <= y && d3_cross2d(a, b, p) < 0) --wn; + } + a = b; + } + } + return wn !== 0; + } + function interpolate(from, to, direction, listener) { + var a = 0, a1 = 0; + if (from == null || (a = corner(from, direction)) !== (a1 = corner(to, direction)) || comparePoints(from, to) < 0 ^ direction > 0) { + do { + listener.point(a === 0 || a === 3 ? x0 : x1, a > 1 ? y1 : y0); + } while ((a = (a + direction + 4) % 4) !== a1); + } else { + listener.point(to[0], to[1]); + } + } + function pointVisible(x, y) { + return x0 <= x && x <= x1 && y0 <= y && y <= y1; + } + function point(x, y) { + if (pointVisible(x, y)) listener.point(x, y); + } + var x__, y__, v__, x_, y_, v_, first, clean; + function lineStart() { + clip.point = linePoint; + if (polygon) polygon.push(ring = []); + first = true; + v_ = false; + x_ = y_ = NaN; + } + function lineEnd() { + if (segments) { + linePoint(x__, y__); + if (v__ && v_) bufferListener.rejoin(); + segments.push(bufferListener.buffer()); + } + clip.point = point; + if (v_) listener.lineEnd(); + } + function linePoint(x, y) { + x = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, x)); + y = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, y)); + var v = pointVisible(x, y); + if (polygon) ring.push([ x, y ]); + if (first) { + x__ = x, y__ = y, v__ = v; + first = false; + if (v) { + listener.lineStart(); + listener.point(x, y); + } + } else { + if (v && v_) listener.point(x, y); else { + var l = { + a: { + x: x_, + y: y_ + }, + b: { + x: x, + y: y + } + }; + if (clipLine(l)) { + if (!v_) { + listener.lineStart(); + listener.point(l.a.x, l.a.y); + } + listener.point(l.b.x, l.b.y); + if (!v) listener.lineEnd(); + clean = false; + } else if (v) { + listener.lineStart(); + listener.point(x, y); + clean = false; + } + } + } + x_ = x, y_ = y, v_ = v; + } + return clip; + }; + function corner(p, direction) { + return abs(p[0] - x0) < ε ? direction > 0 ? 0 : 3 : abs(p[0] - x1) < ε ? direction > 0 ? 2 : 1 : abs(p[1] - y0) < ε ? direction > 0 ? 1 : 0 : direction > 0 ? 3 : 2; + } + function compare(a, b) { + return comparePoints(a.x, b.x); + } + function comparePoints(a, b) { + var ca = corner(a, 1), cb = corner(b, 1); + return ca !== cb ? ca - cb : ca === 0 ? b[1] - a[1] : ca === 1 ? a[0] - b[0] : ca === 2 ? a[1] - b[1] : b[0] - a[0]; + } + } + function d3_geo_compose(a, b) { + function compose(x, y) { + return x = a(x, y), b(x[0], x[1]); + } + if (a.invert && b.invert) compose.invert = function(x, y) { + return x = b.invert(x, y), x && a.invert(x[0], x[1]); + }; + return compose; + } + function d3_geo_conic(projectAt) { + var φ0 = 0, φ1 = π / 3, m = d3_geo_projectionMutator(projectAt), p = m(φ0, φ1); + p.parallels = function(_) { + if (!arguments.length) return [ φ0 / π * 180, φ1 / π * 180 ]; + return m(φ0 = _[0] * π / 180, φ1 = _[1] * π / 180); + }; + return p; + } + function d3_geo_conicEqualArea(φ0, φ1) { + var sinφ0 = Math.sin(φ0), n = (sinφ0 + Math.sin(φ1)) / 2, C = 1 + sinφ0 * (2 * n - sinφ0), ρ0 = Math.sqrt(C) / n; + function forward(λ, φ) { + var ρ = Math.sqrt(C - 2 * n * Math.sin(φ)) / n; + return [ ρ * Math.sin(λ *= n), ρ0 - ρ * Math.cos(λ) ]; + } + forward.invert = function(x, y) { + var ρ0_y = ρ0 - y; + return [ Math.atan2(x, ρ0_y) / n, d3_asin((C - (x * x + ρ0_y * ρ0_y) * n * n) / (2 * n)) ]; + }; + return forward; + } + (d3.geo.conicEqualArea = function() { + return d3_geo_conic(d3_geo_conicEqualArea); + }).raw = d3_geo_conicEqualArea; + d3.geo.albers = function() { + return d3.geo.conicEqualArea().rotate([ 96, 0 ]).center([ -.6, 38.7 ]).parallels([ 29.5, 45.5 ]).scale(1070); + }; + d3.geo.albersUsa = function() { + var lower48 = d3.geo.albers(); + var alaska = d3.geo.conicEqualArea().rotate([ 154, 0 ]).center([ -2, 58.5 ]).parallels([ 55, 65 ]); + var hawaii = d3.geo.conicEqualArea().rotate([ 157, 0 ]).center([ -3, 19.9 ]).parallels([ 8, 18 ]); + var point, pointStream = { + point: function(x, y) { + point = [ x, y ]; + } + }, lower48Point, alaskaPoint, hawaiiPoint; + function albersUsa(coordinates) { + var x = coordinates[0], y = coordinates[1]; + point = null; + (lower48Point(x, y), point) || (alaskaPoint(x, y), point) || hawaiiPoint(x, y); + return point; + } + albersUsa.invert = function(coordinates) { + var k = lower48.scale(), t = lower48.translate(), x = (coordinates[0] - t[0]) / k, y = (coordinates[1] - t[1]) / k; + return (y >= .12 && y < .234 && x >= -.425 && x < -.214 ? alaska : y >= .166 && y < .234 && x >= -.214 && x < -.115 ? hawaii : lower48).invert(coordinates); + }; + albersUsa.stream = function(stream) { + var lower48Stream = lower48.stream(stream), alaskaStream = alaska.stream(stream), hawaiiStream = hawaii.stream(stream); + return { + point: function(x, y) { + lower48Stream.point(x, y); + alaskaStream.point(x, y); + hawaiiStream.point(x, y); + }, + sphere: function() { + lower48Stream.sphere(); + alaskaStream.sphere(); + hawaiiStream.sphere(); + }, + lineStart: function() { + lower48Stream.lineStart(); + alaskaStream.lineStart(); + hawaiiStream.lineStart(); + }, + lineEnd: function() { + lower48Stream.lineEnd(); + alaskaStream.lineEnd(); + hawaiiStream.lineEnd(); + }, + polygonStart: function() { + lower48Stream.polygonStart(); + alaskaStream.polygonStart(); + hawaiiStream.polygonStart(); + }, + polygonEnd: function() { + lower48Stream.polygonEnd(); + alaskaStream.polygonEnd(); + hawaiiStream.polygonEnd(); + } + }; + }; + albersUsa.precision = function(_) { + if (!arguments.length) return lower48.precision(); + lower48.precision(_); + alaska.precision(_); + hawaii.precision(_); + return albersUsa; + }; + albersUsa.scale = function(_) { + if (!arguments.length) return lower48.scale(); + lower48.scale(_); + alaska.scale(_ * .35); + hawaii.scale(_); + return albersUsa.translate(lower48.translate()); + }; + albersUsa.translate = function(_) { + if (!arguments.length) return lower48.translate(); + var k = lower48.scale(), x = +_[0], y = +_[1]; + lower48Point = lower48.translate(_).clipExtent([ [ x - .455 * k, y - .238 * k ], [ x + .455 * k, y + .238 * k ] ]).stream(pointStream).point; + alaskaPoint = alaska.translate([ x - .307 * k, y + .201 * k ]).clipExtent([ [ x - .425 * k + ε, y + .12 * k + ε ], [ x - .214 * k - ε, y + .234 * k - ε ] ]).stream(pointStream).point; + hawaiiPoint = hawaii.translate([ x - .205 * k, y + .212 * k ]).clipExtent([ [ x - .214 * k + ε, y + .166 * k + ε ], [ x - .115 * k - ε, y + .234 * k - ε ] ]).stream(pointStream).point; + return albersUsa; + }; + return albersUsa.scale(1070); + }; + var d3_geo_pathAreaSum, d3_geo_pathAreaPolygon, d3_geo_pathArea = { + point: d3_noop, + lineStart: d3_noop, + lineEnd: d3_noop, + polygonStart: function() { + d3_geo_pathAreaPolygon = 0; + d3_geo_pathArea.lineStart = d3_geo_pathAreaRingStart; + }, + polygonEnd: function() { + d3_geo_pathArea.lineStart = d3_geo_pathArea.lineEnd = d3_geo_pathArea.point = d3_noop; + d3_geo_pathAreaSum += abs(d3_geo_pathAreaPolygon / 2); + } + }; + function d3_geo_pathAreaRingStart() { + var x00, y00, x0, y0; + d3_geo_pathArea.point = function(x, y) { + d3_geo_pathArea.point = nextPoint; + x00 = x0 = x, y00 = y0 = y; + }; + function nextPoint(x, y) { + d3_geo_pathAreaPolygon += y0 * x - x0 * y; + x0 = x, y0 = y; + } + d3_geo_pathArea.lineEnd = function() { + nextPoint(x00, y00); + }; + } + var d3_geo_pathBoundsX0, d3_geo_pathBoundsY0, d3_geo_pathBoundsX1, d3_geo_pathBoundsY1; + var d3_geo_pathBounds = { + point: d3_geo_pathBoundsPoint, + lineStart: d3_noop, + lineEnd: d3_noop, + polygonStart: d3_noop, + polygonEnd: d3_noop + }; + function d3_geo_pathBoundsPoint(x, y) { + if (x < d3_geo_pathBoundsX0) d3_geo_pathBoundsX0 = x; + if (x > d3_geo_pathBoundsX1) d3_geo_pathBoundsX1 = x; + if (y < d3_geo_pathBoundsY0) d3_geo_pathBoundsY0 = y; + if (y > d3_geo_pathBoundsY1) d3_geo_pathBoundsY1 = y; + } + function d3_geo_pathBuffer() { + var pointCircle = d3_geo_pathBufferCircle(4.5), buffer = []; + var stream = { + point: point, + lineStart: function() { + stream.point = pointLineStart; + }, + lineEnd: lineEnd, + polygonStart: function() { + stream.lineEnd = lineEndPolygon; + }, + polygonEnd: function() { + stream.lineEnd = lineEnd; + stream.point = point; + }, + pointRadius: function(_) { + pointCircle = d3_geo_pathBufferCircle(_); + return stream; + }, + result: function() { + if (buffer.length) { + var result = buffer.join(""); + buffer = []; + return result; + } + } + }; + function point(x, y) { + buffer.push("M", x, ",", y, pointCircle); + } + function pointLineStart(x, y) { + buffer.push("M", x, ",", y); + stream.point = pointLine; + } + function pointLine(x, y) { + buffer.push("L", x, ",", y); + } + function lineEnd() { + stream.point = point; + } + function lineEndPolygon() { + buffer.push("Z"); + } + return stream; + } + function d3_geo_pathBufferCircle(radius) { + return "m0," + radius + "a" + radius + "," + radius + " 0 1,1 0," + -2 * radius + "a" + radius + "," + radius + " 0 1,1 0," + 2 * radius + "z"; + } + var d3_geo_pathCentroid = { + point: d3_geo_pathCentroidPoint, + lineStart: d3_geo_pathCentroidLineStart, + lineEnd: d3_geo_pathCentroidLineEnd, + polygonStart: function() { + d3_geo_pathCentroid.lineStart = d3_geo_pathCentroidRingStart; + }, + polygonEnd: function() { + d3_geo_pathCentroid.point = d3_geo_pathCentroidPoint; + d3_geo_pathCentroid.lineStart = d3_geo_pathCentroidLineStart; + d3_geo_pathCentroid.lineEnd = d3_geo_pathCentroidLineEnd; + } + }; + function d3_geo_pathCentroidPoint(x, y) { + d3_geo_centroidX0 += x; + d3_geo_centroidY0 += y; + ++d3_geo_centroidZ0; + } + function d3_geo_pathCentroidLineStart() { + var x0, y0; + d3_geo_pathCentroid.point = function(x, y) { + d3_geo_pathCentroid.point = nextPoint; + d3_geo_pathCentroidPoint(x0 = x, y0 = y); + }; + function nextPoint(x, y) { + var dx = x - x0, dy = y - y0, z = Math.sqrt(dx * dx + dy * dy); + d3_geo_centroidX1 += z * (x0 + x) / 2; + d3_geo_centroidY1 += z * (y0 + y) / 2; + d3_geo_centroidZ1 += z; + d3_geo_pathCentroidPoint(x0 = x, y0 = y); + } + } + function d3_geo_pathCentroidLineEnd() { + d3_geo_pathCentroid.point = d3_geo_pathCentroidPoint; + } + function d3_geo_pathCentroidRingStart() { + var x00, y00, x0, y0; + d3_geo_pathCentroid.point = function(x, y) { + d3_geo_pathCentroid.point = nextPoint; + d3_geo_pathCentroidPoint(x00 = x0 = x, y00 = y0 = y); + }; + function nextPoint(x, y) { + var dx = x - x0, dy = y - y0, z = Math.sqrt(dx * dx + dy * dy); + d3_geo_centroidX1 += z * (x0 + x) / 2; + d3_geo_centroidY1 += z * (y0 + y) / 2; + d3_geo_centroidZ1 += z; + z = y0 * x - x0 * y; + d3_geo_centroidX2 += z * (x0 + x); + d3_geo_centroidY2 += z * (y0 + y); + d3_geo_centroidZ2 += z * 3; + d3_geo_pathCentroidPoint(x0 = x, y0 = y); + } + d3_geo_pathCentroid.lineEnd = function() { + nextPoint(x00, y00); + }; + } + function d3_geo_pathContext(context) { + var pointRadius = 4.5; + var stream = { + point: point, + lineStart: function() { + stream.point = pointLineStart; + }, + lineEnd: lineEnd, + polygonStart: function() { + stream.lineEnd = lineEndPolygon; + }, + polygonEnd: function() { + stream.lineEnd = lineEnd; + stream.point = point; + }, + pointRadius: function(_) { + pointRadius = _; + return stream; + }, + result: d3_noop + }; + function point(x, y) { + context.moveTo(x, y); + context.arc(x, y, pointRadius, 0, τ); + } + function pointLineStart(x, y) { + context.moveTo(x, y); + stream.point = pointLine; + } + function pointLine(x, y) { + context.lineTo(x, y); + } + function lineEnd() { + stream.point = point; + } + function lineEndPolygon() { + context.closePath(); + } + return stream; + } + function d3_geo_resample(project) { + var δ2 = .5, cosMinDistance = Math.cos(30 * d3_radians), maxDepth = 16; + function resample(stream) { + return (maxDepth ? resampleRecursive : resampleNone)(stream); + } + function resampleNone(stream) { + return d3_geo_transformPoint(stream, function(x, y) { + x = project(x, y); + stream.point(x[0], x[1]); + }); + } + function resampleRecursive(stream) { + var λ00, φ00, x00, y00, a00, b00, c00, λ0, x0, y0, a0, b0, c0; + var resample = { + point: point, + lineStart: lineStart, + lineEnd: lineEnd, + polygonStart: function() { + stream.polygonStart(); + resample.lineStart = ringStart; + }, + polygonEnd: function() { + stream.polygonEnd(); + resample.lineStart = lineStart; + } + }; + function point(x, y) { + x = project(x, y); + stream.point(x[0], x[1]); + } + function lineStart() { + x0 = NaN; + resample.point = linePoint; + stream.lineStart(); + } + function linePoint(λ, φ) { + var c = d3_geo_cartesian([ λ, φ ]), p = project(λ, φ); + resampleLineTo(x0, y0, λ0, a0, b0, c0, x0 = p[0], y0 = p[1], λ0 = λ, a0 = c[0], b0 = c[1], c0 = c[2], maxDepth, stream); + stream.point(x0, y0); + } + function lineEnd() { + resample.point = point; + stream.lineEnd(); + } + function ringStart() { + lineStart(); + resample.point = ringPoint; + resample.lineEnd = ringEnd; + } + function ringPoint(λ, φ) { + linePoint(λ00 = λ, φ00 = φ), x00 = x0, y00 = y0, a00 = a0, b00 = b0, c00 = c0; + resample.point = linePoint; + } + function ringEnd() { + resampleLineTo(x0, y0, λ0, a0, b0, c0, x00, y00, λ00, a00, b00, c00, maxDepth, stream); + resample.lineEnd = lineEnd; + lineEnd(); + } + return resample; + } + function resampleLineTo(x0, y0, λ0, a0, b0, c0, x1, y1, λ1, a1, b1, c1, depth, stream) { + var dx = x1 - x0, dy = y1 - y0, d2 = dx * dx + dy * dy; + if (d2 > 4 * δ2 && depth--) { + var a = a0 + a1, b = b0 + b1, c = c0 + c1, m = Math.sqrt(a * a + b * b + c * c), φ2 = Math.asin(c /= m), λ2 = abs(abs(c) - 1) < ε || abs(λ0 - λ1) < ε ? (λ0 + λ1) / 2 : Math.atan2(b, a), p = project(λ2, φ2), x2 = p[0], y2 = p[1], dx2 = x2 - x0, dy2 = y2 - y0, dz = dy * dx2 - dx * dy2; + if (dz * dz / d2 > δ2 || abs((dx * dx2 + dy * dy2) / d2 - .5) > .3 || a0 * a1 + b0 * b1 + c0 * c1 < cosMinDistance) { + resampleLineTo(x0, y0, λ0, a0, b0, c0, x2, y2, λ2, a /= m, b /= m, c, depth, stream); + stream.point(x2, y2); + resampleLineTo(x2, y2, λ2, a, b, c, x1, y1, λ1, a1, b1, c1, depth, stream); + } + } + } + resample.precision = function(_) { + if (!arguments.length) return Math.sqrt(δ2); + maxDepth = (δ2 = _ * _) > 0 && 16; + return resample; + }; + return resample; + } + d3.geo.path = function() { + var pointRadius = 4.5, projection, context, projectStream, contextStream, cacheStream; + function path(object) { + if (object) { + if (typeof pointRadius === "function") contextStream.pointRadius(+pointRadius.apply(this, arguments)); + if (!cacheStream || !cacheStream.valid) cacheStream = projectStream(contextStream); + d3.geo.stream(object, cacheStream); + } + return contextStream.result(); + } + path.area = function(object) { + d3_geo_pathAreaSum = 0; + d3.geo.stream(object, projectStream(d3_geo_pathArea)); + return d3_geo_pathAreaSum; + }; + path.centroid = function(object) { + d3_geo_centroidX0 = d3_geo_centroidY0 = d3_geo_centroidZ0 = d3_geo_centroidX1 = d3_geo_centroidY1 = d3_geo_centroidZ1 = d3_geo_centroidX2 = d3_geo_centroidY2 = d3_geo_centroidZ2 = 0; + d3.geo.stream(object, projectStream(d3_geo_pathCentroid)); + return d3_geo_centroidZ2 ? [ d3_geo_centroidX2 / d3_geo_centroidZ2, d3_geo_centroidY2 / d3_geo_centroidZ2 ] : d3_geo_centroidZ1 ? [ d3_geo_centroidX1 / d3_geo_centroidZ1, d3_geo_centroidY1 / d3_geo_centroidZ1 ] : d3_geo_centroidZ0 ? [ d3_geo_centroidX0 / d3_geo_centroidZ0, d3_geo_centroidY0 / d3_geo_centroidZ0 ] : [ NaN, NaN ]; + }; + path.bounds = function(object) { + d3_geo_pathBoundsX1 = d3_geo_pathBoundsY1 = -(d3_geo_pathBoundsX0 = d3_geo_pathBoundsY0 = Infinity); + d3.geo.stream(object, projectStream(d3_geo_pathBounds)); + return [ [ d3_geo_pathBoundsX0, d3_geo_pathBoundsY0 ], [ d3_geo_pathBoundsX1, d3_geo_pathBoundsY1 ] ]; + }; + path.projection = function(_) { + if (!arguments.length) return projection; + projectStream = (projection = _) ? _.stream || d3_geo_pathProjectStream(_) : d3_identity; + return reset(); + }; + path.context = function(_) { + if (!arguments.length) return context; + contextStream = (context = _) == null ? new d3_geo_pathBuffer() : new d3_geo_pathContext(_); + if (typeof pointRadius !== "function") contextStream.pointRadius(pointRadius); + return reset(); + }; + path.pointRadius = function(_) { + if (!arguments.length) return pointRadius; + pointRadius = typeof _ === "function" ? _ : (contextStream.pointRadius(+_), +_); + return path; + }; + function reset() { + cacheStream = null; + return path; + } + return path.projection(d3.geo.albersUsa()).context(null); + }; + function d3_geo_pathProjectStream(project) { + var resample = d3_geo_resample(function(x, y) { + return project([ x * d3_degrees, y * d3_degrees ]); + }); + return function(stream) { + return d3_geo_projectionRadians(resample(stream)); + }; + } + d3.geo.transform = function(methods) { + return { + stream: function(stream) { + var transform = new d3_geo_transform(stream); + for (var k in methods) transform[k] = methods[k]; + return transform; + } + }; + }; + function d3_geo_transform(stream) { + this.stream = stream; + } + d3_geo_transform.prototype = { + point: function(x, y) { + this.stream.point(x, y); + }, + sphere: function() { + this.stream.sphere(); + }, + lineStart: function() { + this.stream.lineStart(); + }, + lineEnd: function() { + this.stream.lineEnd(); + }, + polygonStart: function() { + this.stream.polygonStart(); + }, + polygonEnd: function() { + this.stream.polygonEnd(); + } + }; + function d3_geo_transformPoint(stream, point) { + return { + point: point, + sphere: function() { + stream.sphere(); + }, + lineStart: function() { + stream.lineStart(); + }, + lineEnd: function() { + stream.lineEnd(); + }, + polygonStart: function() { + stream.polygonStart(); + }, + polygonEnd: function() { + stream.polygonEnd(); + } + }; + } + d3.geo.projection = d3_geo_projection; + d3.geo.projectionMutator = d3_geo_projectionMutator; + function d3_geo_projection(project) { + return d3_geo_projectionMutator(function() { + return project; + })(); + } + function d3_geo_projectionMutator(projectAt) { + var project, rotate, projectRotate, projectResample = d3_geo_resample(function(x, y) { + x = project(x, y); + return [ x[0] * k + δx, δy - x[1] * k ]; + }), k = 150, x = 480, y = 250, λ = 0, φ = 0, δλ = 0, δφ = 0, δγ = 0, δx, δy, preclip = d3_geo_clipAntimeridian, postclip = d3_identity, clipAngle = null, clipExtent = null, stream; + function projection(point) { + point = projectRotate(point[0] * d3_radians, point[1] * d3_radians); + return [ point[0] * k + δx, δy - point[1] * k ]; + } + function invert(point) { + point = projectRotate.invert((point[0] - δx) / k, (δy - point[1]) / k); + return point && [ point[0] * d3_degrees, point[1] * d3_degrees ]; + } + projection.stream = function(output) { + if (stream) stream.valid = false; + stream = d3_geo_projectionRadians(preclip(rotate, projectResample(postclip(output)))); + stream.valid = true; + return stream; + }; + projection.clipAngle = function(_) { + if (!arguments.length) return clipAngle; + preclip = _ == null ? (clipAngle = _, d3_geo_clipAntimeridian) : d3_geo_clipCircle((clipAngle = +_) * d3_radians); + return invalidate(); + }; + projection.clipExtent = function(_) { + if (!arguments.length) return clipExtent; + clipExtent = _; + postclip = _ ? d3_geo_clipExtent(_[0][0], _[0][1], _[1][0], _[1][1]) : d3_identity; + return invalidate(); + }; + projection.scale = function(_) { + if (!arguments.length) return k; + k = +_; + return reset(); + }; + projection.translate = function(_) { + if (!arguments.length) return [ x, y ]; + x = +_[0]; + y = +_[1]; + return reset(); + }; + projection.center = function(_) { + if (!arguments.length) return [ λ * d3_degrees, φ * d3_degrees ]; + λ = _[0] % 360 * d3_radians; + φ = _[1] % 360 * d3_radians; + return reset(); + }; + projection.rotate = function(_) { + if (!arguments.length) return [ δλ * d3_degrees, δφ * d3_degrees, δγ * d3_degrees ]; + δλ = _[0] % 360 * d3_radians; + δφ = _[1] % 360 * d3_radians; + δγ = _.length > 2 ? _[2] % 360 * d3_radians : 0; + return reset(); + }; + d3.rebind(projection, projectResample, "precision"); + function reset() { + projectRotate = d3_geo_compose(rotate = d3_geo_rotation(δλ, δφ, δγ), project); + var center = project(λ, φ); + δx = x - center[0] * k; + δy = y + center[1] * k; + return invalidate(); + } + function invalidate() { + if (stream) stream.valid = false, stream = null; + return projection; + } + return function() { + project = projectAt.apply(this, arguments); + projection.invert = project.invert && invert; + return reset(); + }; + } + function d3_geo_projectionRadians(stream) { + return d3_geo_transformPoint(stream, function(x, y) { + stream.point(x * d3_radians, y * d3_radians); + }); + } + function d3_geo_equirectangular(λ, φ) { + return [ λ, φ ]; + } + (d3.geo.equirectangular = function() { + return d3_geo_projection(d3_geo_equirectangular); + }).raw = d3_geo_equirectangular.invert = d3_geo_equirectangular; + d3.geo.rotation = function(rotate) { + rotate = d3_geo_rotation(rotate[0] % 360 * d3_radians, rotate[1] * d3_radians, rotate.length > 2 ? rotate[2] * d3_radians : 0); + function forward(coordinates) { + coordinates = rotate(coordinates[0] * d3_radians, coordinates[1] * d3_radians); + return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates; + } + forward.invert = function(coordinates) { + coordinates = rotate.invert(coordinates[0] * d3_radians, coordinates[1] * d3_radians); + return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates; + }; + return forward; + }; + function d3_geo_identityRotation(λ, φ) { + return [ λ > π ? λ - τ : λ < -π ? λ + τ : λ, φ ]; + } + d3_geo_identityRotation.invert = d3_geo_equirectangular; + function d3_geo_rotation(δλ, δφ, δγ) { + return δλ ? δφ || δγ ? d3_geo_compose(d3_geo_rotationλ(δλ), d3_geo_rotationφγ(δφ, δγ)) : d3_geo_rotationλ(δλ) : δφ || δγ ? d3_geo_rotationφγ(δφ, δγ) : d3_geo_identityRotation; + } + function d3_geo_forwardRotationλ(δλ) { + return function(λ, φ) { + return λ += δλ, [ λ > π ? λ - τ : λ < -π ? λ + τ : λ, φ ]; + }; + } + function d3_geo_rotationλ(δλ) { + var rotation = d3_geo_forwardRotationλ(δλ); + rotation.invert = d3_geo_forwardRotationλ(-δλ); + return rotation; + } + function d3_geo_rotationφγ(δφ, δγ) { + var cosδφ = Math.cos(δφ), sinδφ = Math.sin(δφ), cosδγ = Math.cos(δγ), sinδγ = Math.sin(δγ); + function rotation(λ, φ) { + var cosφ = Math.cos(φ), x = Math.cos(λ) * cosφ, y = Math.sin(λ) * cosφ, z = Math.sin(φ), k = z * cosδφ + x * sinδφ; + return [ Math.atan2(y * cosδγ - k * sinδγ, x * cosδφ - z * sinδφ), d3_asin(k * cosδγ + y * sinδγ) ]; + } + rotation.invert = function(λ, φ) { + var cosφ = Math.cos(φ), x = Math.cos(λ) * cosφ, y = Math.sin(λ) * cosφ, z = Math.sin(φ), k = z * cosδγ - y * sinδγ; + return [ Math.atan2(y * cosδγ + z * sinδγ, x * cosδφ + k * sinδφ), d3_asin(k * cosδφ - x * sinδφ) ]; + }; + return rotation; + } + d3.geo.circle = function() { + var origin = [ 0, 0 ], angle, precision = 6, interpolate; + function circle() { + var center = typeof origin === "function" ? origin.apply(this, arguments) : origin, rotate = d3_geo_rotation(-center[0] * d3_radians, -center[1] * d3_radians, 0).invert, ring = []; + interpolate(null, null, 1, { + point: function(x, y) { + ring.push(x = rotate(x, y)); + x[0] *= d3_degrees, x[1] *= d3_degrees; + } + }); + return { + type: "Polygon", + coordinates: [ ring ] + }; + } + circle.origin = function(x) { + if (!arguments.length) return origin; + origin = x; + return circle; + }; + circle.angle = function(x) { + if (!arguments.length) return angle; + interpolate = d3_geo_circleInterpolate((angle = +x) * d3_radians, precision * d3_radians); + return circle; + }; + circle.precision = function(_) { + if (!arguments.length) return precision; + interpolate = d3_geo_circleInterpolate(angle * d3_radians, (precision = +_) * d3_radians); + return circle; + }; + return circle.angle(90); + }; + function d3_geo_circleInterpolate(radius, precision) { + var cr = Math.cos(radius), sr = Math.sin(radius); + return function(from, to, direction, listener) { + var step = direction * precision; + if (from != null) { + from = d3_geo_circleAngle(cr, from); + to = d3_geo_circleAngle(cr, to); + if (direction > 0 ? from < to : from > to) from += direction * τ; + } else { + from = radius + direction * τ; + to = radius - .5 * step; + } + for (var point, t = from; direction > 0 ? t > to : t < to; t -= step) { + listener.point((point = d3_geo_spherical([ cr, -sr * Math.cos(t), -sr * Math.sin(t) ]))[0], point[1]); + } + }; + } + function d3_geo_circleAngle(cr, point) { + var a = d3_geo_cartesian(point); + a[0] -= cr; + d3_geo_cartesianNormalize(a); + var angle = d3_acos(-a[1]); + return ((-a[2] < 0 ? -angle : angle) + 2 * Math.PI - ε) % (2 * Math.PI); + } + d3.geo.distance = function(a, b) { + var Δλ = (b[0] - a[0]) * d3_radians, φ0 = a[1] * d3_radians, φ1 = b[1] * d3_radians, sinΔλ = Math.sin(Δλ), cosΔλ = Math.cos(Δλ), sinφ0 = Math.sin(φ0), cosφ0 = Math.cos(φ0), sinφ1 = Math.sin(φ1), cosφ1 = Math.cos(φ1), t; + return Math.atan2(Math.sqrt((t = cosφ1 * sinΔλ) * t + (t = cosφ0 * sinφ1 - sinφ0 * cosφ1 * cosΔλ) * t), sinφ0 * sinφ1 + cosφ0 * cosφ1 * cosΔλ); + }; + d3.geo.graticule = function() { + var x1, x0, X1, X0, y1, y0, Y1, Y0, dx = 10, dy = dx, DX = 90, DY = 360, x, y, X, Y, precision = 2.5; + function graticule() { + return { + type: "MultiLineString", + coordinates: lines() + }; + } + function lines() { + return d3.range(Math.ceil(X0 / DX) * DX, X1, DX).map(X).concat(d3.range(Math.ceil(Y0 / DY) * DY, Y1, DY).map(Y)).concat(d3.range(Math.ceil(x0 / dx) * dx, x1, dx).filter(function(x) { + return abs(x % DX) > ε; + }).map(x)).concat(d3.range(Math.ceil(y0 / dy) * dy, y1, dy).filter(function(y) { + return abs(y % DY) > ε; + }).map(y)); + } + graticule.lines = function() { + return lines().map(function(coordinates) { + return { + type: "LineString", + coordinates: coordinates + }; + }); + }; + graticule.outline = function() { + return { + type: "Polygon", + coordinates: [ X(X0).concat(Y(Y1).slice(1), X(X1).reverse().slice(1), Y(Y0).reverse().slice(1)) ] + }; + }; + graticule.extent = function(_) { + if (!arguments.length) return graticule.minorExtent(); + return graticule.majorExtent(_).minorExtent(_); + }; + graticule.majorExtent = function(_) { + if (!arguments.length) return [ [ X0, Y0 ], [ X1, Y1 ] ]; + X0 = +_[0][0], X1 = +_[1][0]; + Y0 = +_[0][1], Y1 = +_[1][1]; + if (X0 > X1) _ = X0, X0 = X1, X1 = _; + if (Y0 > Y1) _ = Y0, Y0 = Y1, Y1 = _; + return graticule.precision(precision); + }; + graticule.minorExtent = function(_) { + if (!arguments.length) return [ [ x0, y0 ], [ x1, y1 ] ]; + x0 = +_[0][0], x1 = +_[1][0]; + y0 = +_[0][1], y1 = +_[1][1]; + if (x0 > x1) _ = x0, x0 = x1, x1 = _; + if (y0 > y1) _ = y0, y0 = y1, y1 = _; + return graticule.precision(precision); + }; + graticule.step = function(_) { + if (!arguments.length) return graticule.minorStep(); + return graticule.majorStep(_).minorStep(_); + }; + graticule.majorStep = function(_) { + if (!arguments.length) return [ DX, DY ]; + DX = +_[0], DY = +_[1]; + return graticule; + }; + graticule.minorStep = function(_) { + if (!arguments.length) return [ dx, dy ]; + dx = +_[0], dy = +_[1]; + return graticule; + }; + graticule.precision = function(_) { + if (!arguments.length) return precision; + precision = +_; + x = d3_geo_graticuleX(y0, y1, 90); + y = d3_geo_graticuleY(x0, x1, precision); + X = d3_geo_graticuleX(Y0, Y1, 90); + Y = d3_geo_graticuleY(X0, X1, precision); + return graticule; + }; + return graticule.majorExtent([ [ -180, -90 + ε ], [ 180, 90 - ε ] ]).minorExtent([ [ -180, -80 - ε ], [ 180, 80 + ε ] ]); + }; + function d3_geo_graticuleX(y0, y1, dy) { + var y = d3.range(y0, y1 - ε, dy).concat(y1); + return function(x) { + return y.map(function(y) { + return [ x, y ]; + }); + }; + } + function d3_geo_graticuleY(x0, x1, dx) { + var x = d3.range(x0, x1 - ε, dx).concat(x1); + return function(y) { + return x.map(function(x) { + return [ x, y ]; + }); + }; + } + function d3_source(d) { + return d.source; + } + function d3_target(d) { + return d.target; + } + d3.geo.greatArc = function() { + var source = d3_source, source_, target = d3_target, target_; + function greatArc() { + return { + type: "LineString", + coordinates: [ source_ || source.apply(this, arguments), target_ || target.apply(this, arguments) ] + }; + } + greatArc.distance = function() { + return d3.geo.distance(source_ || source.apply(this, arguments), target_ || target.apply(this, arguments)); + }; + greatArc.source = function(_) { + if (!arguments.length) return source; + source = _, source_ = typeof _ === "function" ? null : _; + return greatArc; + }; + greatArc.target = function(_) { + if (!arguments.length) return target; + target = _, target_ = typeof _ === "function" ? null : _; + return greatArc; + }; + greatArc.precision = function() { + return arguments.length ? greatArc : 0; + }; + return greatArc; + }; + d3.geo.interpolate = function(source, target) { + return d3_geo_interpolate(source[0] * d3_radians, source[1] * d3_radians, target[0] * d3_radians, target[1] * d3_radians); + }; + function d3_geo_interpolate(x0, y0, x1, y1) { + var cy0 = Math.cos(y0), sy0 = Math.sin(y0), cy1 = Math.cos(y1), sy1 = Math.sin(y1), kx0 = cy0 * Math.cos(x0), ky0 = cy0 * Math.sin(x0), kx1 = cy1 * Math.cos(x1), ky1 = cy1 * Math.sin(x1), d = 2 * Math.asin(Math.sqrt(d3_haversin(y1 - y0) + cy0 * cy1 * d3_haversin(x1 - x0))), k = 1 / Math.sin(d); + var interpolate = d ? function(t) { + var B = Math.sin(t *= d) * k, A = Math.sin(d - t) * k, x = A * kx0 + B * kx1, y = A * ky0 + B * ky1, z = A * sy0 + B * sy1; + return [ Math.atan2(y, x) * d3_degrees, Math.atan2(z, Math.sqrt(x * x + y * y)) * d3_degrees ]; + } : function() { + return [ x0 * d3_degrees, y0 * d3_degrees ]; + }; + interpolate.distance = d; + return interpolate; + } + d3.geo.length = function(object) { + d3_geo_lengthSum = 0; + d3.geo.stream(object, d3_geo_length); + return d3_geo_lengthSum; + }; + var d3_geo_lengthSum; + var d3_geo_length = { + sphere: d3_noop, + point: d3_noop, + lineStart: d3_geo_lengthLineStart, + lineEnd: d3_noop, + polygonStart: d3_noop, + polygonEnd: d3_noop + }; + function d3_geo_lengthLineStart() { + var λ0, sinφ0, cosφ0; + d3_geo_length.point = function(λ, φ) { + λ0 = λ * d3_radians, sinφ0 = Math.sin(φ *= d3_radians), cosφ0 = Math.cos(φ); + d3_geo_length.point = nextPoint; + }; + d3_geo_length.lineEnd = function() { + d3_geo_length.point = d3_geo_length.lineEnd = d3_noop; + }; + function nextPoint(λ, φ) { + var sinφ = Math.sin(φ *= d3_radians), cosφ = Math.cos(φ), t = abs((λ *= d3_radians) - λ0), cosΔλ = Math.cos(t); + d3_geo_lengthSum += Math.atan2(Math.sqrt((t = cosφ * Math.sin(t)) * t + (t = cosφ0 * sinφ - sinφ0 * cosφ * cosΔλ) * t), sinφ0 * sinφ + cosφ0 * cosφ * cosΔλ); + λ0 = λ, sinφ0 = sinφ, cosφ0 = cosφ; + } + } + function d3_geo_azimuthal(scale, angle) { + function azimuthal(λ, φ) { + var cosλ = Math.cos(λ), cosφ = Math.cos(φ), k = scale(cosλ * cosφ); + return [ k * cosφ * Math.sin(λ), k * Math.sin(φ) ]; + } + azimuthal.invert = function(x, y) { + var ρ = Math.sqrt(x * x + y * y), c = angle(ρ), sinc = Math.sin(c), cosc = Math.cos(c); + return [ Math.atan2(x * sinc, ρ * cosc), Math.asin(ρ && y * sinc / ρ) ]; + }; + return azimuthal; + } + var d3_geo_azimuthalEqualArea = d3_geo_azimuthal(function(cosλcosφ) { + return Math.sqrt(2 / (1 + cosλcosφ)); + }, function(ρ) { + return 2 * Math.asin(ρ / 2); + }); + (d3.geo.azimuthalEqualArea = function() { + return d3_geo_projection(d3_geo_azimuthalEqualArea); + }).raw = d3_geo_azimuthalEqualArea; + var d3_geo_azimuthalEquidistant = d3_geo_azimuthal(function(cosλcosφ) { + var c = Math.acos(cosλcosφ); + return c && c / Math.sin(c); + }, d3_identity); + (d3.geo.azimuthalEquidistant = function() { + return d3_geo_projection(d3_geo_azimuthalEquidistant); + }).raw = d3_geo_azimuthalEquidistant; + function d3_geo_conicConformal(φ0, φ1) { + var cosφ0 = Math.cos(φ0), t = function(φ) { + return Math.tan(π / 4 + φ / 2); + }, n = φ0 === φ1 ? Math.sin(φ0) : Math.log(cosφ0 / Math.cos(φ1)) / Math.log(t(φ1) / t(φ0)), F = cosφ0 * Math.pow(t(φ0), n) / n; + if (!n) return d3_geo_mercator; + function forward(λ, φ) { + var ρ = abs(abs(φ) - halfπ) < ε ? 0 : F / Math.pow(t(φ), n); + return [ ρ * Math.sin(n * λ), F - ρ * Math.cos(n * λ) ]; + } + forward.invert = function(x, y) { + var ρ0_y = F - y, ρ = d3_sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y); + return [ Math.atan2(x, ρ0_y) / n, 2 * Math.atan(Math.pow(F / ρ, 1 / n)) - halfπ ]; + }; + return forward; + } + (d3.geo.conicConformal = function() { + return d3_geo_conic(d3_geo_conicConformal); + }).raw = d3_geo_conicConformal; + function d3_geo_conicEquidistant(φ0, φ1) { + var cosφ0 = Math.cos(φ0), n = φ0 === φ1 ? Math.sin(φ0) : (cosφ0 - Math.cos(φ1)) / (φ1 - φ0), G = cosφ0 / n + φ0; + if (abs(n) < ε) return d3_geo_equirectangular; + function forward(λ, φ) { + var ρ = G - φ; + return [ ρ * Math.sin(n * λ), G - ρ * Math.cos(n * λ) ]; + } + forward.invert = function(x, y) { + var ρ0_y = G - y; + return [ Math.atan2(x, ρ0_y) / n, G - d3_sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y) ]; + }; + return forward; + } + (d3.geo.conicEquidistant = function() { + return d3_geo_conic(d3_geo_conicEquidistant); + }).raw = d3_geo_conicEquidistant; + var d3_geo_gnomonic = d3_geo_azimuthal(function(cosλcosφ) { + return 1 / cosλcosφ; + }, Math.atan); + (d3.geo.gnomonic = function() { + return d3_geo_projection(d3_geo_gnomonic); + }).raw = d3_geo_gnomonic; + function d3_geo_mercator(λ, φ) { + return [ λ, Math.log(Math.tan(π / 4 + φ / 2)) ]; + } + d3_geo_mercator.invert = function(x, y) { + return [ x, 2 * Math.atan(Math.exp(y)) - halfπ ]; + }; + function d3_geo_mercatorProjection(project) { + var m = d3_geo_projection(project), scale = m.scale, translate = m.translate, clipExtent = m.clipExtent, clipAuto; + m.scale = function() { + var v = scale.apply(m, arguments); + return v === m ? clipAuto ? m.clipExtent(null) : m : v; + }; + m.translate = function() { + var v = translate.apply(m, arguments); + return v === m ? clipAuto ? m.clipExtent(null) : m : v; + }; + m.clipExtent = function(_) { + var v = clipExtent.apply(m, arguments); + if (v === m) { + if (clipAuto = _ == null) { + var k = π * scale(), t = translate(); + clipExtent([ [ t[0] - k, t[1] - k ], [ t[0] + k, t[1] + k ] ]); + } + } else if (clipAuto) { + v = null; + } + return v; + }; + return m.clipExtent(null); + } + (d3.geo.mercator = function() { + return d3_geo_mercatorProjection(d3_geo_mercator); + }).raw = d3_geo_mercator; + var d3_geo_orthographic = d3_geo_azimuthal(function() { + return 1; + }, Math.asin); + (d3.geo.orthographic = function() { + return d3_geo_projection(d3_geo_orthographic); + }).raw = d3_geo_orthographic; + var d3_geo_stereographic = d3_geo_azimuthal(function(cosλcosφ) { + return 1 / (1 + cosλcosφ); + }, function(ρ) { + return 2 * Math.atan(ρ); + }); + (d3.geo.stereographic = function() { + return d3_geo_projection(d3_geo_stereographic); + }).raw = d3_geo_stereographic; + function d3_geo_transverseMercator(λ, φ) { + return [ Math.log(Math.tan(π / 4 + φ / 2)), -λ ]; + } + d3_geo_transverseMercator.invert = function(x, y) { + return [ -y, 2 * Math.atan(Math.exp(x)) - halfπ ]; + }; + (d3.geo.transverseMercator = function() { + var projection = d3_geo_mercatorProjection(d3_geo_transverseMercator), center = projection.center, rotate = projection.rotate; + projection.center = function(_) { + return _ ? center([ -_[1], _[0] ]) : (_ = center(), [ -_[1], _[0] ]); + }; + projection.rotate = function(_) { + return _ ? rotate([ _[0], _[1], _.length > 2 ? _[2] + 90 : 90 ]) : (_ = rotate(), + [ _[0], _[1], _[2] - 90 ]); + }; + return projection.rotate([ 0, 0 ]); + }).raw = d3_geo_transverseMercator; + d3.geom = {}; + function d3_geom_pointX(d) { + return d[0]; + } + function d3_geom_pointY(d) { + return d[1]; + } + d3.geom.hull = function(vertices) { + var x = d3_geom_pointX, y = d3_geom_pointY; + if (arguments.length) return hull(vertices); + function hull(data) { + if (data.length < 3) return []; + var fx = d3_functor(x), fy = d3_functor(y), i, n = data.length, points = [], flippedPoints = []; + for (i = 0; i < n; i++) { + points.push([ +fx.call(this, data[i], i), +fy.call(this, data[i], i), i ]); + } + points.sort(d3_geom_hullOrder); + for (i = 0; i < n; i++) flippedPoints.push([ points[i][0], -points[i][1] ]); + var upper = d3_geom_hullUpper(points), lower = d3_geom_hullUpper(flippedPoints); + var skipLeft = lower[0] === upper[0], skipRight = lower[lower.length - 1] === upper[upper.length - 1], polygon = []; + for (i = upper.length - 1; i >= 0; --i) polygon.push(data[points[upper[i]][2]]); + for (i = +skipLeft; i < lower.length - skipRight; ++i) polygon.push(data[points[lower[i]][2]]); + return polygon; + } + hull.x = function(_) { + return arguments.length ? (x = _, hull) : x; + }; + hull.y = function(_) { + return arguments.length ? (y = _, hull) : y; + }; + return hull; + }; + function d3_geom_hullUpper(points) { + var n = points.length, hull = [ 0, 1 ], hs = 2; + for (var i = 2; i < n; i++) { + while (hs > 1 && d3_cross2d(points[hull[hs - 2]], points[hull[hs - 1]], points[i]) <= 0) --hs; + hull[hs++] = i; + } + return hull.slice(0, hs); + } + function d3_geom_hullOrder(a, b) { + return a[0] - b[0] || a[1] - b[1]; + } + d3.geom.polygon = function(coordinates) { + d3_subclass(coordinates, d3_geom_polygonPrototype); + return coordinates; + }; + var d3_geom_polygonPrototype = d3.geom.polygon.prototype = []; + d3_geom_polygonPrototype.area = function() { + var i = -1, n = this.length, a, b = this[n - 1], area = 0; + while (++i < n) { + a = b; + b = this[i]; + area += a[1] * b[0] - a[0] * b[1]; + } + return area * .5; + }; + d3_geom_polygonPrototype.centroid = function(k) { + var i = -1, n = this.length, x = 0, y = 0, a, b = this[n - 1], c; + if (!arguments.length) k = -1 / (6 * this.area()); + while (++i < n) { + a = b; + b = this[i]; + c = a[0] * b[1] - b[0] * a[1]; + x += (a[0] + b[0]) * c; + y += (a[1] + b[1]) * c; + } + return [ x * k, y * k ]; + }; + d3_geom_polygonPrototype.clip = function(subject) { + var input, closed = d3_geom_polygonClosed(subject), i = -1, n = this.length - d3_geom_polygonClosed(this), j, m, a = this[n - 1], b, c, d; + while (++i < n) { + input = subject.slice(); + subject.length = 0; + b = this[i]; + c = input[(m = input.length - closed) - 1]; + j = -1; + while (++j < m) { + d = input[j]; + if (d3_geom_polygonInside(d, a, b)) { + if (!d3_geom_polygonInside(c, a, b)) { + subject.push(d3_geom_polygonIntersect(c, d, a, b)); + } + subject.push(d); + } else if (d3_geom_polygonInside(c, a, b)) { + subject.push(d3_geom_polygonIntersect(c, d, a, b)); + } + c = d; + } + if (closed) subject.push(subject[0]); + a = b; + } + return subject; + }; + function d3_geom_polygonInside(p, a, b) { + return (b[0] - a[0]) * (p[1] - a[1]) < (b[1] - a[1]) * (p[0] - a[0]); + } + function d3_geom_polygonIntersect(c, d, a, b) { + var x1 = c[0], x3 = a[0], x21 = d[0] - x1, x43 = b[0] - x3, y1 = c[1], y3 = a[1], y21 = d[1] - y1, y43 = b[1] - y3, ua = (x43 * (y1 - y3) - y43 * (x1 - x3)) / (y43 * x21 - x43 * y21); + return [ x1 + ua * x21, y1 + ua * y21 ]; + } + function d3_geom_polygonClosed(coordinates) { + var a = coordinates[0], b = coordinates[coordinates.length - 1]; + return !(a[0] - b[0] || a[1] - b[1]); + } + var d3_geom_voronoiEdges, d3_geom_voronoiCells, d3_geom_voronoiBeaches, d3_geom_voronoiBeachPool = [], d3_geom_voronoiFirstCircle, d3_geom_voronoiCircles, d3_geom_voronoiCirclePool = []; + function d3_geom_voronoiBeach() { + d3_geom_voronoiRedBlackNode(this); + this.edge = this.site = this.circle = null; + } + function d3_geom_voronoiCreateBeach(site) { + var beach = d3_geom_voronoiBeachPool.pop() || new d3_geom_voronoiBeach(); + beach.site = site; + return beach; + } + function d3_geom_voronoiDetachBeach(beach) { + d3_geom_voronoiDetachCircle(beach); + d3_geom_voronoiBeaches.remove(beach); + d3_geom_voronoiBeachPool.push(beach); + d3_geom_voronoiRedBlackNode(beach); + } + function d3_geom_voronoiRemoveBeach(beach) { + var circle = beach.circle, x = circle.x, y = circle.cy, vertex = { + x: x, + y: y + }, previous = beach.P, next = beach.N, disappearing = [ beach ]; + d3_geom_voronoiDetachBeach(beach); + var lArc = previous; + while (lArc.circle && abs(x - lArc.circle.x) < ε && abs(y - lArc.circle.cy) < ε) { + previous = lArc.P; + disappearing.unshift(lArc); + d3_geom_voronoiDetachBeach(lArc); + lArc = previous; + } + disappearing.unshift(lArc); + d3_geom_voronoiDetachCircle(lArc); + var rArc = next; + while (rArc.circle && abs(x - rArc.circle.x) < ε && abs(y - rArc.circle.cy) < ε) { + next = rArc.N; + disappearing.push(rArc); + d3_geom_voronoiDetachBeach(rArc); + rArc = next; + } + disappearing.push(rArc); + d3_geom_voronoiDetachCircle(rArc); + var nArcs = disappearing.length, iArc; + for (iArc = 1; iArc < nArcs; ++iArc) { + rArc = disappearing[iArc]; + lArc = disappearing[iArc - 1]; + d3_geom_voronoiSetEdgeEnd(rArc.edge, lArc.site, rArc.site, vertex); + } + lArc = disappearing[0]; + rArc = disappearing[nArcs - 1]; + rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, rArc.site, null, vertex); + d3_geom_voronoiAttachCircle(lArc); + d3_geom_voronoiAttachCircle(rArc); + } + function d3_geom_voronoiAddBeach(site) { + var x = site.x, directrix = site.y, lArc, rArc, dxl, dxr, node = d3_geom_voronoiBeaches._; + while (node) { + dxl = d3_geom_voronoiLeftBreakPoint(node, directrix) - x; + if (dxl > ε) node = node.L; else { + dxr = x - d3_geom_voronoiRightBreakPoint(node, directrix); + if (dxr > ε) { + if (!node.R) { + lArc = node; + break; + } + node = node.R; + } else { + if (dxl > -ε) { + lArc = node.P; + rArc = node; + } else if (dxr > -ε) { + lArc = node; + rArc = node.N; + } else { + lArc = rArc = node; + } + break; + } + } + } + var newArc = d3_geom_voronoiCreateBeach(site); + d3_geom_voronoiBeaches.insert(lArc, newArc); + if (!lArc && !rArc) return; + if (lArc === rArc) { + d3_geom_voronoiDetachCircle(lArc); + rArc = d3_geom_voronoiCreateBeach(lArc.site); + d3_geom_voronoiBeaches.insert(newArc, rArc); + newArc.edge = rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site); + d3_geom_voronoiAttachCircle(lArc); + d3_geom_voronoiAttachCircle(rArc); + return; + } + if (!rArc) { + newArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site); + return; + } + d3_geom_voronoiDetachCircle(lArc); + d3_geom_voronoiDetachCircle(rArc); + var lSite = lArc.site, ax = lSite.x, ay = lSite.y, bx = site.x - ax, by = site.y - ay, rSite = rArc.site, cx = rSite.x - ax, cy = rSite.y - ay, d = 2 * (bx * cy - by * cx), hb = bx * bx + by * by, hc = cx * cx + cy * cy, vertex = { + x: (cy * hb - by * hc) / d + ax, + y: (bx * hc - cx * hb) / d + ay + }; + d3_geom_voronoiSetEdgeEnd(rArc.edge, lSite, rSite, vertex); + newArc.edge = d3_geom_voronoiCreateEdge(lSite, site, null, vertex); + rArc.edge = d3_geom_voronoiCreateEdge(site, rSite, null, vertex); + d3_geom_voronoiAttachCircle(lArc); + d3_geom_voronoiAttachCircle(rArc); + } + function d3_geom_voronoiLeftBreakPoint(arc, directrix) { + var site = arc.site, rfocx = site.x, rfocy = site.y, pby2 = rfocy - directrix; + if (!pby2) return rfocx; + var lArc = arc.P; + if (!lArc) return -Infinity; + site = lArc.site; + var lfocx = site.x, lfocy = site.y, plby2 = lfocy - directrix; + if (!plby2) return lfocx; + var hl = lfocx - rfocx, aby2 = 1 / pby2 - 1 / plby2, b = hl / plby2; + if (aby2) return (-b + Math.sqrt(b * b - 2 * aby2 * (hl * hl / (-2 * plby2) - lfocy + plby2 / 2 + rfocy - pby2 / 2))) / aby2 + rfocx; + return (rfocx + lfocx) / 2; + } + function d3_geom_voronoiRightBreakPoint(arc, directrix) { + var rArc = arc.N; + if (rArc) return d3_geom_voronoiLeftBreakPoint(rArc, directrix); + var site = arc.site; + return site.y === directrix ? site.x : Infinity; + } + function d3_geom_voronoiCell(site) { + this.site = site; + this.edges = []; + } + d3_geom_voronoiCell.prototype.prepare = function() { + var halfEdges = this.edges, iHalfEdge = halfEdges.length, edge; + while (iHalfEdge--) { + edge = halfEdges[iHalfEdge].edge; + if (!edge.b || !edge.a) halfEdges.splice(iHalfEdge, 1); + } + halfEdges.sort(d3_geom_voronoiHalfEdgeOrder); + return halfEdges.length; + }; + function d3_geom_voronoiCloseCells(extent) { + var x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], x2, y2, x3, y3, cells = d3_geom_voronoiCells, iCell = cells.length, cell, iHalfEdge, halfEdges, nHalfEdges, start, end; + while (iCell--) { + cell = cells[iCell]; + if (!cell || !cell.prepare()) continue; + halfEdges = cell.edges; + nHalfEdges = halfEdges.length; + iHalfEdge = 0; + while (iHalfEdge < nHalfEdges) { + end = halfEdges[iHalfEdge].end(), x3 = end.x, y3 = end.y; + start = halfEdges[++iHalfEdge % nHalfEdges].start(), x2 = start.x, y2 = start.y; + if (abs(x3 - x2) > ε || abs(y3 - y2) > ε) { + halfEdges.splice(iHalfEdge, 0, new d3_geom_voronoiHalfEdge(d3_geom_voronoiCreateBorderEdge(cell.site, end, abs(x3 - x0) < ε && y1 - y3 > ε ? { + x: x0, + y: abs(x2 - x0) < ε ? y2 : y1 + } : abs(y3 - y1) < ε && x1 - x3 > ε ? { + x: abs(y2 - y1) < ε ? x2 : x1, + y: y1 + } : abs(x3 - x1) < ε && y3 - y0 > ε ? { + x: x1, + y: abs(x2 - x1) < ε ? y2 : y0 + } : abs(y3 - y0) < ε && x3 - x0 > ε ? { + x: abs(y2 - y0) < ε ? x2 : x0, + y: y0 + } : null), cell.site, null)); + ++nHalfEdges; + } + } + } + } + function d3_geom_voronoiHalfEdgeOrder(a, b) { + return b.angle - a.angle; + } + function d3_geom_voronoiCircle() { + d3_geom_voronoiRedBlackNode(this); + this.x = this.y = this.arc = this.site = this.cy = null; + } + function d3_geom_voronoiAttachCircle(arc) { + var lArc = arc.P, rArc = arc.N; + if (!lArc || !rArc) return; + var lSite = lArc.site, cSite = arc.site, rSite = rArc.site; + if (lSite === rSite) return; + var bx = cSite.x, by = cSite.y, ax = lSite.x - bx, ay = lSite.y - by, cx = rSite.x - bx, cy = rSite.y - by; + var d = 2 * (ax * cy - ay * cx); + if (d >= -ε2) return; + var ha = ax * ax + ay * ay, hc = cx * cx + cy * cy, x = (cy * ha - ay * hc) / d, y = (ax * hc - cx * ha) / d, cy = y + by; + var circle = d3_geom_voronoiCirclePool.pop() || new d3_geom_voronoiCircle(); + circle.arc = arc; + circle.site = cSite; + circle.x = x + bx; + circle.y = cy + Math.sqrt(x * x + y * y); + circle.cy = cy; + arc.circle = circle; + var before = null, node = d3_geom_voronoiCircles._; + while (node) { + if (circle.y < node.y || circle.y === node.y && circle.x <= node.x) { + if (node.L) node = node.L; else { + before = node.P; + break; + } + } else { + if (node.R) node = node.R; else { + before = node; + break; + } + } + } + d3_geom_voronoiCircles.insert(before, circle); + if (!before) d3_geom_voronoiFirstCircle = circle; + } + function d3_geom_voronoiDetachCircle(arc) { + var circle = arc.circle; + if (circle) { + if (!circle.P) d3_geom_voronoiFirstCircle = circle.N; + d3_geom_voronoiCircles.remove(circle); + d3_geom_voronoiCirclePool.push(circle); + d3_geom_voronoiRedBlackNode(circle); + arc.circle = null; + } + } + function d3_geom_voronoiClipEdges(extent) { + var edges = d3_geom_voronoiEdges, clip = d3_geom_clipLine(extent[0][0], extent[0][1], extent[1][0], extent[1][1]), i = edges.length, e; + while (i--) { + e = edges[i]; + if (!d3_geom_voronoiConnectEdge(e, extent) || !clip(e) || abs(e.a.x - e.b.x) < ε && abs(e.a.y - e.b.y) < ε) { + e.a = e.b = null; + edges.splice(i, 1); + } + } + } + function d3_geom_voronoiConnectEdge(edge, extent) { + var vb = edge.b; + if (vb) return true; + var va = edge.a, x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], lSite = edge.l, rSite = edge.r, lx = lSite.x, ly = lSite.y, rx = rSite.x, ry = rSite.y, fx = (lx + rx) / 2, fy = (ly + ry) / 2, fm, fb; + if (ry === ly) { + if (fx < x0 || fx >= x1) return; + if (lx > rx) { + if (!va) va = { + x: fx, + y: y0 + }; else if (va.y >= y1) return; + vb = { + x: fx, + y: y1 + }; + } else { + if (!va) va = { + x: fx, + y: y1 + }; else if (va.y < y0) return; + vb = { + x: fx, + y: y0 + }; + } + } else { + fm = (lx - rx) / (ry - ly); + fb = fy - fm * fx; + if (fm < -1 || fm > 1) { + if (lx > rx) { + if (!va) va = { + x: (y0 - fb) / fm, + y: y0 + }; else if (va.y >= y1) return; + vb = { + x: (y1 - fb) / fm, + y: y1 + }; + } else { + if (!va) va = { + x: (y1 - fb) / fm, + y: y1 + }; else if (va.y < y0) return; + vb = { + x: (y0 - fb) / fm, + y: y0 + }; + } + } else { + if (ly < ry) { + if (!va) va = { + x: x0, + y: fm * x0 + fb + }; else if (va.x >= x1) return; + vb = { + x: x1, + y: fm * x1 + fb + }; + } else { + if (!va) va = { + x: x1, + y: fm * x1 + fb + }; else if (va.x < x0) return; + vb = { + x: x0, + y: fm * x0 + fb + }; + } + } + } + edge.a = va; + edge.b = vb; + return true; + } + function d3_geom_voronoiEdge(lSite, rSite) { + this.l = lSite; + this.r = rSite; + this.a = this.b = null; + } + function d3_geom_voronoiCreateEdge(lSite, rSite, va, vb) { + var edge = new d3_geom_voronoiEdge(lSite, rSite); + d3_geom_voronoiEdges.push(edge); + if (va) d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, va); + if (vb) d3_geom_voronoiSetEdgeEnd(edge, rSite, lSite, vb); + d3_geom_voronoiCells[lSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, lSite, rSite)); + d3_geom_voronoiCells[rSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, rSite, lSite)); + return edge; + } + function d3_geom_voronoiCreateBorderEdge(lSite, va, vb) { + var edge = new d3_geom_voronoiEdge(lSite, null); + edge.a = va; + edge.b = vb; + d3_geom_voronoiEdges.push(edge); + return edge; + } + function d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, vertex) { + if (!edge.a && !edge.b) { + edge.a = vertex; + edge.l = lSite; + edge.r = rSite; + } else if (edge.l === rSite) { + edge.b = vertex; + } else { + edge.a = vertex; + } + } + function d3_geom_voronoiHalfEdge(edge, lSite, rSite) { + var va = edge.a, vb = edge.b; + this.edge = edge; + this.site = lSite; + this.angle = rSite ? Math.atan2(rSite.y - lSite.y, rSite.x - lSite.x) : edge.l === lSite ? Math.atan2(vb.x - va.x, va.y - vb.y) : Math.atan2(va.x - vb.x, vb.y - va.y); + } + d3_geom_voronoiHalfEdge.prototype = { + start: function() { + return this.edge.l === this.site ? this.edge.a : this.edge.b; + }, + end: function() { + return this.edge.l === this.site ? this.edge.b : this.edge.a; + } + }; + function d3_geom_voronoiRedBlackTree() { + this._ = null; + } + function d3_geom_voronoiRedBlackNode(node) { + node.U = node.C = node.L = node.R = node.P = node.N = null; + } + d3_geom_voronoiRedBlackTree.prototype = { + insert: function(after, node) { + var parent, grandpa, uncle; + if (after) { + node.P = after; + node.N = after.N; + if (after.N) after.N.P = node; + after.N = node; + if (after.R) { + after = after.R; + while (after.L) after = after.L; + after.L = node; + } else { + after.R = node; + } + parent = after; + } else if (this._) { + after = d3_geom_voronoiRedBlackFirst(this._); + node.P = null; + node.N = after; + after.P = after.L = node; + parent = after; + } else { + node.P = node.N = null; + this._ = node; + parent = null; + } + node.L = node.R = null; + node.U = parent; + node.C = true; + after = node; + while (parent && parent.C) { + grandpa = parent.U; + if (parent === grandpa.L) { + uncle = grandpa.R; + if (uncle && uncle.C) { + parent.C = uncle.C = false; + grandpa.C = true; + after = grandpa; + } else { + if (after === parent.R) { + d3_geom_voronoiRedBlackRotateLeft(this, parent); + after = parent; + parent = after.U; + } + parent.C = false; + grandpa.C = true; + d3_geom_voronoiRedBlackRotateRight(this, grandpa); + } + } else { + uncle = grandpa.L; + if (uncle && uncle.C) { + parent.C = uncle.C = false; + grandpa.C = true; + after = grandpa; + } else { + if (after === parent.L) { + d3_geom_voronoiRedBlackRotateRight(this, parent); + after = parent; + parent = after.U; + } + parent.C = false; + grandpa.C = true; + d3_geom_voronoiRedBlackRotateLeft(this, grandpa); + } + } + parent = after.U; + } + this._.C = false; + }, + remove: function(node) { + if (node.N) node.N.P = node.P; + if (node.P) node.P.N = node.N; + node.N = node.P = null; + var parent = node.U, sibling, left = node.L, right = node.R, next, red; + if (!left) next = right; else if (!right) next = left; else next = d3_geom_voronoiRedBlackFirst(right); + if (parent) { + if (parent.L === node) parent.L = next; else parent.R = next; + } else { + this._ = next; + } + if (left && right) { + red = next.C; + next.C = node.C; + next.L = left; + left.U = next; + if (next !== right) { + parent = next.U; + next.U = node.U; + node = next.R; + parent.L = node; + next.R = right; + right.U = next; + } else { + next.U = parent; + parent = next; + node = next.R; + } + } else { + red = node.C; + node = next; + } + if (node) node.U = parent; + if (red) return; + if (node && node.C) { + node.C = false; + return; + } + do { + if (node === this._) break; + if (node === parent.L) { + sibling = parent.R; + if (sibling.C) { + sibling.C = false; + parent.C = true; + d3_geom_voronoiRedBlackRotateLeft(this, parent); + sibling = parent.R; + } + if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) { + if (!sibling.R || !sibling.R.C) { + sibling.L.C = false; + sibling.C = true; + d3_geom_voronoiRedBlackRotateRight(this, sibling); + sibling = parent.R; + } + sibling.C = parent.C; + parent.C = sibling.R.C = false; + d3_geom_voronoiRedBlackRotateLeft(this, parent); + node = this._; + break; + } + } else { + sibling = parent.L; + if (sibling.C) { + sibling.C = false; + parent.C = true; + d3_geom_voronoiRedBlackRotateRight(this, parent); + sibling = parent.L; + } + if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) { + if (!sibling.L || !sibling.L.C) { + sibling.R.C = false; + sibling.C = true; + d3_geom_voronoiRedBlackRotateLeft(this, sibling); + sibling = parent.L; + } + sibling.C = parent.C; + parent.C = sibling.L.C = false; + d3_geom_voronoiRedBlackRotateRight(this, parent); + node = this._; + break; + } + } + sibling.C = true; + node = parent; + parent = parent.U; + } while (!node.C); + if (node) node.C = false; + } + }; + function d3_geom_voronoiRedBlackRotateLeft(tree, node) { + var p = node, q = node.R, parent = p.U; + if (parent) { + if (parent.L === p) parent.L = q; else parent.R = q; + } else { + tree._ = q; + } + q.U = parent; + p.U = q; + p.R = q.L; + if (p.R) p.R.U = p; + q.L = p; + } + function d3_geom_voronoiRedBlackRotateRight(tree, node) { + var p = node, q = node.L, parent = p.U; + if (parent) { + if (parent.L === p) parent.L = q; else parent.R = q; + } else { + tree._ = q; + } + q.U = parent; + p.U = q; + p.L = q.R; + if (p.L) p.L.U = p; + q.R = p; + } + function d3_geom_voronoiRedBlackFirst(node) { + while (node.L) node = node.L; + return node; + } + function d3_geom_voronoi(sites, bbox) { + var site = sites.sort(d3_geom_voronoiVertexOrder).pop(), x0, y0, circle; + d3_geom_voronoiEdges = []; + d3_geom_voronoiCells = new Array(sites.length); + d3_geom_voronoiBeaches = new d3_geom_voronoiRedBlackTree(); + d3_geom_voronoiCircles = new d3_geom_voronoiRedBlackTree(); + while (true) { + circle = d3_geom_voronoiFirstCircle; + if (site && (!circle || site.y < circle.y || site.y === circle.y && site.x < circle.x)) { + if (site.x !== x0 || site.y !== y0) { + d3_geom_voronoiCells[site.i] = new d3_geom_voronoiCell(site); + d3_geom_voronoiAddBeach(site); + x0 = site.x, y0 = site.y; + } + site = sites.pop(); + } else if (circle) { + d3_geom_voronoiRemoveBeach(circle.arc); + } else { + break; + } + } + if (bbox) d3_geom_voronoiClipEdges(bbox), d3_geom_voronoiCloseCells(bbox); + var diagram = { + cells: d3_geom_voronoiCells, + edges: d3_geom_voronoiEdges + }; + d3_geom_voronoiBeaches = d3_geom_voronoiCircles = d3_geom_voronoiEdges = d3_geom_voronoiCells = null; + return diagram; + } + function d3_geom_voronoiVertexOrder(a, b) { + return b.y - a.y || b.x - a.x; + } + d3.geom.voronoi = function(points) { + var x = d3_geom_pointX, y = d3_geom_pointY, fx = x, fy = y, clipExtent = d3_geom_voronoiClipExtent; + if (points) return voronoi(points); + function voronoi(data) { + var polygons = new Array(data.length), x0 = clipExtent[0][0], y0 = clipExtent[0][1], x1 = clipExtent[1][0], y1 = clipExtent[1][1]; + d3_geom_voronoi(sites(data), clipExtent).cells.forEach(function(cell, i) { + var edges = cell.edges, site = cell.site, polygon = polygons[i] = edges.length ? edges.map(function(e) { + var s = e.start(); + return [ s.x, s.y ]; + }) : site.x >= x0 && site.x <= x1 && site.y >= y0 && site.y <= y1 ? [ [ x0, y1 ], [ x1, y1 ], [ x1, y0 ], [ x0, y0 ] ] : []; + polygon.point = data[i]; + }); + return polygons; + } + function sites(data) { + return data.map(function(d, i) { + return { + x: Math.round(fx(d, i) / ε) * ε, + y: Math.round(fy(d, i) / ε) * ε, + i: i + }; + }); + } + voronoi.links = function(data) { + return d3_geom_voronoi(sites(data)).edges.filter(function(edge) { + return edge.l && edge.r; + }).map(function(edge) { + return { + source: data[edge.l.i], + target: data[edge.r.i] + }; + }); + }; + voronoi.triangles = function(data) { + var triangles = []; + d3_geom_voronoi(sites(data)).cells.forEach(function(cell, i) { + var site = cell.site, edges = cell.edges.sort(d3_geom_voronoiHalfEdgeOrder), j = -1, m = edges.length, e0, s0, e1 = edges[m - 1].edge, s1 = e1.l === site ? e1.r : e1.l; + while (++j < m) { + e0 = e1; + s0 = s1; + e1 = edges[j].edge; + s1 = e1.l === site ? e1.r : e1.l; + if (i < s0.i && i < s1.i && d3_geom_voronoiTriangleArea(site, s0, s1) < 0) { + triangles.push([ data[i], data[s0.i], data[s1.i] ]); + } + } + }); + return triangles; + }; + voronoi.x = function(_) { + return arguments.length ? (fx = d3_functor(x = _), voronoi) : x; + }; + voronoi.y = function(_) { + return arguments.length ? (fy = d3_functor(y = _), voronoi) : y; + }; + voronoi.clipExtent = function(_) { + if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent; + clipExtent = _ == null ? d3_geom_voronoiClipExtent : _; + return voronoi; + }; + voronoi.size = function(_) { + if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent && clipExtent[1]; + return voronoi.clipExtent(_ && [ [ 0, 0 ], _ ]); + }; + return voronoi; + }; + var d3_geom_voronoiClipExtent = [ [ -1e6, -1e6 ], [ 1e6, 1e6 ] ]; + function d3_geom_voronoiTriangleArea(a, b, c) { + return (a.x - c.x) * (b.y - a.y) - (a.x - b.x) * (c.y - a.y); + } + d3.geom.delaunay = function(vertices) { + return d3.geom.voronoi().triangles(vertices); + }; + d3.geom.quadtree = function(points, x1, y1, x2, y2) { + var x = d3_geom_pointX, y = d3_geom_pointY, compat; + if (compat = arguments.length) { + x = d3_geom_quadtreeCompatX; + y = d3_geom_quadtreeCompatY; + if (compat === 3) { + y2 = y1; + x2 = x1; + y1 = x1 = 0; + } + return quadtree(points); + } + function quadtree(data) { + var d, fx = d3_functor(x), fy = d3_functor(y), xs, ys, i, n, x1_, y1_, x2_, y2_; + if (x1 != null) { + x1_ = x1, y1_ = y1, x2_ = x2, y2_ = y2; + } else { + x2_ = y2_ = -(x1_ = y1_ = Infinity); + xs = [], ys = []; + n = data.length; + if (compat) for (i = 0; i < n; ++i) { + d = data[i]; + if (d.x < x1_) x1_ = d.x; + if (d.y < y1_) y1_ = d.y; + if (d.x > x2_) x2_ = d.x; + if (d.y > y2_) y2_ = d.y; + xs.push(d.x); + ys.push(d.y); + } else for (i = 0; i < n; ++i) { + var x_ = +fx(d = data[i], i), y_ = +fy(d, i); + if (x_ < x1_) x1_ = x_; + if (y_ < y1_) y1_ = y_; + if (x_ > x2_) x2_ = x_; + if (y_ > y2_) y2_ = y_; + xs.push(x_); + ys.push(y_); + } + } + var dx = x2_ - x1_, dy = y2_ - y1_; + if (dx > dy) y2_ = y1_ + dx; else x2_ = x1_ + dy; + function insert(n, d, x, y, x1, y1, x2, y2) { + if (isNaN(x) || isNaN(y)) return; + if (n.leaf) { + var nx = n.x, ny = n.y; + if (nx != null) { + if (abs(nx - x) + abs(ny - y) < .01) { + insertChild(n, d, x, y, x1, y1, x2, y2); + } else { + var nPoint = n.point; + n.x = n.y = n.point = null; + insertChild(n, nPoint, nx, ny, x1, y1, x2, y2); + insertChild(n, d, x, y, x1, y1, x2, y2); + } + } else { + n.x = x, n.y = y, n.point = d; + } + } else { + insertChild(n, d, x, y, x1, y1, x2, y2); + } + } + function insertChild(n, d, x, y, x1, y1, x2, y2) { + var sx = (x1 + x2) * .5, sy = (y1 + y2) * .5, right = x >= sx, bottom = y >= sy, i = (bottom << 1) + right; + n.leaf = false; + n = n.nodes[i] || (n.nodes[i] = d3_geom_quadtreeNode()); + if (right) x1 = sx; else x2 = sx; + if (bottom) y1 = sy; else y2 = sy; + insert(n, d, x, y, x1, y1, x2, y2); + } + var root = d3_geom_quadtreeNode(); + root.add = function(d) { + insert(root, d, +fx(d, ++i), +fy(d, i), x1_, y1_, x2_, y2_); + }; + root.visit = function(f) { + d3_geom_quadtreeVisit(f, root, x1_, y1_, x2_, y2_); + }; + i = -1; + if (x1 == null) { + while (++i < n) { + insert(root, data[i], xs[i], ys[i], x1_, y1_, x2_, y2_); + } + --i; + } else data.forEach(root.add); + xs = ys = data = d = null; + return root; + } + quadtree.x = function(_) { + return arguments.length ? (x = _, quadtree) : x; + }; + quadtree.y = function(_) { + return arguments.length ? (y = _, quadtree) : y; + }; + quadtree.extent = function(_) { + if (!arguments.length) return x1 == null ? null : [ [ x1, y1 ], [ x2, y2 ] ]; + if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = +_[0][0], y1 = +_[0][1], x2 = +_[1][0], + y2 = +_[1][1]; + return quadtree; + }; + quadtree.size = function(_) { + if (!arguments.length) return x1 == null ? null : [ x2 - x1, y2 - y1 ]; + if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = y1 = 0, x2 = +_[0], y2 = +_[1]; + return quadtree; + }; + return quadtree; + }; + function d3_geom_quadtreeCompatX(d) { + return d.x; + } + function d3_geom_quadtreeCompatY(d) { + return d.y; + } + function d3_geom_quadtreeNode() { + return { + leaf: true, + nodes: [], + point: null, + x: null, + y: null + }; + } + function d3_geom_quadtreeVisit(f, node, x1, y1, x2, y2) { + if (!f(node, x1, y1, x2, y2)) { + var sx = (x1 + x2) * .5, sy = (y1 + y2) * .5, children = node.nodes; + if (children[0]) d3_geom_quadtreeVisit(f, children[0], x1, y1, sx, sy); + if (children[1]) d3_geom_quadtreeVisit(f, children[1], sx, y1, x2, sy); + if (children[2]) d3_geom_quadtreeVisit(f, children[2], x1, sy, sx, y2); + if (children[3]) d3_geom_quadtreeVisit(f, children[3], sx, sy, x2, y2); + } + } + d3.interpolateRgb = d3_interpolateRgb; + function d3_interpolateRgb(a, b) { + a = d3.rgb(a); + b = d3.rgb(b); + var ar = a.r, ag = a.g, ab = a.b, br = b.r - ar, bg = b.g - ag, bb = b.b - ab; + return function(t) { + return "#" + d3_rgb_hex(Math.round(ar + br * t)) + d3_rgb_hex(Math.round(ag + bg * t)) + d3_rgb_hex(Math.round(ab + bb * t)); + }; + } + d3.interpolateObject = d3_interpolateObject; + function d3_interpolateObject(a, b) { + var i = {}, c = {}, k; + for (k in a) { + if (k in b) { + i[k] = d3_interpolate(a[k], b[k]); + } else { + c[k] = a[k]; + } + } + for (k in b) { + if (!(k in a)) { + c[k] = b[k]; + } + } + return function(t) { + for (k in i) c[k] = i[k](t); + return c; + }; + } + d3.interpolateNumber = d3_interpolateNumber; + function d3_interpolateNumber(a, b) { + b -= a = +a; + return function(t) { + return a + b * t; + }; + } + d3.interpolateString = d3_interpolateString; + function d3_interpolateString(a, b) { + var m, i, j, s0 = 0, s1 = 0, s = [], q = [], n, o; + a = a + "", b = b + ""; + d3_interpolate_number.lastIndex = 0; + for (i = 0; m = d3_interpolate_number.exec(b); ++i) { + if (m.index) s.push(b.substring(s0, s1 = m.index)); + q.push({ + i: s.length, + x: m[0] + }); + s.push(null); + s0 = d3_interpolate_number.lastIndex; + } + if (s0 < b.length) s.push(b.substring(s0)); + for (i = 0, n = q.length; (m = d3_interpolate_number.exec(a)) && i < n; ++i) { + o = q[i]; + if (o.x == m[0]) { + if (o.i) { + if (s[o.i + 1] == null) { + s[o.i - 1] += o.x; + s.splice(o.i, 1); + for (j = i + 1; j < n; ++j) q[j].i--; + } else { + s[o.i - 1] += o.x + s[o.i + 1]; + s.splice(o.i, 2); + for (j = i + 1; j < n; ++j) q[j].i -= 2; + } + } else { + if (s[o.i + 1] == null) { + s[o.i] = o.x; + } else { + s[o.i] = o.x + s[o.i + 1]; + s.splice(o.i + 1, 1); + for (j = i + 1; j < n; ++j) q[j].i--; + } + } + q.splice(i, 1); + n--; + i--; + } else { + o.x = d3_interpolateNumber(parseFloat(m[0]), parseFloat(o.x)); + } + } + while (i < n) { + o = q.pop(); + if (s[o.i + 1] == null) { + s[o.i] = o.x; + } else { + s[o.i] = o.x + s[o.i + 1]; + s.splice(o.i + 1, 1); + } + n--; + } + if (s.length === 1) { + return s[0] == null ? (o = q[0].x, function(t) { + return o(t) + ""; + }) : function() { + return b; + }; + } + return function(t) { + for (i = 0; i < n; ++i) s[(o = q[i]).i] = o.x(t); + return s.join(""); + }; + } + var d3_interpolate_number = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g; + d3.interpolate = d3_interpolate; + function d3_interpolate(a, b) { + var i = d3.interpolators.length, f; + while (--i >= 0 && !(f = d3.interpolators[i](a, b))) ; + return f; + } + d3.interpolators = [ function(a, b) { + var t = typeof b; + return (t === "string" ? d3_rgb_names.has(b) || /^(#|rgb\(|hsl\()/.test(b) ? d3_interpolateRgb : d3_interpolateString : b instanceof d3_Color ? d3_interpolateRgb : t === "object" ? Array.isArray(b) ? d3_interpolateArray : d3_interpolateObject : d3_interpolateNumber)(a, b); + } ]; + d3.interpolateArray = d3_interpolateArray; + function d3_interpolateArray(a, b) { + var x = [], c = [], na = a.length, nb = b.length, n0 = Math.min(a.length, b.length), i; + for (i = 0; i < n0; ++i) x.push(d3_interpolate(a[i], b[i])); + for (;i < na; ++i) c[i] = a[i]; + for (;i < nb; ++i) c[i] = b[i]; + return function(t) { + for (i = 0; i < n0; ++i) c[i] = x[i](t); + return c; + }; + } + var d3_ease_default = function() { + return d3_identity; + }; + var d3_ease = d3.map({ + linear: d3_ease_default, + poly: d3_ease_poly, + quad: function() { + return d3_ease_quad; + }, + cubic: function() { + return d3_ease_cubic; + }, + sin: function() { + return d3_ease_sin; + }, + exp: function() { + return d3_ease_exp; + }, + circle: function() { + return d3_ease_circle; + }, + elastic: d3_ease_elastic, + back: d3_ease_back, + bounce: function() { + return d3_ease_bounce; + } + }); + var d3_ease_mode = d3.map({ + "in": d3_identity, + out: d3_ease_reverse, + "in-out": d3_ease_reflect, + "out-in": function(f) { + return d3_ease_reflect(d3_ease_reverse(f)); + } + }); + d3.ease = function(name) { + var i = name.indexOf("-"), t = i >= 0 ? name.substring(0, i) : name, m = i >= 0 ? name.substring(i + 1) : "in"; + t = d3_ease.get(t) || d3_ease_default; + m = d3_ease_mode.get(m) || d3_identity; + return d3_ease_clamp(m(t.apply(null, d3_arraySlice.call(arguments, 1)))); + }; + function d3_ease_clamp(f) { + return function(t) { + return t <= 0 ? 0 : t >= 1 ? 1 : f(t); + }; + } + function d3_ease_reverse(f) { + return function(t) { + return 1 - f(1 - t); + }; + } + function d3_ease_reflect(f) { + return function(t) { + return .5 * (t < .5 ? f(2 * t) : 2 - f(2 - 2 * t)); + }; + } + function d3_ease_quad(t) { + return t * t; + } + function d3_ease_cubic(t) { + return t * t * t; + } + function d3_ease_cubicInOut(t) { + if (t <= 0) return 0; + if (t >= 1) return 1; + var t2 = t * t, t3 = t2 * t; + return 4 * (t < .5 ? t3 : 3 * (t - t2) + t3 - .75); + } + function d3_ease_poly(e) { + return function(t) { + return Math.pow(t, e); + }; + } + function d3_ease_sin(t) { + return 1 - Math.cos(t * halfπ); + } + function d3_ease_exp(t) { + return Math.pow(2, 10 * (t - 1)); + } + function d3_ease_circle(t) { + return 1 - Math.sqrt(1 - t * t); + } + function d3_ease_elastic(a, p) { + var s; + if (arguments.length < 2) p = .45; + if (arguments.length) s = p / τ * Math.asin(1 / a); else a = 1, s = p / 4; + return function(t) { + return 1 + a * Math.pow(2, -10 * t) * Math.sin((t - s) * τ / p); + }; + } + function d3_ease_back(s) { + if (!s) s = 1.70158; + return function(t) { + return t * t * ((s + 1) * t - s); + }; + } + function d3_ease_bounce(t) { + return t < 1 / 2.75 ? 7.5625 * t * t : t < 2 / 2.75 ? 7.5625 * (t -= 1.5 / 2.75) * t + .75 : t < 2.5 / 2.75 ? 7.5625 * (t -= 2.25 / 2.75) * t + .9375 : 7.5625 * (t -= 2.625 / 2.75) * t + .984375; + } + d3.interpolateHcl = d3_interpolateHcl; + function d3_interpolateHcl(a, b) { + a = d3.hcl(a); + b = d3.hcl(b); + var ah = a.h, ac = a.c, al = a.l, bh = b.h - ah, bc = b.c - ac, bl = b.l - al; + if (isNaN(bc)) bc = 0, ac = isNaN(ac) ? b.c : ac; + if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; else if (bh > 180) bh -= 360; else if (bh < -180) bh += 360; + return function(t) { + return d3_hcl_lab(ah + bh * t, ac + bc * t, al + bl * t) + ""; + }; + } + d3.interpolateHsl = d3_interpolateHsl; + function d3_interpolateHsl(a, b) { + a = d3.hsl(a); + b = d3.hsl(b); + var ah = a.h, as = a.s, al = a.l, bh = b.h - ah, bs = b.s - as, bl = b.l - al; + if (isNaN(bs)) bs = 0, as = isNaN(as) ? b.s : as; + if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; else if (bh > 180) bh -= 360; else if (bh < -180) bh += 360; + return function(t) { + return d3_hsl_rgb(ah + bh * t, as + bs * t, al + bl * t) + ""; + }; + } + d3.interpolateLab = d3_interpolateLab; + function d3_interpolateLab(a, b) { + a = d3.lab(a); + b = d3.lab(b); + var al = a.l, aa = a.a, ab = a.b, bl = b.l - al, ba = b.a - aa, bb = b.b - ab; + return function(t) { + return d3_lab_rgb(al + bl * t, aa + ba * t, ab + bb * t) + ""; + }; + } + d3.interpolateRound = d3_interpolateRound; + function d3_interpolateRound(a, b) { + b -= a; + return function(t) { + return Math.round(a + b * t); + }; + } + d3.transform = function(string) { + var g = d3_document.createElementNS(d3.ns.prefix.svg, "g"); + return (d3.transform = function(string) { + if (string != null) { + g.setAttribute("transform", string); + var t = g.transform.baseVal.consolidate(); + } + return new d3_transform(t ? t.matrix : d3_transformIdentity); + })(string); + }; + function d3_transform(m) { + var r0 = [ m.a, m.b ], r1 = [ m.c, m.d ], kx = d3_transformNormalize(r0), kz = d3_transformDot(r0, r1), ky = d3_transformNormalize(d3_transformCombine(r1, r0, -kz)) || 0; + if (r0[0] * r1[1] < r1[0] * r0[1]) { + r0[0] *= -1; + r0[1] *= -1; + kx *= -1; + kz *= -1; + } + this.rotate = (kx ? Math.atan2(r0[1], r0[0]) : Math.atan2(-r1[0], r1[1])) * d3_degrees; + this.translate = [ m.e, m.f ]; + this.scale = [ kx, ky ]; + this.skew = ky ? Math.atan2(kz, ky) * d3_degrees : 0; + } + d3_transform.prototype.toString = function() { + return "translate(" + this.translate + ")rotate(" + this.rotate + ")skewX(" + this.skew + ")scale(" + this.scale + ")"; + }; + function d3_transformDot(a, b) { + return a[0] * b[0] + a[1] * b[1]; + } + function d3_transformNormalize(a) { + var k = Math.sqrt(d3_transformDot(a, a)); + if (k) { + a[0] /= k; + a[1] /= k; + } + return k; + } + function d3_transformCombine(a, b, k) { + a[0] += k * b[0]; + a[1] += k * b[1]; + return a; + } + var d3_transformIdentity = { + a: 1, + b: 0, + c: 0, + d: 1, + e: 0, + f: 0 + }; + d3.interpolateTransform = d3_interpolateTransform; + function d3_interpolateTransform(a, b) { + var s = [], q = [], n, A = d3.transform(a), B = d3.transform(b), ta = A.translate, tb = B.translate, ra = A.rotate, rb = B.rotate, wa = A.skew, wb = B.skew, ka = A.scale, kb = B.scale; + if (ta[0] != tb[0] || ta[1] != tb[1]) { + s.push("translate(", null, ",", null, ")"); + q.push({ + i: 1, + x: d3_interpolateNumber(ta[0], tb[0]) + }, { + i: 3, + x: d3_interpolateNumber(ta[1], tb[1]) + }); + } else if (tb[0] || tb[1]) { + s.push("translate(" + tb + ")"); + } else { + s.push(""); + } + if (ra != rb) { + if (ra - rb > 180) rb += 360; else if (rb - ra > 180) ra += 360; + q.push({ + i: s.push(s.pop() + "rotate(", null, ")") - 2, + x: d3_interpolateNumber(ra, rb) + }); + } else if (rb) { + s.push(s.pop() + "rotate(" + rb + ")"); + } + if (wa != wb) { + q.push({ + i: s.push(s.pop() + "skewX(", null, ")") - 2, + x: d3_interpolateNumber(wa, wb) + }); + } else if (wb) { + s.push(s.pop() + "skewX(" + wb + ")"); + } + if (ka[0] != kb[0] || ka[1] != kb[1]) { + n = s.push(s.pop() + "scale(", null, ",", null, ")"); + q.push({ + i: n - 4, + x: d3_interpolateNumber(ka[0], kb[0]) + }, { + i: n - 2, + x: d3_interpolateNumber(ka[1], kb[1]) + }); + } else if (kb[0] != 1 || kb[1] != 1) { + s.push(s.pop() + "scale(" + kb + ")"); + } + n = q.length; + return function(t) { + var i = -1, o; + while (++i < n) s[(o = q[i]).i] = o.x(t); + return s.join(""); + }; + } + function d3_uninterpolateNumber(a, b) { + b = b - (a = +a) ? 1 / (b - a) : 0; + return function(x) { + return (x - a) * b; + }; + } + function d3_uninterpolateClamp(a, b) { + b = b - (a = +a) ? 1 / (b - a) : 0; + return function(x) { + return Math.max(0, Math.min(1, (x - a) * b)); + }; + } + d3.layout = {}; + d3.layout.bundle = function() { + return function(links) { + var paths = [], i = -1, n = links.length; + while (++i < n) paths.push(d3_layout_bundlePath(links[i])); + return paths; + }; + }; + function d3_layout_bundlePath(link) { + var start = link.source, end = link.target, lca = d3_layout_bundleLeastCommonAncestor(start, end), points = [ start ]; + while (start !== lca) { + start = start.parent; + points.push(start); + } + var k = points.length; + while (end !== lca) { + points.splice(k, 0, end); + end = end.parent; + } + return points; + } + function d3_layout_bundleAncestors(node) { + var ancestors = [], parent = node.parent; + while (parent != null) { + ancestors.push(node); + node = parent; + parent = parent.parent; + } + ancestors.push(node); + return ancestors; + } + function d3_layout_bundleLeastCommonAncestor(a, b) { + if (a === b) return a; + var aNodes = d3_layout_bundleAncestors(a), bNodes = d3_layout_bundleAncestors(b), aNode = aNodes.pop(), bNode = bNodes.pop(), sharedNode = null; + while (aNode === bNode) { + sharedNode = aNode; + aNode = aNodes.pop(); + bNode = bNodes.pop(); + } + return sharedNode; + } + d3.layout.chord = function() { + var chord = {}, chords, groups, matrix, n, padding = 0, sortGroups, sortSubgroups, sortChords; + function relayout() { + var subgroups = {}, groupSums = [], groupIndex = d3.range(n), subgroupIndex = [], k, x, x0, i, j; + chords = []; + groups = []; + k = 0, i = -1; + while (++i < n) { + x = 0, j = -1; + while (++j < n) { + x += matrix[i][j]; + } + groupSums.push(x); + subgroupIndex.push(d3.range(n)); + k += x; + } + if (sortGroups) { + groupIndex.sort(function(a, b) { + return sortGroups(groupSums[a], groupSums[b]); + }); + } + if (sortSubgroups) { + subgroupIndex.forEach(function(d, i) { + d.sort(function(a, b) { + return sortSubgroups(matrix[i][a], matrix[i][b]); + }); + }); + } + k = (τ - padding * n) / k; + x = 0, i = -1; + while (++i < n) { + x0 = x, j = -1; + while (++j < n) { + var di = groupIndex[i], dj = subgroupIndex[di][j], v = matrix[di][dj], a0 = x, a1 = x += v * k; + subgroups[di + "-" + dj] = { + index: di, + subindex: dj, + startAngle: a0, + endAngle: a1, + value: v + }; + } + groups[di] = { + index: di, + startAngle: x0, + endAngle: x, + value: (x - x0) / k + }; + x += padding; + } + i = -1; + while (++i < n) { + j = i - 1; + while (++j < n) { + var source = subgroups[i + "-" + j], target = subgroups[j + "-" + i]; + if (source.value || target.value) { + chords.push(source.value < target.value ? { + source: target, + target: source + } : { + source: source, + target: target + }); + } + } + } + if (sortChords) resort(); + } + function resort() { + chords.sort(function(a, b) { + return sortChords((a.source.value + a.target.value) / 2, (b.source.value + b.target.value) / 2); + }); + } + chord.matrix = function(x) { + if (!arguments.length) return matrix; + n = (matrix = x) && matrix.length; + chords = groups = null; + return chord; + }; + chord.padding = function(x) { + if (!arguments.length) return padding; + padding = x; + chords = groups = null; + return chord; + }; + chord.sortGroups = function(x) { + if (!arguments.length) return sortGroups; + sortGroups = x; + chords = groups = null; + return chord; + }; + chord.sortSubgroups = function(x) { + if (!arguments.length) return sortSubgroups; + sortSubgroups = x; + chords = null; + return chord; + }; + chord.sortChords = function(x) { + if (!arguments.length) return sortChords; + sortChords = x; + if (chords) resort(); + return chord; + }; + chord.chords = function() { + if (!chords) relayout(); + return chords; + }; + chord.groups = function() { + if (!groups) relayout(); + return groups; + }; + return chord; + }; + d3.layout.force = function() { + var force = {}, event = d3.dispatch("start", "tick", "end"), size = [ 1, 1 ], drag, alpha, friction = .9, linkDistance = d3_layout_forceLinkDistance, linkStrength = d3_layout_forceLinkStrength, charge = -30, chargeDistance2 = d3_layout_forceChargeDistance2, gravity = .1, theta2 = .64, nodes = [], links = [], distances, strengths, charges; + function repulse(node) { + return function(quad, x1, _, x2) { + if (quad.point !== node) { + var dx = quad.cx - node.x, dy = quad.cy - node.y, dw = x2 - x1, dn = dx * dx + dy * dy; + if (dw * dw / theta2 < dn) { + if (dn < chargeDistance2) { + var k = quad.charge / dn; + node.px -= dx * k; + node.py -= dy * k; + } + return true; + } + if (quad.point && dn && dn < chargeDistance2) { + var k = quad.pointCharge / dn; + node.px -= dx * k; + node.py -= dy * k; + } + } + return !quad.charge; + }; + } + force.tick = function() { + if ((alpha *= .99) < .005) { + event.end({ + type: "end", + alpha: alpha = 0 + }); + return true; + } + var n = nodes.length, m = links.length, q, i, o, s, t, l, k, x, y; + for (i = 0; i < m; ++i) { + o = links[i]; + s = o.source; + t = o.target; + x = t.x - s.x; + y = t.y - s.y; + if (l = x * x + y * y) { + l = alpha * strengths[i] * ((l = Math.sqrt(l)) - distances[i]) / l; + x *= l; + y *= l; + t.x -= x * (k = s.weight / (t.weight + s.weight)); + t.y -= y * k; + s.x += x * (k = 1 - k); + s.y += y * k; + } + } + if (k = alpha * gravity) { + x = size[0] / 2; + y = size[1] / 2; + i = -1; + if (k) while (++i < n) { + o = nodes[i]; + o.x += (x - o.x) * k; + o.y += (y - o.y) * k; + } + } + if (charge) { + d3_layout_forceAccumulate(q = d3.geom.quadtree(nodes), alpha, charges); + i = -1; + while (++i < n) { + if (!(o = nodes[i]).fixed) { + q.visit(repulse(o)); + } + } + } + i = -1; + while (++i < n) { + o = nodes[i]; + if (o.fixed) { + o.x = o.px; + o.y = o.py; + } else { + o.x -= (o.px - (o.px = o.x)) * friction; + o.y -= (o.py - (o.py = o.y)) * friction; + } + } + event.tick({ + type: "tick", + alpha: alpha + }); + }; + force.nodes = function(x) { + if (!arguments.length) return nodes; + nodes = x; + return force; + }; + force.links = function(x) { + if (!arguments.length) return links; + links = x; + return force; + }; + force.size = function(x) { + if (!arguments.length) return size; + size = x; + return force; + }; + force.linkDistance = function(x) { + if (!arguments.length) return linkDistance; + linkDistance = typeof x === "function" ? x : +x; + return force; + }; + force.distance = force.linkDistance; + force.linkStrength = function(x) { + if (!arguments.length) return linkStrength; + linkStrength = typeof x === "function" ? x : +x; + return force; + }; + force.friction = function(x) { + if (!arguments.length) return friction; + friction = +x; + return force; + }; + force.charge = function(x) { + if (!arguments.length) return charge; + charge = typeof x === "function" ? x : +x; + return force; + }; + force.chargeDistance = function(x) { + if (!arguments.length) return Math.sqrt(chargeDistance2); + chargeDistance2 = x * x; + return force; + }; + force.gravity = function(x) { + if (!arguments.length) return gravity; + gravity = +x; + return force; + }; + force.theta = function(x) { + if (!arguments.length) return Math.sqrt(theta2); + theta2 = x * x; + return force; + }; + force.alpha = function(x) { + if (!arguments.length) return alpha; + x = +x; + if (alpha) { + if (x > 0) alpha = x; else alpha = 0; + } else if (x > 0) { + event.start({ + type: "start", + alpha: alpha = x + }); + d3.timer(force.tick); + } + return force; + }; + force.start = function() { + var i, n = nodes.length, m = links.length, w = size[0], h = size[1], neighbors, o; + for (i = 0; i < n; ++i) { + (o = nodes[i]).index = i; + o.weight = 0; + } + for (i = 0; i < m; ++i) { + o = links[i]; + if (typeof o.source == "number") o.source = nodes[o.source]; + if (typeof o.target == "number") o.target = nodes[o.target]; + ++o.source.weight; + ++o.target.weight; + } + for (i = 0; i < n; ++i) { + o = nodes[i]; + if (isNaN(o.x)) o.x = position("x", w); + if (isNaN(o.y)) o.y = position("y", h); + if (isNaN(o.px)) o.px = o.x; + if (isNaN(o.py)) o.py = o.y; + } + distances = []; + if (typeof linkDistance === "function") for (i = 0; i < m; ++i) distances[i] = +linkDistance.call(this, links[i], i); else for (i = 0; i < m; ++i) distances[i] = linkDistance; + strengths = []; + if (typeof linkStrength === "function") for (i = 0; i < m; ++i) strengths[i] = +linkStrength.call(this, links[i], i); else for (i = 0; i < m; ++i) strengths[i] = linkStrength; + charges = []; + if (typeof charge === "function") for (i = 0; i < n; ++i) charges[i] = +charge.call(this, nodes[i], i); else for (i = 0; i < n; ++i) charges[i] = charge; + function position(dimension, size) { + if (!neighbors) { + neighbors = new Array(n); + for (j = 0; j < n; ++j) { + neighbors[j] = []; + } + for (j = 0; j < m; ++j) { + var o = links[j]; + neighbors[o.source.index].push(o.target); + neighbors[o.target.index].push(o.source); + } + } + var candidates = neighbors[i], j = -1, m = candidates.length, x; + while (++j < m) if (!isNaN(x = candidates[j][dimension])) return x; + return Math.random() * size; + } + return force.resume(); + }; + force.resume = function() { + return force.alpha(.1); + }; + force.stop = function() { + return force.alpha(0); + }; + force.drag = function() { + if (!drag) drag = d3.behavior.drag().origin(d3_identity).on("dragstart.force", d3_layout_forceDragstart).on("drag.force", dragmove).on("dragend.force", d3_layout_forceDragend); + if (!arguments.length) return drag; + this.on("mouseover.force", d3_layout_forceMouseover).on("mouseout.force", d3_layout_forceMouseout).call(drag); + }; + function dragmove(d) { + d.px = d3.event.x, d.py = d3.event.y; + force.resume(); + } + return d3.rebind(force, event, "on"); + }; + function d3_layout_forceDragstart(d) { + d.fixed |= 2; + } + function d3_layout_forceDragend(d) { + d.fixed &= ~6; + } + function d3_layout_forceMouseover(d) { + d.fixed |= 4; + d.px = d.x, d.py = d.y; + } + function d3_layout_forceMouseout(d) { + d.fixed &= ~4; + } + function d3_layout_forceAccumulate(quad, alpha, charges) { + var cx = 0, cy = 0; + quad.charge = 0; + if (!quad.leaf) { + var nodes = quad.nodes, n = nodes.length, i = -1, c; + while (++i < n) { + c = nodes[i]; + if (c == null) continue; + d3_layout_forceAccumulate(c, alpha, charges); + quad.charge += c.charge; + cx += c.charge * c.cx; + cy += c.charge * c.cy; + } + } + if (quad.point) { + if (!quad.leaf) { + quad.point.x += Math.random() - .5; + quad.point.y += Math.random() - .5; + } + var k = alpha * charges[quad.point.index]; + quad.charge += quad.pointCharge = k; + cx += k * quad.point.x; + cy += k * quad.point.y; + } + quad.cx = cx / quad.charge; + quad.cy = cy / quad.charge; + } + var d3_layout_forceLinkDistance = 20, d3_layout_forceLinkStrength = 1, d3_layout_forceChargeDistance2 = Infinity; + d3.layout.hierarchy = function() { + var sort = d3_layout_hierarchySort, children = d3_layout_hierarchyChildren, value = d3_layout_hierarchyValue; + function recurse(node, depth, nodes) { + var childs = children.call(hierarchy, node, depth); + node.depth = depth; + nodes.push(node); + if (childs && (n = childs.length)) { + var i = -1, n, c = node.children = new Array(n), v = 0, j = depth + 1, d; + while (++i < n) { + d = c[i] = recurse(childs[i], j, nodes); + d.parent = node; + v += d.value; + } + if (sort) c.sort(sort); + if (value) node.value = v; + } else { + delete node.children; + if (value) { + node.value = +value.call(hierarchy, node, depth) || 0; + } + } + return node; + } + function revalue(node, depth) { + var children = node.children, v = 0; + if (children && (n = children.length)) { + var i = -1, n, j = depth + 1; + while (++i < n) v += revalue(children[i], j); + } else if (value) { + v = +value.call(hierarchy, node, depth) || 0; + } + if (value) node.value = v; + return v; + } + function hierarchy(d) { + var nodes = []; + recurse(d, 0, nodes); + return nodes; + } + hierarchy.sort = function(x) { + if (!arguments.length) return sort; + sort = x; + return hierarchy; + }; + hierarchy.children = function(x) { + if (!arguments.length) return children; + children = x; + return hierarchy; + }; + hierarchy.value = function(x) { + if (!arguments.length) return value; + value = x; + return hierarchy; + }; + hierarchy.revalue = function(root) { + revalue(root, 0); + return root; + }; + return hierarchy; + }; + function d3_layout_hierarchyRebind(object, hierarchy) { + d3.rebind(object, hierarchy, "sort", "children", "value"); + object.nodes = object; + object.links = d3_layout_hierarchyLinks; + return object; + } + function d3_layout_hierarchyChildren(d) { + return d.children; + } + function d3_layout_hierarchyValue(d) { + return d.value; + } + function d3_layout_hierarchySort(a, b) { + return b.value - a.value; + } + function d3_layout_hierarchyLinks(nodes) { + return d3.merge(nodes.map(function(parent) { + return (parent.children || []).map(function(child) { + return { + source: parent, + target: child + }; + }); + })); + } + d3.layout.partition = function() { + var hierarchy = d3.layout.hierarchy(), size = [ 1, 1 ]; + function position(node, x, dx, dy) { + var children = node.children; + node.x = x; + node.y = node.depth * dy; + node.dx = dx; + node.dy = dy; + if (children && (n = children.length)) { + var i = -1, n, c, d; + dx = node.value ? dx / node.value : 0; + while (++i < n) { + position(c = children[i], x, d = c.value * dx, dy); + x += d; + } + } + } + function depth(node) { + var children = node.children, d = 0; + if (children && (n = children.length)) { + var i = -1, n; + while (++i < n) d = Math.max(d, depth(children[i])); + } + return 1 + d; + } + function partition(d, i) { + var nodes = hierarchy.call(this, d, i); + position(nodes[0], 0, size[0], size[1] / depth(nodes[0])); + return nodes; + } + partition.size = function(x) { + if (!arguments.length) return size; + size = x; + return partition; + }; + return d3_layout_hierarchyRebind(partition, hierarchy); + }; + d3.layout.pie = function() { + var value = Number, sort = d3_layout_pieSortByValue, startAngle = 0, endAngle = τ; + function pie(data) { + var values = data.map(function(d, i) { + return +value.call(pie, d, i); + }); + var a = +(typeof startAngle === "function" ? startAngle.apply(this, arguments) : startAngle); + var k = ((typeof endAngle === "function" ? endAngle.apply(this, arguments) : endAngle) - a) / d3.sum(values); + var index = d3.range(data.length); + if (sort != null) index.sort(sort === d3_layout_pieSortByValue ? function(i, j) { + return values[j] - values[i]; + } : function(i, j) { + return sort(data[i], data[j]); + }); + var arcs = []; + index.forEach(function(i) { + var d; + arcs[i] = { + data: data[i], + value: d = values[i], + startAngle: a, + endAngle: a += d * k + }; + }); + return arcs; + } + pie.value = function(x) { + if (!arguments.length) return value; + value = x; + return pie; + }; + pie.sort = function(x) { + if (!arguments.length) return sort; + sort = x; + return pie; + }; + pie.startAngle = function(x) { + if (!arguments.length) return startAngle; + startAngle = x; + return pie; + }; + pie.endAngle = function(x) { + if (!arguments.length) return endAngle; + endAngle = x; + return pie; + }; + return pie; + }; + var d3_layout_pieSortByValue = {}; + d3.layout.stack = function() { + var values = d3_identity, order = d3_layout_stackOrderDefault, offset = d3_layout_stackOffsetZero, out = d3_layout_stackOut, x = d3_layout_stackX, y = d3_layout_stackY; + function stack(data, index) { + var series = data.map(function(d, i) { + return values.call(stack, d, i); + }); + var points = series.map(function(d) { + return d.map(function(v, i) { + return [ x.call(stack, v, i), y.call(stack, v, i) ]; + }); + }); + var orders = order.call(stack, points, index); + series = d3.permute(series, orders); + points = d3.permute(points, orders); + var offsets = offset.call(stack, points, index); + var n = series.length, m = series[0].length, i, j, o; + for (j = 0; j < m; ++j) { + out.call(stack, series[0][j], o = offsets[j], points[0][j][1]); + for (i = 1; i < n; ++i) { + out.call(stack, series[i][j], o += points[i - 1][j][1], points[i][j][1]); + } + } + return data; + } + stack.values = function(x) { + if (!arguments.length) return values; + values = x; + return stack; + }; + stack.order = function(x) { + if (!arguments.length) return order; + order = typeof x === "function" ? x : d3_layout_stackOrders.get(x) || d3_layout_stackOrderDefault; + return stack; + }; + stack.offset = function(x) { + if (!arguments.length) return offset; + offset = typeof x === "function" ? x : d3_layout_stackOffsets.get(x) || d3_layout_stackOffsetZero; + return stack; + }; + stack.x = function(z) { + if (!arguments.length) return x; + x = z; + return stack; + }; + stack.y = function(z) { + if (!arguments.length) return y; + y = z; + return stack; + }; + stack.out = function(z) { + if (!arguments.length) return out; + out = z; + return stack; + }; + return stack; + }; + function d3_layout_stackX(d) { + return d.x; + } + function d3_layout_stackY(d) { + return d.y; + } + function d3_layout_stackOut(d, y0, y) { + d.y0 = y0; + d.y = y; + } + var d3_layout_stackOrders = d3.map({ + "inside-out": function(data) { + var n = data.length, i, j, max = data.map(d3_layout_stackMaxIndex), sums = data.map(d3_layout_stackReduceSum), index = d3.range(n).sort(function(a, b) { + return max[a] - max[b]; + }), top = 0, bottom = 0, tops = [], bottoms = []; + for (i = 0; i < n; ++i) { + j = index[i]; + if (top < bottom) { + top += sums[j]; + tops.push(j); + } else { + bottom += sums[j]; + bottoms.push(j); + } + } + return bottoms.reverse().concat(tops); + }, + reverse: function(data) { + return d3.range(data.length).reverse(); + }, + "default": d3_layout_stackOrderDefault + }); + var d3_layout_stackOffsets = d3.map({ + silhouette: function(data) { + var n = data.length, m = data[0].length, sums = [], max = 0, i, j, o, y0 = []; + for (j = 0; j < m; ++j) { + for (i = 0, o = 0; i < n; i++) o += data[i][j][1]; + if (o > max) max = o; + sums.push(o); + } + for (j = 0; j < m; ++j) { + y0[j] = (max - sums[j]) / 2; + } + return y0; + }, + wiggle: function(data) { + var n = data.length, x = data[0], m = x.length, i, j, k, s1, s2, s3, dx, o, o0, y0 = []; + y0[0] = o = o0 = 0; + for (j = 1; j < m; ++j) { + for (i = 0, s1 = 0; i < n; ++i) s1 += data[i][j][1]; + for (i = 0, s2 = 0, dx = x[j][0] - x[j - 1][0]; i < n; ++i) { + for (k = 0, s3 = (data[i][j][1] - data[i][j - 1][1]) / (2 * dx); k < i; ++k) { + s3 += (data[k][j][1] - data[k][j - 1][1]) / dx; + } + s2 += s3 * data[i][j][1]; + } + y0[j] = o -= s1 ? s2 / s1 * dx : 0; + if (o < o0) o0 = o; + } + for (j = 0; j < m; ++j) y0[j] -= o0; + return y0; + }, + expand: function(data) { + var n = data.length, m = data[0].length, k = 1 / n, i, j, o, y0 = []; + for (j = 0; j < m; ++j) { + for (i = 0, o = 0; i < n; i++) o += data[i][j][1]; + if (o) for (i = 0; i < n; i++) data[i][j][1] /= o; else for (i = 0; i < n; i++) data[i][j][1] = k; + } + for (j = 0; j < m; ++j) y0[j] = 0; + return y0; + }, + zero: d3_layout_stackOffsetZero + }); + function d3_layout_stackOrderDefault(data) { + return d3.range(data.length); + } + function d3_layout_stackOffsetZero(data) { + var j = -1, m = data[0].length, y0 = []; + while (++j < m) y0[j] = 0; + return y0; + } + function d3_layout_stackMaxIndex(array) { + var i = 1, j = 0, v = array[0][1], k, n = array.length; + for (;i < n; ++i) { + if ((k = array[i][1]) > v) { + j = i; + v = k; + } + } + return j; + } + function d3_layout_stackReduceSum(d) { + return d.reduce(d3_layout_stackSum, 0); + } + function d3_layout_stackSum(p, d) { + return p + d[1]; + } + d3.layout.histogram = function() { + var frequency = true, valuer = Number, ranger = d3_layout_histogramRange, binner = d3_layout_histogramBinSturges; + function histogram(data, i) { + var bins = [], values = data.map(valuer, this), range = ranger.call(this, values, i), thresholds = binner.call(this, range, values, i), bin, i = -1, n = values.length, m = thresholds.length - 1, k = frequency ? 1 : 1 / n, x; + while (++i < m) { + bin = bins[i] = []; + bin.dx = thresholds[i + 1] - (bin.x = thresholds[i]); + bin.y = 0; + } + if (m > 0) { + i = -1; + while (++i < n) { + x = values[i]; + if (x >= range[0] && x <= range[1]) { + bin = bins[d3.bisect(thresholds, x, 1, m) - 1]; + bin.y += k; + bin.push(data[i]); + } + } + } + return bins; + } + histogram.value = function(x) { + if (!arguments.length) return valuer; + valuer = x; + return histogram; + }; + histogram.range = function(x) { + if (!arguments.length) return ranger; + ranger = d3_functor(x); + return histogram; + }; + histogram.bins = function(x) { + if (!arguments.length) return binner; + binner = typeof x === "number" ? function(range) { + return d3_layout_histogramBinFixed(range, x); + } : d3_functor(x); + return histogram; + }; + histogram.frequency = function(x) { + if (!arguments.length) return frequency; + frequency = !!x; + return histogram; + }; + return histogram; + }; + function d3_layout_histogramBinSturges(range, values) { + return d3_layout_histogramBinFixed(range, Math.ceil(Math.log(values.length) / Math.LN2 + 1)); + } + function d3_layout_histogramBinFixed(range, n) { + var x = -1, b = +range[0], m = (range[1] - b) / n, f = []; + while (++x <= n) f[x] = m * x + b; + return f; + } + function d3_layout_histogramRange(values) { + return [ d3.min(values), d3.max(values) ]; + } + d3.layout.tree = function() { + var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = false; + function tree(d, i) { + var nodes = hierarchy.call(this, d, i), root = nodes[0]; + function firstWalk(node, previousSibling) { + var children = node.children, layout = node._tree; + if (children && (n = children.length)) { + var n, firstChild = children[0], previousChild, ancestor = firstChild, child, i = -1; + while (++i < n) { + child = children[i]; + firstWalk(child, previousChild); + ancestor = apportion(child, previousChild, ancestor); + previousChild = child; + } + d3_layout_treeShift(node); + var midpoint = .5 * (firstChild._tree.prelim + child._tree.prelim); + if (previousSibling) { + layout.prelim = previousSibling._tree.prelim + separation(node, previousSibling); + layout.mod = layout.prelim - midpoint; + } else { + layout.prelim = midpoint; + } + } else { + if (previousSibling) { + layout.prelim = previousSibling._tree.prelim + separation(node, previousSibling); + } + } + } + function secondWalk(node, x) { + node.x = node._tree.prelim + x; + var children = node.children; + if (children && (n = children.length)) { + var i = -1, n; + x += node._tree.mod; + while (++i < n) { + secondWalk(children[i], x); + } + } + } + function apportion(node, previousSibling, ancestor) { + if (previousSibling) { + var vip = node, vop = node, vim = previousSibling, vom = node.parent.children[0], sip = vip._tree.mod, sop = vop._tree.mod, sim = vim._tree.mod, som = vom._tree.mod, shift; + while (vim = d3_layout_treeRight(vim), vip = d3_layout_treeLeft(vip), vim && vip) { + vom = d3_layout_treeLeft(vom); + vop = d3_layout_treeRight(vop); + vop._tree.ancestor = node; + shift = vim._tree.prelim + sim - vip._tree.prelim - sip + separation(vim, vip); + if (shift > 0) { + d3_layout_treeMove(d3_layout_treeAncestor(vim, node, ancestor), node, shift); + sip += shift; + sop += shift; + } + sim += vim._tree.mod; + sip += vip._tree.mod; + som += vom._tree.mod; + sop += vop._tree.mod; + } + if (vim && !d3_layout_treeRight(vop)) { + vop._tree.thread = vim; + vop._tree.mod += sim - sop; + } + if (vip && !d3_layout_treeLeft(vom)) { + vom._tree.thread = vip; + vom._tree.mod += sip - som; + ancestor = node; + } + } + return ancestor; + } + d3_layout_treeVisitAfter(root, function(node, previousSibling) { + node._tree = { + ancestor: node, + prelim: 0, + mod: 0, + change: 0, + shift: 0, + number: previousSibling ? previousSibling._tree.number + 1 : 0 + }; + }); + firstWalk(root); + secondWalk(root, -root._tree.prelim); + var left = d3_layout_treeSearch(root, d3_layout_treeLeftmost), right = d3_layout_treeSearch(root, d3_layout_treeRightmost), deep = d3_layout_treeSearch(root, d3_layout_treeDeepest), x0 = left.x - separation(left, right) / 2, x1 = right.x + separation(right, left) / 2, y1 = deep.depth || 1; + d3_layout_treeVisitAfter(root, nodeSize ? function(node) { + node.x *= size[0]; + node.y = node.depth * size[1]; + delete node._tree; + } : function(node) { + node.x = (node.x - x0) / (x1 - x0) * size[0]; + node.y = node.depth / y1 * size[1]; + delete node._tree; + }); + return nodes; + } + tree.separation = function(x) { + if (!arguments.length) return separation; + separation = x; + return tree; + }; + tree.size = function(x) { + if (!arguments.length) return nodeSize ? null : size; + nodeSize = (size = x) == null; + return tree; + }; + tree.nodeSize = function(x) { + if (!arguments.length) return nodeSize ? size : null; + nodeSize = (size = x) != null; + return tree; + }; + return d3_layout_hierarchyRebind(tree, hierarchy); + }; + function d3_layout_treeSeparation(a, b) { + return a.parent == b.parent ? 1 : 2; + } + function d3_layout_treeLeft(node) { + var children = node.children; + return children && children.length ? children[0] : node._tree.thread; + } + function d3_layout_treeRight(node) { + var children = node.children, n; + return children && (n = children.length) ? children[n - 1] : node._tree.thread; + } + function d3_layout_treeSearch(node, compare) { + var children = node.children; + if (children && (n = children.length)) { + var child, n, i = -1; + while (++i < n) { + if (compare(child = d3_layout_treeSearch(children[i], compare), node) > 0) { + node = child; + } + } + } + return node; + } + function d3_layout_treeRightmost(a, b) { + return a.x - b.x; + } + function d3_layout_treeLeftmost(a, b) { + return b.x - a.x; + } + function d3_layout_treeDeepest(a, b) { + return a.depth - b.depth; + } + function d3_layout_treeVisitAfter(node, callback) { + function visit(node, previousSibling) { + var children = node.children; + if (children && (n = children.length)) { + var child, previousChild = null, i = -1, n; + while (++i < n) { + child = children[i]; + visit(child, previousChild); + previousChild = child; + } + } + callback(node, previousSibling); + } + visit(node, null); + } + function d3_layout_treeShift(node) { + var shift = 0, change = 0, children = node.children, i = children.length, child; + while (--i >= 0) { + child = children[i]._tree; + child.prelim += shift; + child.mod += shift; + shift += child.shift + (change += child.change); + } + } + function d3_layout_treeMove(ancestor, node, shift) { + ancestor = ancestor._tree; + node = node._tree; + var change = shift / (node.number - ancestor.number); + ancestor.change += change; + node.change -= change; + node.shift += shift; + node.prelim += shift; + node.mod += shift; + } + function d3_layout_treeAncestor(vim, node, ancestor) { + return vim._tree.ancestor.parent == node.parent ? vim._tree.ancestor : ancestor; + } + d3.layout.pack = function() { + var hierarchy = d3.layout.hierarchy().sort(d3_layout_packSort), padding = 0, size = [ 1, 1 ], radius; + function pack(d, i) { + var nodes = hierarchy.call(this, d, i), root = nodes[0], w = size[0], h = size[1], r = radius == null ? Math.sqrt : typeof radius === "function" ? radius : function() { + return radius; + }; + root.x = root.y = 0; + d3_layout_treeVisitAfter(root, function(d) { + d.r = +r(d.value); + }); + d3_layout_treeVisitAfter(root, d3_layout_packSiblings); + if (padding) { + var dr = padding * (radius ? 1 : Math.max(2 * root.r / w, 2 * root.r / h)) / 2; + d3_layout_treeVisitAfter(root, function(d) { + d.r += dr; + }); + d3_layout_treeVisitAfter(root, d3_layout_packSiblings); + d3_layout_treeVisitAfter(root, function(d) { + d.r -= dr; + }); + } + d3_layout_packTransform(root, w / 2, h / 2, radius ? 1 : 1 / Math.max(2 * root.r / w, 2 * root.r / h)); + return nodes; + } + pack.size = function(_) { + if (!arguments.length) return size; + size = _; + return pack; + }; + pack.radius = function(_) { + if (!arguments.length) return radius; + radius = _ == null || typeof _ === "function" ? _ : +_; + return pack; + }; + pack.padding = function(_) { + if (!arguments.length) return padding; + padding = +_; + return pack; + }; + return d3_layout_hierarchyRebind(pack, hierarchy); + }; + function d3_layout_packSort(a, b) { + return a.value - b.value; + } + function d3_layout_packInsert(a, b) { + var c = a._pack_next; + a._pack_next = b; + b._pack_prev = a; + b._pack_next = c; + c._pack_prev = b; + } + function d3_layout_packSplice(a, b) { + a._pack_next = b; + b._pack_prev = a; + } + function d3_layout_packIntersects(a, b) { + var dx = b.x - a.x, dy = b.y - a.y, dr = a.r + b.r; + return .999 * dr * dr > dx * dx + dy * dy; + } + function d3_layout_packSiblings(node) { + if (!(nodes = node.children) || !(n = nodes.length)) return; + var nodes, xMin = Infinity, xMax = -Infinity, yMin = Infinity, yMax = -Infinity, a, b, c, i, j, k, n; + function bound(node) { + xMin = Math.min(node.x - node.r, xMin); + xMax = Math.max(node.x + node.r, xMax); + yMin = Math.min(node.y - node.r, yMin); + yMax = Math.max(node.y + node.r, yMax); + } + nodes.forEach(d3_layout_packLink); + a = nodes[0]; + a.x = -a.r; + a.y = 0; + bound(a); + if (n > 1) { + b = nodes[1]; + b.x = b.r; + b.y = 0; + bound(b); + if (n > 2) { + c = nodes[2]; + d3_layout_packPlace(a, b, c); + bound(c); + d3_layout_packInsert(a, c); + a._pack_prev = c; + d3_layout_packInsert(c, b); + b = a._pack_next; + for (i = 3; i < n; i++) { + d3_layout_packPlace(a, b, c = nodes[i]); + var isect = 0, s1 = 1, s2 = 1; + for (j = b._pack_next; j !== b; j = j._pack_next, s1++) { + if (d3_layout_packIntersects(j, c)) { + isect = 1; + break; + } + } + if (isect == 1) { + for (k = a._pack_prev; k !== j._pack_prev; k = k._pack_prev, s2++) { + if (d3_layout_packIntersects(k, c)) { + break; + } + } + } + if (isect) { + if (s1 < s2 || s1 == s2 && b.r < a.r) d3_layout_packSplice(a, b = j); else d3_layout_packSplice(a = k, b); + i--; + } else { + d3_layout_packInsert(a, c); + b = c; + bound(c); + } + } + } + } + var cx = (xMin + xMax) / 2, cy = (yMin + yMax) / 2, cr = 0; + for (i = 0; i < n; i++) { + c = nodes[i]; + c.x -= cx; + c.y -= cy; + cr = Math.max(cr, c.r + Math.sqrt(c.x * c.x + c.y * c.y)); + } + node.r = cr; + nodes.forEach(d3_layout_packUnlink); + } + function d3_layout_packLink(node) { + node._pack_next = node._pack_prev = node; + } + function d3_layout_packUnlink(node) { + delete node._pack_next; + delete node._pack_prev; + } + function d3_layout_packTransform(node, x, y, k) { + var children = node.children; + node.x = x += k * node.x; + node.y = y += k * node.y; + node.r *= k; + if (children) { + var i = -1, n = children.length; + while (++i < n) d3_layout_packTransform(children[i], x, y, k); + } + } + function d3_layout_packPlace(a, b, c) { + var db = a.r + c.r, dx = b.x - a.x, dy = b.y - a.y; + if (db && (dx || dy)) { + var da = b.r + c.r, dc = dx * dx + dy * dy; + da *= da; + db *= db; + var x = .5 + (db - da) / (2 * dc), y = Math.sqrt(Math.max(0, 2 * da * (db + dc) - (db -= dc) * db - da * da)) / (2 * dc); + c.x = a.x + x * dx + y * dy; + c.y = a.y + x * dy - y * dx; + } else { + c.x = a.x + db; + c.y = a.y; + } + } + d3.layout.cluster = function() { + var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = false; + function cluster(d, i) { + var nodes = hierarchy.call(this, d, i), root = nodes[0], previousNode, x = 0; + d3_layout_treeVisitAfter(root, function(node) { + var children = node.children; + if (children && children.length) { + node.x = d3_layout_clusterX(children); + node.y = d3_layout_clusterY(children); + } else { + node.x = previousNode ? x += separation(node, previousNode) : 0; + node.y = 0; + previousNode = node; + } + }); + var left = d3_layout_clusterLeft(root), right = d3_layout_clusterRight(root), x0 = left.x - separation(left, right) / 2, x1 = right.x + separation(right, left) / 2; + d3_layout_treeVisitAfter(root, nodeSize ? function(node) { + node.x = (node.x - root.x) * size[0]; + node.y = (root.y - node.y) * size[1]; + } : function(node) { + node.x = (node.x - x0) / (x1 - x0) * size[0]; + node.y = (1 - (root.y ? node.y / root.y : 1)) * size[1]; + }); + return nodes; + } + cluster.separation = function(x) { + if (!arguments.length) return separation; + separation = x; + return cluster; + }; + cluster.size = function(x) { + if (!arguments.length) return nodeSize ? null : size; + nodeSize = (size = x) == null; + return cluster; + }; + cluster.nodeSize = function(x) { + if (!arguments.length) return nodeSize ? size : null; + nodeSize = (size = x) != null; + return cluster; + }; + return d3_layout_hierarchyRebind(cluster, hierarchy); + }; + function d3_layout_clusterY(children) { + return 1 + d3.max(children, function(child) { + return child.y; + }); + } + function d3_layout_clusterX(children) { + return children.reduce(function(x, child) { + return x + child.x; + }, 0) / children.length; + } + function d3_layout_clusterLeft(node) { + var children = node.children; + return children && children.length ? d3_layout_clusterLeft(children[0]) : node; + } + function d3_layout_clusterRight(node) { + var children = node.children, n; + return children && (n = children.length) ? d3_layout_clusterRight(children[n - 1]) : node; + } + d3.layout.treemap = function() { + var hierarchy = d3.layout.hierarchy(), round = Math.round, size = [ 1, 1 ], padding = null, pad = d3_layout_treemapPadNull, sticky = false, stickies, mode = "squarify", ratio = .5 * (1 + Math.sqrt(5)); + function scale(children, k) { + var i = -1, n = children.length, child, area; + while (++i < n) { + area = (child = children[i]).value * (k < 0 ? 0 : k); + child.area = isNaN(area) || area <= 0 ? 0 : area; + } + } + function squarify(node) { + var children = node.children; + if (children && children.length) { + var rect = pad(node), row = [], remaining = children.slice(), child, best = Infinity, score, u = mode === "slice" ? rect.dx : mode === "dice" ? rect.dy : mode === "slice-dice" ? node.depth & 1 ? rect.dy : rect.dx : Math.min(rect.dx, rect.dy), n; + scale(remaining, rect.dx * rect.dy / node.value); + row.area = 0; + while ((n = remaining.length) > 0) { + row.push(child = remaining[n - 1]); + row.area += child.area; + if (mode !== "squarify" || (score = worst(row, u)) <= best) { + remaining.pop(); + best = score; + } else { + row.area -= row.pop().area; + position(row, u, rect, false); + u = Math.min(rect.dx, rect.dy); + row.length = row.area = 0; + best = Infinity; + } + } + if (row.length) { + position(row, u, rect, true); + row.length = row.area = 0; + } + children.forEach(squarify); + } + } + function stickify(node) { + var children = node.children; + if (children && children.length) { + var rect = pad(node), remaining = children.slice(), child, row = []; + scale(remaining, rect.dx * rect.dy / node.value); + row.area = 0; + while (child = remaining.pop()) { + row.push(child); + row.area += child.area; + if (child.z != null) { + position(row, child.z ? rect.dx : rect.dy, rect, !remaining.length); + row.length = row.area = 0; + } + } + children.forEach(stickify); + } + } + function worst(row, u) { + var s = row.area, r, rmax = 0, rmin = Infinity, i = -1, n = row.length; + while (++i < n) { + if (!(r = row[i].area)) continue; + if (r < rmin) rmin = r; + if (r > rmax) rmax = r; + } + s *= s; + u *= u; + return s ? Math.max(u * rmax * ratio / s, s / (u * rmin * ratio)) : Infinity; + } + function position(row, u, rect, flush) { + var i = -1, n = row.length, x = rect.x, y = rect.y, v = u ? round(row.area / u) : 0, o; + if (u == rect.dx) { + if (flush || v > rect.dy) v = rect.dy; + while (++i < n) { + o = row[i]; + o.x = x; + o.y = y; + o.dy = v; + x += o.dx = Math.min(rect.x + rect.dx - x, v ? round(o.area / v) : 0); + } + o.z = true; + o.dx += rect.x + rect.dx - x; + rect.y += v; + rect.dy -= v; + } else { + if (flush || v > rect.dx) v = rect.dx; + while (++i < n) { + o = row[i]; + o.x = x; + o.y = y; + o.dx = v; + y += o.dy = Math.min(rect.y + rect.dy - y, v ? round(o.area / v) : 0); + } + o.z = false; + o.dy += rect.y + rect.dy - y; + rect.x += v; + rect.dx -= v; + } + } + function treemap(d) { + var nodes = stickies || hierarchy(d), root = nodes[0]; + root.x = 0; + root.y = 0; + root.dx = size[0]; + root.dy = size[1]; + if (stickies) hierarchy.revalue(root); + scale([ root ], root.dx * root.dy / root.value); + (stickies ? stickify : squarify)(root); + if (sticky) stickies = nodes; + return nodes; + } + treemap.size = function(x) { + if (!arguments.length) return size; + size = x; + return treemap; + }; + treemap.padding = function(x) { + if (!arguments.length) return padding; + function padFunction(node) { + var p = x.call(treemap, node, node.depth); + return p == null ? d3_layout_treemapPadNull(node) : d3_layout_treemapPad(node, typeof p === "number" ? [ p, p, p, p ] : p); + } + function padConstant(node) { + return d3_layout_treemapPad(node, x); + } + var type; + pad = (padding = x) == null ? d3_layout_treemapPadNull : (type = typeof x) === "function" ? padFunction : type === "number" ? (x = [ x, x, x, x ], + padConstant) : padConstant; + return treemap; + }; + treemap.round = function(x) { + if (!arguments.length) return round != Number; + round = x ? Math.round : Number; + return treemap; + }; + treemap.sticky = function(x) { + if (!arguments.length) return sticky; + sticky = x; + stickies = null; + return treemap; + }; + treemap.ratio = function(x) { + if (!arguments.length) return ratio; + ratio = x; + return treemap; + }; + treemap.mode = function(x) { + if (!arguments.length) return mode; + mode = x + ""; + return treemap; + }; + return d3_layout_hierarchyRebind(treemap, hierarchy); + }; + function d3_layout_treemapPadNull(node) { + return { + x: node.x, + y: node.y, + dx: node.dx, + dy: node.dy + }; + } + function d3_layout_treemapPad(node, padding) { + var x = node.x + padding[3], y = node.y + padding[0], dx = node.dx - padding[1] - padding[3], dy = node.dy - padding[0] - padding[2]; + if (dx < 0) { + x += dx / 2; + dx = 0; + } + if (dy < 0) { + y += dy / 2; + dy = 0; + } + return { + x: x, + y: y, + dx: dx, + dy: dy + }; + } + d3.random = { + normal: function(µ, σ) { + var n = arguments.length; + if (n < 2) σ = 1; + if (n < 1) µ = 0; + return function() { + var x, y, r; + do { + x = Math.random() * 2 - 1; + y = Math.random() * 2 - 1; + r = x * x + y * y; + } while (!r || r > 1); + return µ + σ * x * Math.sqrt(-2 * Math.log(r) / r); + }; + }, + logNormal: function() { + var random = d3.random.normal.apply(d3, arguments); + return function() { + return Math.exp(random()); + }; + }, + bates: function(m) { + var random = d3.random.irwinHall(m); + return function() { + return random() / m; + }; + }, + irwinHall: function(m) { + return function() { + for (var s = 0, j = 0; j < m; j++) s += Math.random(); + return s; + }; + } + }; + d3.scale = {}; + function d3_scaleExtent(domain) { + var start = domain[0], stop = domain[domain.length - 1]; + return start < stop ? [ start, stop ] : [ stop, start ]; + } + function d3_scaleRange(scale) { + return scale.rangeExtent ? scale.rangeExtent() : d3_scaleExtent(scale.range()); + } + function d3_scale_bilinear(domain, range, uninterpolate, interpolate) { + var u = uninterpolate(domain[0], domain[1]), i = interpolate(range[0], range[1]); + return function(x) { + return i(u(x)); + }; + } + function d3_scale_nice(domain, nice) { + var i0 = 0, i1 = domain.length - 1, x0 = domain[i0], x1 = domain[i1], dx; + if (x1 < x0) { + dx = i0, i0 = i1, i1 = dx; + dx = x0, x0 = x1, x1 = dx; + } + domain[i0] = nice.floor(x0); + domain[i1] = nice.ceil(x1); + return domain; + } + function d3_scale_niceStep(step) { + return step ? { + floor: function(x) { + return Math.floor(x / step) * step; + }, + ceil: function(x) { + return Math.ceil(x / step) * step; + } + } : d3_scale_niceIdentity; + } + var d3_scale_niceIdentity = { + floor: d3_identity, + ceil: d3_identity + }; + function d3_scale_polylinear(domain, range, uninterpolate, interpolate) { + var u = [], i = [], j = 0, k = Math.min(domain.length, range.length) - 1; + if (domain[k] < domain[0]) { + domain = domain.slice().reverse(); + range = range.slice().reverse(); + } + while (++j <= k) { + u.push(uninterpolate(domain[j - 1], domain[j])); + i.push(interpolate(range[j - 1], range[j])); + } + return function(x) { + var j = d3.bisect(domain, x, 1, k) - 1; + return i[j](u[j](x)); + }; + } + d3.scale.linear = function() { + return d3_scale_linear([ 0, 1 ], [ 0, 1 ], d3_interpolate, false); + }; + function d3_scale_linear(domain, range, interpolate, clamp) { + var output, input; + function rescale() { + var linear = Math.min(domain.length, range.length) > 2 ? d3_scale_polylinear : d3_scale_bilinear, uninterpolate = clamp ? d3_uninterpolateClamp : d3_uninterpolateNumber; + output = linear(domain, range, uninterpolate, interpolate); + input = linear(range, domain, uninterpolate, d3_interpolate); + return scale; + } + function scale(x) { + return output(x); + } + scale.invert = function(y) { + return input(y); + }; + scale.domain = function(x) { + if (!arguments.length) return domain; + domain = x.map(Number); + return rescale(); + }; + scale.range = function(x) { + if (!arguments.length) return range; + range = x; + return rescale(); + }; + scale.rangeRound = function(x) { + return scale.range(x).interpolate(d3_interpolateRound); + }; + scale.clamp = function(x) { + if (!arguments.length) return clamp; + clamp = x; + return rescale(); + }; + scale.interpolate = function(x) { + if (!arguments.length) return interpolate; + interpolate = x; + return rescale(); + }; + scale.ticks = function(m) { + return d3_scale_linearTicks(domain, m); + }; + scale.tickFormat = function(m, format) { + return d3_scale_linearTickFormat(domain, m, format); + }; + scale.nice = function(m) { + d3_scale_linearNice(domain, m); + return rescale(); + }; + scale.copy = function() { + return d3_scale_linear(domain, range, interpolate, clamp); + }; + return rescale(); + } + function d3_scale_linearRebind(scale, linear) { + return d3.rebind(scale, linear, "range", "rangeRound", "interpolate", "clamp"); + } + function d3_scale_linearNice(domain, m) { + return d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2])); + } + function d3_scale_linearTickRange(domain, m) { + if (m == null) m = 10; + var extent = d3_scaleExtent(domain), span = extent[1] - extent[0], step = Math.pow(10, Math.floor(Math.log(span / m) / Math.LN10)), err = m / span * step; + if (err <= .15) step *= 10; else if (err <= .35) step *= 5; else if (err <= .75) step *= 2; + extent[0] = Math.ceil(extent[0] / step) * step; + extent[1] = Math.floor(extent[1] / step) * step + step * .5; + extent[2] = step; + return extent; + } + function d3_scale_linearTicks(domain, m) { + return d3.range.apply(d3, d3_scale_linearTickRange(domain, m)); + } + function d3_scale_linearTickFormat(domain, m, format) { + var range = d3_scale_linearTickRange(domain, m); + return d3.format(format ? format.replace(d3_format_re, function(a, b, c, d, e, f, g, h, i, j) { + return [ b, c, d, e, f, g, h, i || "." + d3_scale_linearFormatPrecision(j, range), j ].join(""); + }) : ",." + d3_scale_linearPrecision(range[2]) + "f"); + } + var d3_scale_linearFormatSignificant = { + s: 1, + g: 1, + p: 1, + r: 1, + e: 1 + }; + function d3_scale_linearPrecision(value) { + return -Math.floor(Math.log(value) / Math.LN10 + .01); + } + function d3_scale_linearFormatPrecision(type, range) { + var p = d3_scale_linearPrecision(range[2]); + return type in d3_scale_linearFormatSignificant ? Math.abs(p - d3_scale_linearPrecision(Math.max(Math.abs(range[0]), Math.abs(range[1])))) + +(type !== "e") : p - (type === "%") * 2; + } + d3.scale.log = function() { + return d3_scale_log(d3.scale.linear().domain([ 0, 1 ]), 10, true, [ 1, 10 ]); + }; + function d3_scale_log(linear, base, positive, domain) { + function log(x) { + return (positive ? Math.log(x < 0 ? 0 : x) : -Math.log(x > 0 ? 0 : -x)) / Math.log(base); + } + function pow(x) { + return positive ? Math.pow(base, x) : -Math.pow(base, -x); + } + function scale(x) { + return linear(log(x)); + } + scale.invert = function(x) { + return pow(linear.invert(x)); + }; + scale.domain = function(x) { + if (!arguments.length) return domain; + positive = x[0] >= 0; + linear.domain((domain = x.map(Number)).map(log)); + return scale; + }; + scale.base = function(_) { + if (!arguments.length) return base; + base = +_; + linear.domain(domain.map(log)); + return scale; + }; + scale.nice = function() { + var niced = d3_scale_nice(domain.map(log), positive ? Math : d3_scale_logNiceNegative); + linear.domain(niced); + domain = niced.map(pow); + return scale; + }; + scale.ticks = function() { + var extent = d3_scaleExtent(domain), ticks = [], u = extent[0], v = extent[1], i = Math.floor(log(u)), j = Math.ceil(log(v)), n = base % 1 ? 2 : base; + if (isFinite(j - i)) { + if (positive) { + for (;i < j; i++) for (var k = 1; k < n; k++) ticks.push(pow(i) * k); + ticks.push(pow(i)); + } else { + ticks.push(pow(i)); + for (;i++ < j; ) for (var k = n - 1; k > 0; k--) ticks.push(pow(i) * k); + } + for (i = 0; ticks[i] < u; i++) {} + for (j = ticks.length; ticks[j - 1] > v; j--) {} + ticks = ticks.slice(i, j); + } + return ticks; + }; + scale.tickFormat = function(n, format) { + if (!arguments.length) return d3_scale_logFormat; + if (arguments.length < 2) format = d3_scale_logFormat; else if (typeof format !== "function") format = d3.format(format); + var k = Math.max(.1, n / scale.ticks().length), f = positive ? (e = 1e-12, Math.ceil) : (e = -1e-12, + Math.floor), e; + return function(d) { + return d / pow(f(log(d) + e)) <= k ? format(d) : ""; + }; + }; + scale.copy = function() { + return d3_scale_log(linear.copy(), base, positive, domain); + }; + return d3_scale_linearRebind(scale, linear); + } + var d3_scale_logFormat = d3.format(".0e"), d3_scale_logNiceNegative = { + floor: function(x) { + return -Math.ceil(-x); + }, + ceil: function(x) { + return -Math.floor(-x); + } + }; + d3.scale.pow = function() { + return d3_scale_pow(d3.scale.linear(), 1, [ 0, 1 ]); + }; + function d3_scale_pow(linear, exponent, domain) { + var powp = d3_scale_powPow(exponent), powb = d3_scale_powPow(1 / exponent); + function scale(x) { + return linear(powp(x)); + } + scale.invert = function(x) { + return powb(linear.invert(x)); + }; + scale.domain = function(x) { + if (!arguments.length) return domain; + linear.domain((domain = x.map(Number)).map(powp)); + return scale; + }; + scale.ticks = function(m) { + return d3_scale_linearTicks(domain, m); + }; + scale.tickFormat = function(m, format) { + return d3_scale_linearTickFormat(domain, m, format); + }; + scale.nice = function(m) { + return scale.domain(d3_scale_linearNice(domain, m)); + }; + scale.exponent = function(x) { + if (!arguments.length) return exponent; + powp = d3_scale_powPow(exponent = x); + powb = d3_scale_powPow(1 / exponent); + linear.domain(domain.map(powp)); + return scale; + }; + scale.copy = function() { + return d3_scale_pow(linear.copy(), exponent, domain); + }; + return d3_scale_linearRebind(scale, linear); + } + function d3_scale_powPow(e) { + return function(x) { + return x < 0 ? -Math.pow(-x, e) : Math.pow(x, e); + }; + } + d3.scale.sqrt = function() { + return d3.scale.pow().exponent(.5); + }; + d3.scale.ordinal = function() { + return d3_scale_ordinal([], { + t: "range", + a: [ [] ] + }); + }; + function d3_scale_ordinal(domain, ranger) { + var index, range, rangeBand; + function scale(x) { + return range[((index.get(x) || ranger.t === "range" && index.set(x, domain.push(x))) - 1) % range.length]; + } + function steps(start, step) { + return d3.range(domain.length).map(function(i) { + return start + step * i; + }); + } + scale.domain = function(x) { + if (!arguments.length) return domain; + domain = []; + index = new d3_Map(); + var i = -1, n = x.length, xi; + while (++i < n) if (!index.has(xi = x[i])) index.set(xi, domain.push(xi)); + return scale[ranger.t].apply(scale, ranger.a); + }; + scale.range = function(x) { + if (!arguments.length) return range; + range = x; + rangeBand = 0; + ranger = { + t: "range", + a: arguments + }; + return scale; + }; + scale.rangePoints = function(x, padding) { + if (arguments.length < 2) padding = 0; + var start = x[0], stop = x[1], step = (stop - start) / (Math.max(1, domain.length - 1) + padding); + range = steps(domain.length < 2 ? (start + stop) / 2 : start + step * padding / 2, step); + rangeBand = 0; + ranger = { + t: "rangePoints", + a: arguments + }; + return scale; + }; + scale.rangeBands = function(x, padding, outerPadding) { + if (arguments.length < 2) padding = 0; + if (arguments.length < 3) outerPadding = padding; + var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = (stop - start) / (domain.length - padding + 2 * outerPadding); + range = steps(start + step * outerPadding, step); + if (reverse) range.reverse(); + rangeBand = step * (1 - padding); + ranger = { + t: "rangeBands", + a: arguments + }; + return scale; + }; + scale.rangeRoundBands = function(x, padding, outerPadding) { + if (arguments.length < 2) padding = 0; + if (arguments.length < 3) outerPadding = padding; + var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = Math.floor((stop - start) / (domain.length - padding + 2 * outerPadding)), error = stop - start - (domain.length - padding) * step; + range = steps(start + Math.round(error / 2), step); + if (reverse) range.reverse(); + rangeBand = Math.round(step * (1 - padding)); + ranger = { + t: "rangeRoundBands", + a: arguments + }; + return scale; + }; + scale.rangeBand = function() { + return rangeBand; + }; + scale.rangeExtent = function() { + return d3_scaleExtent(ranger.a[0]); + }; + scale.copy = function() { + return d3_scale_ordinal(domain, ranger); + }; + return scale.domain(domain); + } + d3.scale.category10 = function() { + return d3.scale.ordinal().range(d3_category10); + }; + d3.scale.category20 = function() { + return d3.scale.ordinal().range(d3_category20); + }; + d3.scale.category20b = function() { + return d3.scale.ordinal().range(d3_category20b); + }; + d3.scale.category20c = function() { + return d3.scale.ordinal().range(d3_category20c); + }; + var d3_category10 = [ 2062260, 16744206, 2924588, 14034728, 9725885, 9197131, 14907330, 8355711, 12369186, 1556175 ].map(d3_rgbString); + var d3_category20 = [ 2062260, 11454440, 16744206, 16759672, 2924588, 10018698, 14034728, 16750742, 9725885, 12955861, 9197131, 12885140, 14907330, 16234194, 8355711, 13092807, 12369186, 14408589, 1556175, 10410725 ].map(d3_rgbString); + var d3_category20b = [ 3750777, 5395619, 7040719, 10264286, 6519097, 9216594, 11915115, 13556636, 9202993, 12426809, 15186514, 15190932, 8666169, 11356490, 14049643, 15177372, 8077683, 10834324, 13528509, 14589654 ].map(d3_rgbString); + var d3_category20c = [ 3244733, 7057110, 10406625, 13032431, 15095053, 16616764, 16625259, 16634018, 3253076, 7652470, 10607003, 13101504, 7695281, 10394312, 12369372, 14342891, 6513507, 9868950, 12434877, 14277081 ].map(d3_rgbString); + d3.scale.quantile = function() { + return d3_scale_quantile([], []); + }; + function d3_scale_quantile(domain, range) { + var thresholds; + function rescale() { + var k = 0, q = range.length; + thresholds = []; + while (++k < q) thresholds[k - 1] = d3.quantile(domain, k / q); + return scale; + } + function scale(x) { + if (!isNaN(x = +x)) return range[d3.bisect(thresholds, x)]; + } + scale.domain = function(x) { + if (!arguments.length) return domain; + domain = x.filter(function(d) { + return !isNaN(d); + }).sort(d3.ascending); + return rescale(); + }; + scale.range = function(x) { + if (!arguments.length) return range; + range = x; + return rescale(); + }; + scale.quantiles = function() { + return thresholds; + }; + scale.invertExtent = function(y) { + y = range.indexOf(y); + return y < 0 ? [ NaN, NaN ] : [ y > 0 ? thresholds[y - 1] : domain[0], y < thresholds.length ? thresholds[y] : domain[domain.length - 1] ]; + }; + scale.copy = function() { + return d3_scale_quantile(domain, range); + }; + return rescale(); + } + d3.scale.quantize = function() { + return d3_scale_quantize(0, 1, [ 0, 1 ]); + }; + function d3_scale_quantize(x0, x1, range) { + var kx, i; + function scale(x) { + return range[Math.max(0, Math.min(i, Math.floor(kx * (x - x0))))]; + } + function rescale() { + kx = range.length / (x1 - x0); + i = range.length - 1; + return scale; + } + scale.domain = function(x) { + if (!arguments.length) return [ x0, x1 ]; + x0 = +x[0]; + x1 = +x[x.length - 1]; + return rescale(); + }; + scale.range = function(x) { + if (!arguments.length) return range; + range = x; + return rescale(); + }; + scale.invertExtent = function(y) { + y = range.indexOf(y); + y = y < 0 ? NaN : y / kx + x0; + return [ y, y + 1 / kx ]; + }; + scale.copy = function() { + return d3_scale_quantize(x0, x1, range); + }; + return rescale(); + } + d3.scale.threshold = function() { + return d3_scale_threshold([ .5 ], [ 0, 1 ]); + }; + function d3_scale_threshold(domain, range) { + function scale(x) { + if (x <= x) return range[d3.bisect(domain, x)]; + } + scale.domain = function(_) { + if (!arguments.length) return domain; + domain = _; + return scale; + }; + scale.range = function(_) { + if (!arguments.length) return range; + range = _; + return scale; + }; + scale.invertExtent = function(y) { + y = range.indexOf(y); + return [ domain[y - 1], domain[y] ]; + }; + scale.copy = function() { + return d3_scale_threshold(domain, range); + }; + return scale; + } + d3.scale.identity = function() { + return d3_scale_identity([ 0, 1 ]); + }; + function d3_scale_identity(domain) { + function identity(x) { + return +x; + } + identity.invert = identity; + identity.domain = identity.range = function(x) { + if (!arguments.length) return domain; + domain = x.map(identity); + return identity; + }; + identity.ticks = function(m) { + return d3_scale_linearTicks(domain, m); + }; + identity.tickFormat = function(m, format) { + return d3_scale_linearTickFormat(domain, m, format); + }; + identity.copy = function() { + return d3_scale_identity(domain); + }; + return identity; + } + d3.svg = {}; + d3.svg.arc = function() { + var innerRadius = d3_svg_arcInnerRadius, outerRadius = d3_svg_arcOuterRadius, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle; + function arc() { + var r0 = innerRadius.apply(this, arguments), r1 = outerRadius.apply(this, arguments), a0 = startAngle.apply(this, arguments) + d3_svg_arcOffset, a1 = endAngle.apply(this, arguments) + d3_svg_arcOffset, da = (a1 < a0 && (da = a0, + a0 = a1, a1 = da), a1 - a0), df = da < π ? "0" : "1", c0 = Math.cos(a0), s0 = Math.sin(a0), c1 = Math.cos(a1), s1 = Math.sin(a1); + return da >= d3_svg_arcMax ? r0 ? "M0," + r1 + "A" + r1 + "," + r1 + " 0 1,1 0," + -r1 + "A" + r1 + "," + r1 + " 0 1,1 0," + r1 + "M0," + r0 + "A" + r0 + "," + r0 + " 0 1,0 0," + -r0 + "A" + r0 + "," + r0 + " 0 1,0 0," + r0 + "Z" : "M0," + r1 + "A" + r1 + "," + r1 + " 0 1,1 0," + -r1 + "A" + r1 + "," + r1 + " 0 1,1 0," + r1 + "Z" : r0 ? "M" + r1 * c0 + "," + r1 * s0 + "A" + r1 + "," + r1 + " 0 " + df + ",1 " + r1 * c1 + "," + r1 * s1 + "L" + r0 * c1 + "," + r0 * s1 + "A" + r0 + "," + r0 + " 0 " + df + ",0 " + r0 * c0 + "," + r0 * s0 + "Z" : "M" + r1 * c0 + "," + r1 * s0 + "A" + r1 + "," + r1 + " 0 " + df + ",1 " + r1 * c1 + "," + r1 * s1 + "L0,0" + "Z"; + } + arc.innerRadius = function(v) { + if (!arguments.length) return innerRadius; + innerRadius = d3_functor(v); + return arc; + }; + arc.outerRadius = function(v) { + if (!arguments.length) return outerRadius; + outerRadius = d3_functor(v); + return arc; + }; + arc.startAngle = function(v) { + if (!arguments.length) return startAngle; + startAngle = d3_functor(v); + return arc; + }; + arc.endAngle = function(v) { + if (!arguments.length) return endAngle; + endAngle = d3_functor(v); + return arc; + }; + arc.centroid = function() { + var r = (innerRadius.apply(this, arguments) + outerRadius.apply(this, arguments)) / 2, a = (startAngle.apply(this, arguments) + endAngle.apply(this, arguments)) / 2 + d3_svg_arcOffset; + return [ Math.cos(a) * r, Math.sin(a) * r ]; + }; + return arc; + }; + var d3_svg_arcOffset = -halfπ, d3_svg_arcMax = τ - ε; + function d3_svg_arcInnerRadius(d) { + return d.innerRadius; + } + function d3_svg_arcOuterRadius(d) { + return d.outerRadius; + } + function d3_svg_arcStartAngle(d) { + return d.startAngle; + } + function d3_svg_arcEndAngle(d) { + return d.endAngle; + } + function d3_svg_line(projection) { + var x = d3_geom_pointX, y = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, tension = .7; + function line(data) { + var segments = [], points = [], i = -1, n = data.length, d, fx = d3_functor(x), fy = d3_functor(y); + function segment() { + segments.push("M", interpolate(projection(points), tension)); + } + while (++i < n) { + if (defined.call(this, d = data[i], i)) { + points.push([ +fx.call(this, d, i), +fy.call(this, d, i) ]); + } else if (points.length) { + segment(); + points = []; + } + } + if (points.length) segment(); + return segments.length ? segments.join("") : null; + } + line.x = function(_) { + if (!arguments.length) return x; + x = _; + return line; + }; + line.y = function(_) { + if (!arguments.length) return y; + y = _; + return line; + }; + line.defined = function(_) { + if (!arguments.length) return defined; + defined = _; + return line; + }; + line.interpolate = function(_) { + if (!arguments.length) return interpolateKey; + if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key; + return line; + }; + line.tension = function(_) { + if (!arguments.length) return tension; + tension = _; + return line; + }; + return line; + } + d3.svg.line = function() { + return d3_svg_line(d3_identity); + }; + var d3_svg_lineInterpolators = d3.map({ + linear: d3_svg_lineLinear, + "linear-closed": d3_svg_lineLinearClosed, + step: d3_svg_lineStep, + "step-before": d3_svg_lineStepBefore, + "step-after": d3_svg_lineStepAfter, + basis: d3_svg_lineBasis, + "basis-open": d3_svg_lineBasisOpen, + "basis-closed": d3_svg_lineBasisClosed, + bundle: d3_svg_lineBundle, + cardinal: d3_svg_lineCardinal, + "cardinal-open": d3_svg_lineCardinalOpen, + "cardinal-closed": d3_svg_lineCardinalClosed, + monotone: d3_svg_lineMonotone + }); + d3_svg_lineInterpolators.forEach(function(key, value) { + value.key = key; + value.closed = /-closed$/.test(key); + }); + function d3_svg_lineLinear(points) { + return points.join("L"); + } + function d3_svg_lineLinearClosed(points) { + return d3_svg_lineLinear(points) + "Z"; + } + function d3_svg_lineStep(points) { + var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; + while (++i < n) path.push("H", (p[0] + (p = points[i])[0]) / 2, "V", p[1]); + if (n > 1) path.push("H", p[0]); + return path.join(""); + } + function d3_svg_lineStepBefore(points) { + var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; + while (++i < n) path.push("V", (p = points[i])[1], "H", p[0]); + return path.join(""); + } + function d3_svg_lineStepAfter(points) { + var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; + while (++i < n) path.push("H", (p = points[i])[0], "V", p[1]); + return path.join(""); + } + function d3_svg_lineCardinalOpen(points, tension) { + return points.length < 4 ? d3_svg_lineLinear(points) : points[1] + d3_svg_lineHermite(points.slice(1, points.length - 1), d3_svg_lineCardinalTangents(points, tension)); + } + function d3_svg_lineCardinalClosed(points, tension) { + return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite((points.push(points[0]), + points), d3_svg_lineCardinalTangents([ points[points.length - 2] ].concat(points, [ points[1] ]), tension)); + } + function d3_svg_lineCardinal(points, tension) { + return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineCardinalTangents(points, tension)); + } + function d3_svg_lineHermite(points, tangents) { + if (tangents.length < 1 || points.length != tangents.length && points.length != tangents.length + 2) { + return d3_svg_lineLinear(points); + } + var quad = points.length != tangents.length, path = "", p0 = points[0], p = points[1], t0 = tangents[0], t = t0, pi = 1; + if (quad) { + path += "Q" + (p[0] - t0[0] * 2 / 3) + "," + (p[1] - t0[1] * 2 / 3) + "," + p[0] + "," + p[1]; + p0 = points[1]; + pi = 2; + } + if (tangents.length > 1) { + t = tangents[1]; + p = points[pi]; + pi++; + path += "C" + (p0[0] + t0[0]) + "," + (p0[1] + t0[1]) + "," + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1]; + for (var i = 2; i < tangents.length; i++, pi++) { + p = points[pi]; + t = tangents[i]; + path += "S" + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1]; + } + } + if (quad) { + var lp = points[pi]; + path += "Q" + (p[0] + t[0] * 2 / 3) + "," + (p[1] + t[1] * 2 / 3) + "," + lp[0] + "," + lp[1]; + } + return path; + } + function d3_svg_lineCardinalTangents(points, tension) { + var tangents = [], a = (1 - tension) / 2, p0, p1 = points[0], p2 = points[1], i = 1, n = points.length; + while (++i < n) { + p0 = p1; + p1 = p2; + p2 = points[i]; + tangents.push([ a * (p2[0] - p0[0]), a * (p2[1] - p0[1]) ]); + } + return tangents; + } + function d3_svg_lineBasis(points) { + if (points.length < 3) return d3_svg_lineLinear(points); + var i = 1, n = points.length, pi = points[0], x0 = pi[0], y0 = pi[1], px = [ x0, x0, x0, (pi = points[1])[0] ], py = [ y0, y0, y0, pi[1] ], path = [ x0, ",", y0, "L", d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ]; + points.push(points[n - 1]); + while (++i <= n) { + pi = points[i]; + px.shift(); + px.push(pi[0]); + py.shift(); + py.push(pi[1]); + d3_svg_lineBasisBezier(path, px, py); + } + points.pop(); + path.push("L", pi); + return path.join(""); + } + function d3_svg_lineBasisOpen(points) { + if (points.length < 4) return d3_svg_lineLinear(points); + var path = [], i = -1, n = points.length, pi, px = [ 0 ], py = [ 0 ]; + while (++i < 3) { + pi = points[i]; + px.push(pi[0]); + py.push(pi[1]); + } + path.push(d3_svg_lineDot4(d3_svg_lineBasisBezier3, px) + "," + d3_svg_lineDot4(d3_svg_lineBasisBezier3, py)); + --i; + while (++i < n) { + pi = points[i]; + px.shift(); + px.push(pi[0]); + py.shift(); + py.push(pi[1]); + d3_svg_lineBasisBezier(path, px, py); + } + return path.join(""); + } + function d3_svg_lineBasisClosed(points) { + var path, i = -1, n = points.length, m = n + 4, pi, px = [], py = []; + while (++i < 4) { + pi = points[i % n]; + px.push(pi[0]); + py.push(pi[1]); + } + path = [ d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ]; + --i; + while (++i < m) { + pi = points[i % n]; + px.shift(); + px.push(pi[0]); + py.shift(); + py.push(pi[1]); + d3_svg_lineBasisBezier(path, px, py); + } + return path.join(""); + } + function d3_svg_lineBundle(points, tension) { + var n = points.length - 1; + if (n) { + var x0 = points[0][0], y0 = points[0][1], dx = points[n][0] - x0, dy = points[n][1] - y0, i = -1, p, t; + while (++i <= n) { + p = points[i]; + t = i / n; + p[0] = tension * p[0] + (1 - tension) * (x0 + t * dx); + p[1] = tension * p[1] + (1 - tension) * (y0 + t * dy); + } + } + return d3_svg_lineBasis(points); + } + function d3_svg_lineDot4(a, b) { + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]; + } + var d3_svg_lineBasisBezier1 = [ 0, 2 / 3, 1 / 3, 0 ], d3_svg_lineBasisBezier2 = [ 0, 1 / 3, 2 / 3, 0 ], d3_svg_lineBasisBezier3 = [ 0, 1 / 6, 2 / 3, 1 / 6 ]; + function d3_svg_lineBasisBezier(path, x, y) { + path.push("C", d3_svg_lineDot4(d3_svg_lineBasisBezier1, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier1, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, y)); + } + function d3_svg_lineSlope(p0, p1) { + return (p1[1] - p0[1]) / (p1[0] - p0[0]); + } + function d3_svg_lineFiniteDifferences(points) { + var i = 0, j = points.length - 1, m = [], p0 = points[0], p1 = points[1], d = m[0] = d3_svg_lineSlope(p0, p1); + while (++i < j) { + m[i] = (d + (d = d3_svg_lineSlope(p0 = p1, p1 = points[i + 1]))) / 2; + } + m[i] = d; + return m; + } + function d3_svg_lineMonotoneTangents(points) { + var tangents = [], d, a, b, s, m = d3_svg_lineFiniteDifferences(points), i = -1, j = points.length - 1; + while (++i < j) { + d = d3_svg_lineSlope(points[i], points[i + 1]); + if (abs(d) < ε) { + m[i] = m[i + 1] = 0; + } else { + a = m[i] / d; + b = m[i + 1] / d; + s = a * a + b * b; + if (s > 9) { + s = d * 3 / Math.sqrt(s); + m[i] = s * a; + m[i + 1] = s * b; + } + } + } + i = -1; + while (++i <= j) { + s = (points[Math.min(j, i + 1)][0] - points[Math.max(0, i - 1)][0]) / (6 * (1 + m[i] * m[i])); + tangents.push([ s || 0, m[i] * s || 0 ]); + } + return tangents; + } + function d3_svg_lineMonotone(points) { + return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineMonotoneTangents(points)); + } + d3.svg.line.radial = function() { + var line = d3_svg_line(d3_svg_lineRadial); + line.radius = line.x, delete line.x; + line.angle = line.y, delete line.y; + return line; + }; + function d3_svg_lineRadial(points) { + var point, i = -1, n = points.length, r, a; + while (++i < n) { + point = points[i]; + r = point[0]; + a = point[1] + d3_svg_arcOffset; + point[0] = r * Math.cos(a); + point[1] = r * Math.sin(a); + } + return points; + } + function d3_svg_area(projection) { + var x0 = d3_geom_pointX, x1 = d3_geom_pointX, y0 = 0, y1 = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, interpolateReverse = interpolate, L = "L", tension = .7; + function area(data) { + var segments = [], points0 = [], points1 = [], i = -1, n = data.length, d, fx0 = d3_functor(x0), fy0 = d3_functor(y0), fx1 = x0 === x1 ? function() { + return x; + } : d3_functor(x1), fy1 = y0 === y1 ? function() { + return y; + } : d3_functor(y1), x, y; + function segment() { + segments.push("M", interpolate(projection(points1), tension), L, interpolateReverse(projection(points0.reverse()), tension), "Z"); + } + while (++i < n) { + if (defined.call(this, d = data[i], i)) { + points0.push([ x = +fx0.call(this, d, i), y = +fy0.call(this, d, i) ]); + points1.push([ +fx1.call(this, d, i), +fy1.call(this, d, i) ]); + } else if (points0.length) { + segment(); + points0 = []; + points1 = []; + } + } + if (points0.length) segment(); + return segments.length ? segments.join("") : null; + } + area.x = function(_) { + if (!arguments.length) return x1; + x0 = x1 = _; + return area; + }; + area.x0 = function(_) { + if (!arguments.length) return x0; + x0 = _; + return area; + }; + area.x1 = function(_) { + if (!arguments.length) return x1; + x1 = _; + return area; + }; + area.y = function(_) { + if (!arguments.length) return y1; + y0 = y1 = _; + return area; + }; + area.y0 = function(_) { + if (!arguments.length) return y0; + y0 = _; + return area; + }; + area.y1 = function(_) { + if (!arguments.length) return y1; + y1 = _; + return area; + }; + area.defined = function(_) { + if (!arguments.length) return defined; + defined = _; + return area; + }; + area.interpolate = function(_) { + if (!arguments.length) return interpolateKey; + if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key; + interpolateReverse = interpolate.reverse || interpolate; + L = interpolate.closed ? "M" : "L"; + return area; + }; + area.tension = function(_) { + if (!arguments.length) return tension; + tension = _; + return area; + }; + return area; + } + d3_svg_lineStepBefore.reverse = d3_svg_lineStepAfter; + d3_svg_lineStepAfter.reverse = d3_svg_lineStepBefore; + d3.svg.area = function() { + return d3_svg_area(d3_identity); + }; + d3.svg.area.radial = function() { + var area = d3_svg_area(d3_svg_lineRadial); + area.radius = area.x, delete area.x; + area.innerRadius = area.x0, delete area.x0; + area.outerRadius = area.x1, delete area.x1; + area.angle = area.y, delete area.y; + area.startAngle = area.y0, delete area.y0; + area.endAngle = area.y1, delete area.y1; + return area; + }; + d3.svg.chord = function() { + var source = d3_source, target = d3_target, radius = d3_svg_chordRadius, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle; + function chord(d, i) { + var s = subgroup(this, source, d, i), t = subgroup(this, target, d, i); + return "M" + s.p0 + arc(s.r, s.p1, s.a1 - s.a0) + (equals(s, t) ? curve(s.r, s.p1, s.r, s.p0) : curve(s.r, s.p1, t.r, t.p0) + arc(t.r, t.p1, t.a1 - t.a0) + curve(t.r, t.p1, s.r, s.p0)) + "Z"; + } + function subgroup(self, f, d, i) { + var subgroup = f.call(self, d, i), r = radius.call(self, subgroup, i), a0 = startAngle.call(self, subgroup, i) + d3_svg_arcOffset, a1 = endAngle.call(self, subgroup, i) + d3_svg_arcOffset; + return { + r: r, + a0: a0, + a1: a1, + p0: [ r * Math.cos(a0), r * Math.sin(a0) ], + p1: [ r * Math.cos(a1), r * Math.sin(a1) ] + }; + } + function equals(a, b) { + return a.a0 == b.a0 && a.a1 == b.a1; + } + function arc(r, p, a) { + return "A" + r + "," + r + " 0 " + +(a > π) + ",1 " + p; + } + function curve(r0, p0, r1, p1) { + return "Q 0,0 " + p1; + } + chord.radius = function(v) { + if (!arguments.length) return radius; + radius = d3_functor(v); + return chord; + }; + chord.source = function(v) { + if (!arguments.length) return source; + source = d3_functor(v); + return chord; + }; + chord.target = function(v) { + if (!arguments.length) return target; + target = d3_functor(v); + return chord; + }; + chord.startAngle = function(v) { + if (!arguments.length) return startAngle; + startAngle = d3_functor(v); + return chord; + }; + chord.endAngle = function(v) { + if (!arguments.length) return endAngle; + endAngle = d3_functor(v); + return chord; + }; + return chord; + }; + function d3_svg_chordRadius(d) { + return d.radius; + } + d3.svg.diagonal = function() { + var source = d3_source, target = d3_target, projection = d3_svg_diagonalProjection; + function diagonal(d, i) { + var p0 = source.call(this, d, i), p3 = target.call(this, d, i), m = (p0.y + p3.y) / 2, p = [ p0, { + x: p0.x, + y: m + }, { + x: p3.x, + y: m + }, p3 ]; + p = p.map(projection); + return "M" + p[0] + "C" + p[1] + " " + p[2] + " " + p[3]; + } + diagonal.source = function(x) { + if (!arguments.length) return source; + source = d3_functor(x); + return diagonal; + }; + diagonal.target = function(x) { + if (!arguments.length) return target; + target = d3_functor(x); + return diagonal; + }; + diagonal.projection = function(x) { + if (!arguments.length) return projection; + projection = x; + return diagonal; + }; + return diagonal; + }; + function d3_svg_diagonalProjection(d) { + return [ d.x, d.y ]; + } + d3.svg.diagonal.radial = function() { + var diagonal = d3.svg.diagonal(), projection = d3_svg_diagonalProjection, projection_ = diagonal.projection; + diagonal.projection = function(x) { + return arguments.length ? projection_(d3_svg_diagonalRadialProjection(projection = x)) : projection; + }; + return diagonal; + }; + function d3_svg_diagonalRadialProjection(projection) { + return function() { + var d = projection.apply(this, arguments), r = d[0], a = d[1] + d3_svg_arcOffset; + return [ r * Math.cos(a), r * Math.sin(a) ]; + }; + } + d3.svg.symbol = function() { + var type = d3_svg_symbolType, size = d3_svg_symbolSize; + function symbol(d, i) { + return (d3_svg_symbols.get(type.call(this, d, i)) || d3_svg_symbolCircle)(size.call(this, d, i)); + } + symbol.type = function(x) { + if (!arguments.length) return type; + type = d3_functor(x); + return symbol; + }; + symbol.size = function(x) { + if (!arguments.length) return size; + size = d3_functor(x); + return symbol; + }; + return symbol; + }; + function d3_svg_symbolSize() { + return 64; + } + function d3_svg_symbolType() { + return "circle"; + } + function d3_svg_symbolCircle(size) { + var r = Math.sqrt(size / π); + return "M0," + r + "A" + r + "," + r + " 0 1,1 0," + -r + "A" + r + "," + r + " 0 1,1 0," + r + "Z"; + } + var d3_svg_symbols = d3.map({ + circle: d3_svg_symbolCircle, + cross: function(size) { + var r = Math.sqrt(size / 5) / 2; + return "M" + -3 * r + "," + -r + "H" + -r + "V" + -3 * r + "H" + r + "V" + -r + "H" + 3 * r + "V" + r + "H" + r + "V" + 3 * r + "H" + -r + "V" + r + "H" + -3 * r + "Z"; + }, + diamond: function(size) { + var ry = Math.sqrt(size / (2 * d3_svg_symbolTan30)), rx = ry * d3_svg_symbolTan30; + return "M0," + -ry + "L" + rx + ",0" + " 0," + ry + " " + -rx + ",0" + "Z"; + }, + square: function(size) { + var r = Math.sqrt(size) / 2; + return "M" + -r + "," + -r + "L" + r + "," + -r + " " + r + "," + r + " " + -r + "," + r + "Z"; + }, + "triangle-down": function(size) { + var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2; + return "M0," + ry + "L" + rx + "," + -ry + " " + -rx + "," + -ry + "Z"; + }, + "triangle-up": function(size) { + var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2; + return "M0," + -ry + "L" + rx + "," + ry + " " + -rx + "," + ry + "Z"; + } + }); + d3.svg.symbolTypes = d3_svg_symbols.keys(); + var d3_svg_symbolSqrt3 = Math.sqrt(3), d3_svg_symbolTan30 = Math.tan(30 * d3_radians); + function d3_transition(groups, id) { + d3_subclass(groups, d3_transitionPrototype); + groups.id = id; + return groups; + } + var d3_transitionPrototype = [], d3_transitionId = 0, d3_transitionInheritId, d3_transitionInherit; + d3_transitionPrototype.call = d3_selectionPrototype.call; + d3_transitionPrototype.empty = d3_selectionPrototype.empty; + d3_transitionPrototype.node = d3_selectionPrototype.node; + d3_transitionPrototype.size = d3_selectionPrototype.size; + d3.transition = function(selection) { + return arguments.length ? d3_transitionInheritId ? selection.transition() : selection : d3_selectionRoot.transition(); + }; + d3.transition.prototype = d3_transitionPrototype; + d3_transitionPrototype.select = function(selector) { + var id = this.id, subgroups = [], subgroup, subnode, node; + selector = d3_selection_selector(selector); + for (var j = -1, m = this.length; ++j < m; ) { + subgroups.push(subgroup = []); + for (var group = this[j], i = -1, n = group.length; ++i < n; ) { + if ((node = group[i]) && (subnode = selector.call(node, node.__data__, i, j))) { + if ("__data__" in node) subnode.__data__ = node.__data__; + d3_transitionNode(subnode, i, id, node.__transition__[id]); + subgroup.push(subnode); + } else { + subgroup.push(null); + } + } + } + return d3_transition(subgroups, id); + }; + d3_transitionPrototype.selectAll = function(selector) { + var id = this.id, subgroups = [], subgroup, subnodes, node, subnode, transition; + selector = d3_selection_selectorAll(selector); + for (var j = -1, m = this.length; ++j < m; ) { + for (var group = this[j], i = -1, n = group.length; ++i < n; ) { + if (node = group[i]) { + transition = node.__transition__[id]; + subnodes = selector.call(node, node.__data__, i, j); + subgroups.push(subgroup = []); + for (var k = -1, o = subnodes.length; ++k < o; ) { + if (subnode = subnodes[k]) d3_transitionNode(subnode, k, id, transition); + subgroup.push(subnode); + } + } + } + } + return d3_transition(subgroups, id); + }; + d3_transitionPrototype.filter = function(filter) { + var subgroups = [], subgroup, group, node; + if (typeof filter !== "function") filter = d3_selection_filter(filter); + for (var j = 0, m = this.length; j < m; j++) { + subgroups.push(subgroup = []); + for (var group = this[j], i = 0, n = group.length; i < n; i++) { + if ((node = group[i]) && filter.call(node, node.__data__, i, j)) { + subgroup.push(node); + } + } + } + return d3_transition(subgroups, this.id); + }; + d3_transitionPrototype.tween = function(name, tween) { + var id = this.id; + if (arguments.length < 2) return this.node().__transition__[id].tween.get(name); + return d3_selection_each(this, tween == null ? function(node) { + node.__transition__[id].tween.remove(name); + } : function(node) { + node.__transition__[id].tween.set(name, tween); + }); + }; + function d3_transition_tween(groups, name, value, tween) { + var id = groups.id; + return d3_selection_each(groups, typeof value === "function" ? function(node, i, j) { + node.__transition__[id].tween.set(name, tween(value.call(node, node.__data__, i, j))); + } : (value = tween(value), function(node) { + node.__transition__[id].tween.set(name, value); + })); + } + d3_transitionPrototype.attr = function(nameNS, value) { + if (arguments.length < 2) { + for (value in nameNS) this.attr(value, nameNS[value]); + return this; + } + var interpolate = nameNS == "transform" ? d3_interpolateTransform : d3_interpolate, name = d3.ns.qualify(nameNS); + function attrNull() { + this.removeAttribute(name); + } + function attrNullNS() { + this.removeAttributeNS(name.space, name.local); + } + function attrTween(b) { + return b == null ? attrNull : (b += "", function() { + var a = this.getAttribute(name), i; + return a !== b && (i = interpolate(a, b), function(t) { + this.setAttribute(name, i(t)); + }); + }); + } + function attrTweenNS(b) { + return b == null ? attrNullNS : (b += "", function() { + var a = this.getAttributeNS(name.space, name.local), i; + return a !== b && (i = interpolate(a, b), function(t) { + this.setAttributeNS(name.space, name.local, i(t)); + }); + }); + } + return d3_transition_tween(this, "attr." + nameNS, value, name.local ? attrTweenNS : attrTween); + }; + d3_transitionPrototype.attrTween = function(nameNS, tween) { + var name = d3.ns.qualify(nameNS); + function attrTween(d, i) { + var f = tween.call(this, d, i, this.getAttribute(name)); + return f && function(t) { + this.setAttribute(name, f(t)); + }; + } + function attrTweenNS(d, i) { + var f = tween.call(this, d, i, this.getAttributeNS(name.space, name.local)); + return f && function(t) { + this.setAttributeNS(name.space, name.local, f(t)); + }; + } + return this.tween("attr." + nameNS, name.local ? attrTweenNS : attrTween); + }; + d3_transitionPrototype.style = function(name, value, priority) { + var n = arguments.length; + if (n < 3) { + if (typeof name !== "string") { + if (n < 2) value = ""; + for (priority in name) this.style(priority, name[priority], value); + return this; + } + priority = ""; + } + function styleNull() { + this.style.removeProperty(name); + } + function styleString(b) { + return b == null ? styleNull : (b += "", function() { + var a = d3_window.getComputedStyle(this, null).getPropertyValue(name), i; + return a !== b && (i = d3_interpolate(a, b), function(t) { + this.style.setProperty(name, i(t), priority); + }); + }); + } + return d3_transition_tween(this, "style." + name, value, styleString); + }; + d3_transitionPrototype.styleTween = function(name, tween, priority) { + if (arguments.length < 3) priority = ""; + function styleTween(d, i) { + var f = tween.call(this, d, i, d3_window.getComputedStyle(this, null).getPropertyValue(name)); + return f && function(t) { + this.style.setProperty(name, f(t), priority); + }; + } + return this.tween("style." + name, styleTween); + }; + d3_transitionPrototype.text = function(value) { + return d3_transition_tween(this, "text", value, d3_transition_text); + }; + function d3_transition_text(b) { + if (b == null) b = ""; + return function() { + this.textContent = b; + }; + } + d3_transitionPrototype.remove = function() { + return this.each("end.transition", function() { + var p; + if (this.__transition__.count < 2 && (p = this.parentNode)) p.removeChild(this); + }); + }; + d3_transitionPrototype.ease = function(value) { + var id = this.id; + if (arguments.length < 1) return this.node().__transition__[id].ease; + if (typeof value !== "function") value = d3.ease.apply(d3, arguments); + return d3_selection_each(this, function(node) { + node.__transition__[id].ease = value; + }); + }; + d3_transitionPrototype.delay = function(value) { + var id = this.id; + return d3_selection_each(this, typeof value === "function" ? function(node, i, j) { + node.__transition__[id].delay = +value.call(node, node.__data__, i, j); + } : (value = +value, function(node) { + node.__transition__[id].delay = value; + })); + }; + d3_transitionPrototype.duration = function(value) { + var id = this.id; + return d3_selection_each(this, typeof value === "function" ? function(node, i, j) { + node.__transition__[id].duration = Math.max(1, value.call(node, node.__data__, i, j)); + } : (value = Math.max(1, value), function(node) { + node.__transition__[id].duration = value; + })); + }; + d3_transitionPrototype.each = function(type, listener) { + var id = this.id; + if (arguments.length < 2) { + var inherit = d3_transitionInherit, inheritId = d3_transitionInheritId; + d3_transitionInheritId = id; + d3_selection_each(this, function(node, i, j) { + d3_transitionInherit = node.__transition__[id]; + type.call(node, node.__data__, i, j); + }); + d3_transitionInherit = inherit; + d3_transitionInheritId = inheritId; + } else { + d3_selection_each(this, function(node) { + var transition = node.__transition__[id]; + (transition.event || (transition.event = d3.dispatch("start", "end"))).on(type, listener); + }); + } + return this; + }; + d3_transitionPrototype.transition = function() { + var id0 = this.id, id1 = ++d3_transitionId, subgroups = [], subgroup, group, node, transition; + for (var j = 0, m = this.length; j < m; j++) { + subgroups.push(subgroup = []); + for (var group = this[j], i = 0, n = group.length; i < n; i++) { + if (node = group[i]) { + transition = Object.create(node.__transition__[id0]); + transition.delay += transition.duration; + d3_transitionNode(node, i, id1, transition); + } + subgroup.push(node); + } + } + return d3_transition(subgroups, id1); + }; + function d3_transitionNode(node, i, id, inherit) { + var lock = node.__transition__ || (node.__transition__ = { + active: 0, + count: 0 + }), transition = lock[id]; + if (!transition) { + var time = inherit.time; + transition = lock[id] = { + tween: new d3_Map(), + time: time, + ease: inherit.ease, + delay: inherit.delay, + duration: inherit.duration + }; + ++lock.count; + d3.timer(function(elapsed) { + var d = node.__data__, ease = transition.ease, delay = transition.delay, duration = transition.duration, timer = d3_timer_active, tweened = []; + timer.t = delay + time; + if (delay <= elapsed) return start(elapsed - delay); + timer.c = start; + function start(elapsed) { + if (lock.active > id) return stop(); + lock.active = id; + transition.event && transition.event.start.call(node, d, i); + transition.tween.forEach(function(key, value) { + if (value = value.call(node, d, i)) { + tweened.push(value); + } + }); + d3.timer(function() { + timer.c = tick(elapsed || 1) ? d3_true : tick; + return 1; + }, 0, time); + } + function tick(elapsed) { + if (lock.active !== id) return stop(); + var t = elapsed / duration, e = ease(t), n = tweened.length; + while (n > 0) { + tweened[--n].call(node, e); + } + if (t >= 1) { + transition.event && transition.event.end.call(node, d, i); + return stop(); + } + } + function stop() { + if (--lock.count) delete lock[id]; else delete node.__transition__; + return 1; + } + }, 0, time); + } + } + d3.svg.axis = function() { + var scale = d3.scale.linear(), orient = d3_svg_axisDefaultOrient, innerTickSize = 6, outerTickSize = 6, tickPadding = 3, tickArguments_ = [ 10 ], tickValues = null, tickFormat_; + function axis(g) { + g.each(function() { + var g = d3.select(this); + var scale0 = this.__chart__ || scale, scale1 = this.__chart__ = scale.copy(); + var ticks = tickValues == null ? scale1.ticks ? scale1.ticks.apply(scale1, tickArguments_) : scale1.domain() : tickValues, tickFormat = tickFormat_ == null ? scale1.tickFormat ? scale1.tickFormat.apply(scale1, tickArguments_) : d3_identity : tickFormat_, tick = g.selectAll(".tick").data(ticks, scale1), tickEnter = tick.enter().insert("g", ".domain").attr("class", "tick").style("opacity", ε), tickExit = d3.transition(tick.exit()).style("opacity", ε).remove(), tickUpdate = d3.transition(tick).style("opacity", 1), tickTransform; + var range = d3_scaleRange(scale1), path = g.selectAll(".domain").data([ 0 ]), pathUpdate = (path.enter().append("path").attr("class", "domain"), + d3.transition(path)); + tickEnter.append("line"); + tickEnter.append("text"); + var lineEnter = tickEnter.select("line"), lineUpdate = tickUpdate.select("line"), text = tick.select("text").text(tickFormat), textEnter = tickEnter.select("text"), textUpdate = tickUpdate.select("text"); + switch (orient) { + case "bottom": + { + tickTransform = d3_svg_axisX; + lineEnter.attr("y2", innerTickSize); + textEnter.attr("y", Math.max(innerTickSize, 0) + tickPadding); + lineUpdate.attr("x2", 0).attr("y2", innerTickSize); + textUpdate.attr("x", 0).attr("y", Math.max(innerTickSize, 0) + tickPadding); + text.attr("dy", ".71em").style("text-anchor", "middle"); + pathUpdate.attr("d", "M" + range[0] + "," + outerTickSize + "V0H" + range[1] + "V" + outerTickSize); + break; + } + + case "top": + { + tickTransform = d3_svg_axisX; + lineEnter.attr("y2", -innerTickSize); + textEnter.attr("y", -(Math.max(innerTickSize, 0) + tickPadding)); + lineUpdate.attr("x2", 0).attr("y2", -innerTickSize); + textUpdate.attr("x", 0).attr("y", -(Math.max(innerTickSize, 0) + tickPadding)); + text.attr("dy", "0em").style("text-anchor", "middle"); + pathUpdate.attr("d", "M" + range[0] + "," + -outerTickSize + "V0H" + range[1] + "V" + -outerTickSize); + break; + } + + case "left": + { + tickTransform = d3_svg_axisY; + lineEnter.attr("x2", -innerTickSize); + textEnter.attr("x", -(Math.max(innerTickSize, 0) + tickPadding)); + lineUpdate.attr("x2", -innerTickSize).attr("y2", 0); + textUpdate.attr("x", -(Math.max(innerTickSize, 0) + tickPadding)).attr("y", 0); + text.attr("dy", ".32em").style("text-anchor", "end"); + pathUpdate.attr("d", "M" + -outerTickSize + "," + range[0] + "H0V" + range[1] + "H" + -outerTickSize); + break; + } + + case "right": + { + tickTransform = d3_svg_axisY; + lineEnter.attr("x2", innerTickSize); + textEnter.attr("x", Math.max(innerTickSize, 0) + tickPadding); + lineUpdate.attr("x2", innerTickSize).attr("y2", 0); + textUpdate.attr("x", Math.max(innerTickSize, 0) + tickPadding).attr("y", 0); + text.attr("dy", ".32em").style("text-anchor", "start"); + pathUpdate.attr("d", "M" + outerTickSize + "," + range[0] + "H0V" + range[1] + "H" + outerTickSize); + break; + } + } + if (scale1.rangeBand) { + var x = scale1, dx = x.rangeBand() / 2; + scale0 = scale1 = function(d) { + return x(d) + dx; + }; + } else if (scale0.rangeBand) { + scale0 = scale1; + } else { + tickExit.call(tickTransform, scale1); + } + tickEnter.call(tickTransform, scale0); + tickUpdate.call(tickTransform, scale1); + }); + } + axis.scale = function(x) { + if (!arguments.length) return scale; + scale = x; + return axis; + }; + axis.orient = function(x) { + if (!arguments.length) return orient; + orient = x in d3_svg_axisOrients ? x + "" : d3_svg_axisDefaultOrient; + return axis; + }; + axis.ticks = function() { + if (!arguments.length) return tickArguments_; + tickArguments_ = arguments; + return axis; + }; + axis.tickValues = function(x) { + if (!arguments.length) return tickValues; + tickValues = x; + return axis; + }; + axis.tickFormat = function(x) { + if (!arguments.length) return tickFormat_; + tickFormat_ = x; + return axis; + }; + axis.tickSize = function(x) { + var n = arguments.length; + if (!n) return innerTickSize; + innerTickSize = +x; + outerTickSize = +arguments[n - 1]; + return axis; + }; + axis.innerTickSize = function(x) { + if (!arguments.length) return innerTickSize; + innerTickSize = +x; + return axis; + }; + axis.outerTickSize = function(x) { + if (!arguments.length) return outerTickSize; + outerTickSize = +x; + return axis; + }; + axis.tickPadding = function(x) { + if (!arguments.length) return tickPadding; + tickPadding = +x; + return axis; + }; + axis.tickSubdivide = function() { + return arguments.length && axis; + }; + return axis; + }; + var d3_svg_axisDefaultOrient = "bottom", d3_svg_axisOrients = { + top: 1, + right: 1, + bottom: 1, + left: 1 + }; + function d3_svg_axisX(selection, x) { + selection.attr("transform", function(d) { + return "translate(" + x(d) + ",0)"; + }); + } + function d3_svg_axisY(selection, y) { + selection.attr("transform", function(d) { + return "translate(0," + y(d) + ")"; + }); + } + d3.svg.brush = function() { + var event = d3_eventDispatch(brush, "brushstart", "brush", "brushend"), x = null, y = null, xExtent = [ 0, 0 ], yExtent = [ 0, 0 ], xExtentDomain, yExtentDomain, xClamp = true, yClamp = true, resizes = d3_svg_brushResizes[0]; + function brush(g) { + g.each(function() { + var g = d3.select(this).style("pointer-events", "all").style("-webkit-tap-highlight-color", "rgba(0,0,0,0)").on("mousedown.brush", brushstart).on("touchstart.brush", brushstart); + var background = g.selectAll(".background").data([ 0 ]); + background.enter().append("rect").attr("class", "background").style("visibility", "hidden").style("cursor", "crosshair"); + g.selectAll(".extent").data([ 0 ]).enter().append("rect").attr("class", "extent").style("cursor", "move"); + var resize = g.selectAll(".resize").data(resizes, d3_identity); + resize.exit().remove(); + resize.enter().append("g").attr("class", function(d) { + return "resize " + d; + }).style("cursor", function(d) { + return d3_svg_brushCursor[d]; + }).append("rect").attr("x", function(d) { + return /[ew]$/.test(d) ? -3 : null; + }).attr("y", function(d) { + return /^[ns]/.test(d) ? -3 : null; + }).attr("width", 6).attr("height", 6).style("visibility", "hidden"); + resize.style("display", brush.empty() ? "none" : null); + var gUpdate = d3.transition(g), backgroundUpdate = d3.transition(background), range; + if (x) { + range = d3_scaleRange(x); + backgroundUpdate.attr("x", range[0]).attr("width", range[1] - range[0]); + redrawX(gUpdate); + } + if (y) { + range = d3_scaleRange(y); + backgroundUpdate.attr("y", range[0]).attr("height", range[1] - range[0]); + redrawY(gUpdate); + } + redraw(gUpdate); + }); + } + brush.event = function(g) { + g.each(function() { + var event_ = event.of(this, arguments), extent1 = { + x: xExtent, + y: yExtent, + i: xExtentDomain, + j: yExtentDomain + }, extent0 = this.__chart__ || extent1; + this.__chart__ = extent1; + if (d3_transitionInheritId) { + d3.select(this).transition().each("start.brush", function() { + xExtentDomain = extent0.i; + yExtentDomain = extent0.j; + xExtent = extent0.x; + yExtent = extent0.y; + event_({ + type: "brushstart" + }); + }).tween("brush:brush", function() { + var xi = d3_interpolateArray(xExtent, extent1.x), yi = d3_interpolateArray(yExtent, extent1.y); + xExtentDomain = yExtentDomain = null; + return function(t) { + xExtent = extent1.x = xi(t); + yExtent = extent1.y = yi(t); + event_({ + type: "brush", + mode: "resize" + }); + }; + }).each("end.brush", function() { + xExtentDomain = extent1.i; + yExtentDomain = extent1.j; + event_({ + type: "brush", + mode: "resize" + }); + event_({ + type: "brushend" + }); + }); + } else { + event_({ + type: "brushstart" + }); + event_({ + type: "brush", + mode: "resize" + }); + event_({ + type: "brushend" + }); + } + }); + }; + function redraw(g) { + g.selectAll(".resize").attr("transform", function(d) { + return "translate(" + xExtent[+/e$/.test(d)] + "," + yExtent[+/^s/.test(d)] + ")"; + }); + } + function redrawX(g) { + g.select(".extent").attr("x", xExtent[0]); + g.selectAll(".extent,.n>rect,.s>rect").attr("width", xExtent[1] - xExtent[0]); + } + function redrawY(g) { + g.select(".extent").attr("y", yExtent[0]); + g.selectAll(".extent,.e>rect,.w>rect").attr("height", yExtent[1] - yExtent[0]); + } + function brushstart() { + var target = this, eventTarget = d3.select(d3.event.target), event_ = event.of(target, arguments), g = d3.select(target), resizing = eventTarget.datum(), resizingX = !/^(n|s)$/.test(resizing) && x, resizingY = !/^(e|w)$/.test(resizing) && y, dragging = eventTarget.classed("extent"), dragRestore = d3_event_dragSuppress(), center, origin = d3.mouse(target), offset; + var w = d3.select(d3_window).on("keydown.brush", keydown).on("keyup.brush", keyup); + if (d3.event.changedTouches) { + w.on("touchmove.brush", brushmove).on("touchend.brush", brushend); + } else { + w.on("mousemove.brush", brushmove).on("mouseup.brush", brushend); + } + g.interrupt().selectAll("*").interrupt(); + if (dragging) { + origin[0] = xExtent[0] - origin[0]; + origin[1] = yExtent[0] - origin[1]; + } else if (resizing) { + var ex = +/w$/.test(resizing), ey = +/^n/.test(resizing); + offset = [ xExtent[1 - ex] - origin[0], yExtent[1 - ey] - origin[1] ]; + origin[0] = xExtent[ex]; + origin[1] = yExtent[ey]; + } else if (d3.event.altKey) center = origin.slice(); + g.style("pointer-events", "none").selectAll(".resize").style("display", null); + d3.select("body").style("cursor", eventTarget.style("cursor")); + event_({ + type: "brushstart" + }); + brushmove(); + function keydown() { + if (d3.event.keyCode == 32) { + if (!dragging) { + center = null; + origin[0] -= xExtent[1]; + origin[1] -= yExtent[1]; + dragging = 2; + } + d3_eventPreventDefault(); + } + } + function keyup() { + if (d3.event.keyCode == 32 && dragging == 2) { + origin[0] += xExtent[1]; + origin[1] += yExtent[1]; + dragging = 0; + d3_eventPreventDefault(); + } + } + function brushmove() { + var point = d3.mouse(target), moved = false; + if (offset) { + point[0] += offset[0]; + point[1] += offset[1]; + } + if (!dragging) { + if (d3.event.altKey) { + if (!center) center = [ (xExtent[0] + xExtent[1]) / 2, (yExtent[0] + yExtent[1]) / 2 ]; + origin[0] = xExtent[+(point[0] < center[0])]; + origin[1] = yExtent[+(point[1] < center[1])]; + } else center = null; + } + if (resizingX && move1(point, x, 0)) { + redrawX(g); + moved = true; + } + if (resizingY && move1(point, y, 1)) { + redrawY(g); + moved = true; + } + if (moved) { + redraw(g); + event_({ + type: "brush", + mode: dragging ? "move" : "resize" + }); + } + } + function move1(point, scale, i) { + var range = d3_scaleRange(scale), r0 = range[0], r1 = range[1], position = origin[i], extent = i ? yExtent : xExtent, size = extent[1] - extent[0], min, max; + if (dragging) { + r0 -= position; + r1 -= size + position; + } + min = (i ? yClamp : xClamp) ? Math.max(r0, Math.min(r1, point[i])) : point[i]; + if (dragging) { + max = (min += position) + size; + } else { + if (center) position = Math.max(r0, Math.min(r1, 2 * center[i] - min)); + if (position < min) { + max = min; + min = position; + } else { + max = position; + } + } + if (extent[0] != min || extent[1] != max) { + if (i) yExtentDomain = null; else xExtentDomain = null; + extent[0] = min; + extent[1] = max; + return true; + } + } + function brushend() { + brushmove(); + g.style("pointer-events", "all").selectAll(".resize").style("display", brush.empty() ? "none" : null); + d3.select("body").style("cursor", null); + w.on("mousemove.brush", null).on("mouseup.brush", null).on("touchmove.brush", null).on("touchend.brush", null).on("keydown.brush", null).on("keyup.brush", null); + dragRestore(); + event_({ + type: "brushend" + }); + } + } + brush.x = function(z) { + if (!arguments.length) return x; + x = z; + resizes = d3_svg_brushResizes[!x << 1 | !y]; + return brush; + }; + brush.y = function(z) { + if (!arguments.length) return y; + y = z; + resizes = d3_svg_brushResizes[!x << 1 | !y]; + return brush; + }; + brush.clamp = function(z) { + if (!arguments.length) return x && y ? [ xClamp, yClamp ] : x ? xClamp : y ? yClamp : null; + if (x && y) xClamp = !!z[0], yClamp = !!z[1]; else if (x) xClamp = !!z; else if (y) yClamp = !!z; + return brush; + }; + brush.extent = function(z) { + var x0, x1, y0, y1, t; + if (!arguments.length) { + if (x) { + if (xExtentDomain) { + x0 = xExtentDomain[0], x1 = xExtentDomain[1]; + } else { + x0 = xExtent[0], x1 = xExtent[1]; + if (x.invert) x0 = x.invert(x0), x1 = x.invert(x1); + if (x1 < x0) t = x0, x0 = x1, x1 = t; + } + } + if (y) { + if (yExtentDomain) { + y0 = yExtentDomain[0], y1 = yExtentDomain[1]; + } else { + y0 = yExtent[0], y1 = yExtent[1]; + if (y.invert) y0 = y.invert(y0), y1 = y.invert(y1); + if (y1 < y0) t = y0, y0 = y1, y1 = t; + } + } + return x && y ? [ [ x0, y0 ], [ x1, y1 ] ] : x ? [ x0, x1 ] : y && [ y0, y1 ]; + } + if (x) { + x0 = z[0], x1 = z[1]; + if (y) x0 = x0[0], x1 = x1[0]; + xExtentDomain = [ x0, x1 ]; + if (x.invert) x0 = x(x0), x1 = x(x1); + if (x1 < x0) t = x0, x0 = x1, x1 = t; + if (x0 != xExtent[0] || x1 != xExtent[1]) xExtent = [ x0, x1 ]; + } + if (y) { + y0 = z[0], y1 = z[1]; + if (x) y0 = y0[1], y1 = y1[1]; + yExtentDomain = [ y0, y1 ]; + if (y.invert) y0 = y(y0), y1 = y(y1); + if (y1 < y0) t = y0, y0 = y1, y1 = t; + if (y0 != yExtent[0] || y1 != yExtent[1]) yExtent = [ y0, y1 ]; + } + return brush; + }; + brush.clear = function() { + if (!brush.empty()) { + xExtent = [ 0, 0 ], yExtent = [ 0, 0 ]; + xExtentDomain = yExtentDomain = null; + } + return brush; + }; + brush.empty = function() { + return !!x && xExtent[0] == xExtent[1] || !!y && yExtent[0] == yExtent[1]; + }; + return d3.rebind(brush, event, "on"); + }; + var d3_svg_brushCursor = { + n: "ns-resize", + e: "ew-resize", + s: "ns-resize", + w: "ew-resize", + nw: "nwse-resize", + ne: "nesw-resize", + se: "nwse-resize", + sw: "nesw-resize" + }; + var d3_svg_brushResizes = [ [ "n", "e", "s", "w", "nw", "ne", "se", "sw" ], [ "e", "w" ], [ "n", "s" ], [] ]; + var d3_time_format = d3_time.format = d3_locale_enUS.timeFormat; + var d3_time_formatUtc = d3_time_format.utc; + var d3_time_formatIso = d3_time_formatUtc("%Y-%m-%dT%H:%M:%S.%LZ"); + d3_time_format.iso = Date.prototype.toISOString && +new Date("2000-01-01T00:00:00.000Z") ? d3_time_formatIsoNative : d3_time_formatIso; + function d3_time_formatIsoNative(date) { + return date.toISOString(); + } + d3_time_formatIsoNative.parse = function(string) { + var date = new Date(string); + return isNaN(date) ? null : date; + }; + d3_time_formatIsoNative.toString = d3_time_formatIso.toString; + d3_time.second = d3_time_interval(function(date) { + return new d3_date(Math.floor(date / 1e3) * 1e3); + }, function(date, offset) { + date.setTime(date.getTime() + Math.floor(offset) * 1e3); + }, function(date) { + return date.getSeconds(); + }); + d3_time.seconds = d3_time.second.range; + d3_time.seconds.utc = d3_time.second.utc.range; + d3_time.minute = d3_time_interval(function(date) { + return new d3_date(Math.floor(date / 6e4) * 6e4); + }, function(date, offset) { + date.setTime(date.getTime() + Math.floor(offset) * 6e4); + }, function(date) { + return date.getMinutes(); + }); + d3_time.minutes = d3_time.minute.range; + d3_time.minutes.utc = d3_time.minute.utc.range; + d3_time.hour = d3_time_interval(function(date) { + var timezone = date.getTimezoneOffset() / 60; + return new d3_date((Math.floor(date / 36e5 - timezone) + timezone) * 36e5); + }, function(date, offset) { + date.setTime(date.getTime() + Math.floor(offset) * 36e5); + }, function(date) { + return date.getHours(); + }); + d3_time.hours = d3_time.hour.range; + d3_time.hours.utc = d3_time.hour.utc.range; + d3_time.month = d3_time_interval(function(date) { + date = d3_time.day(date); + date.setDate(1); + return date; + }, function(date, offset) { + date.setMonth(date.getMonth() + offset); + }, function(date) { + return date.getMonth(); + }); + d3_time.months = d3_time.month.range; + d3_time.months.utc = d3_time.month.utc.range; + function d3_time_scale(linear, methods, format) { + function scale(x) { + return linear(x); + } + scale.invert = function(x) { + return d3_time_scaleDate(linear.invert(x)); + }; + scale.domain = function(x) { + if (!arguments.length) return linear.domain().map(d3_time_scaleDate); + linear.domain(x); + return scale; + }; + function tickMethod(extent, count) { + var span = extent[1] - extent[0], target = span / count, i = d3.bisect(d3_time_scaleSteps, target); + return i == d3_time_scaleSteps.length ? [ methods.year, d3_scale_linearTickRange(extent.map(function(d) { + return d / 31536e6; + }), count)[2] ] : !i ? [ d3_time_scaleMilliseconds, d3_scale_linearTickRange(extent, count)[2] ] : methods[target / d3_time_scaleSteps[i - 1] < d3_time_scaleSteps[i] / target ? i - 1 : i]; + } + scale.nice = function(interval, skip) { + var domain = scale.domain(), extent = d3_scaleExtent(domain), method = interval == null ? tickMethod(extent, 10) : typeof interval === "number" && tickMethod(extent, interval); + if (method) interval = method[0], skip = method[1]; + function skipped(date) { + return !isNaN(date) && !interval.range(date, d3_time_scaleDate(+date + 1), skip).length; + } + return scale.domain(d3_scale_nice(domain, skip > 1 ? { + floor: function(date) { + while (skipped(date = interval.floor(date))) date = d3_time_scaleDate(date - 1); + return date; + }, + ceil: function(date) { + while (skipped(date = interval.ceil(date))) date = d3_time_scaleDate(+date + 1); + return date; + } + } : interval)); + }; + scale.ticks = function(interval, skip) { + var extent = d3_scaleExtent(scale.domain()), method = interval == null ? tickMethod(extent, 10) : typeof interval === "number" ? tickMethod(extent, interval) : !interval.range && [ { + range: interval + }, skip ]; + if (method) interval = method[0], skip = method[1]; + return interval.range(extent[0], d3_time_scaleDate(+extent[1] + 1), skip < 1 ? 1 : skip); + }; + scale.tickFormat = function() { + return format; + }; + scale.copy = function() { + return d3_time_scale(linear.copy(), methods, format); + }; + return d3_scale_linearRebind(scale, linear); + } + function d3_time_scaleDate(t) { + return new Date(t); + } + var d3_time_scaleSteps = [ 1e3, 5e3, 15e3, 3e4, 6e4, 3e5, 9e5, 18e5, 36e5, 108e5, 216e5, 432e5, 864e5, 1728e5, 6048e5, 2592e6, 7776e6, 31536e6 ]; + var d3_time_scaleLocalMethods = [ [ d3_time.second, 1 ], [ d3_time.second, 5 ], [ d3_time.second, 15 ], [ d3_time.second, 30 ], [ d3_time.minute, 1 ], [ d3_time.minute, 5 ], [ d3_time.minute, 15 ], [ d3_time.minute, 30 ], [ d3_time.hour, 1 ], [ d3_time.hour, 3 ], [ d3_time.hour, 6 ], [ d3_time.hour, 12 ], [ d3_time.day, 1 ], [ d3_time.day, 2 ], [ d3_time.week, 1 ], [ d3_time.month, 1 ], [ d3_time.month, 3 ], [ d3_time.year, 1 ] ]; + var d3_time_scaleLocalFormat = d3_time_format.multi([ [ ".%L", function(d) { + return d.getMilliseconds(); + } ], [ ":%S", function(d) { + return d.getSeconds(); + } ], [ "%I:%M", function(d) { + return d.getMinutes(); + } ], [ "%I %p", function(d) { + return d.getHours(); + } ], [ "%a %d", function(d) { + return d.getDay() && d.getDate() != 1; + } ], [ "%b %d", function(d) { + return d.getDate() != 1; + } ], [ "%B", function(d) { + return d.getMonth(); + } ], [ "%Y", d3_true ] ]); + var d3_time_scaleMilliseconds = { + range: function(start, stop, step) { + return d3.range(+start, +stop, step).map(d3_time_scaleDate); + }, + floor: d3_identity, + ceil: d3_identity + }; + d3_time_scaleLocalMethods.year = d3_time.year; + d3_time.scale = function() { + return d3_time_scale(d3.scale.linear(), d3_time_scaleLocalMethods, d3_time_scaleLocalFormat); + }; + var d3_time_scaleUtcMethods = d3_time_scaleLocalMethods.map(function(m) { + return [ m[0].utc, m[1] ]; + }); + var d3_time_scaleUtcFormat = d3_time_formatUtc.multi([ [ ".%L", function(d) { + return d.getUTCMilliseconds(); + } ], [ ":%S", function(d) { + return d.getUTCSeconds(); + } ], [ "%I:%M", function(d) { + return d.getUTCMinutes(); + } ], [ "%I %p", function(d) { + return d.getUTCHours(); + } ], [ "%a %d", function(d) { + return d.getUTCDay() && d.getUTCDate() != 1; + } ], [ "%b %d", function(d) { + return d.getUTCDate() != 1; + } ], [ "%B", function(d) { + return d.getUTCMonth(); + } ], [ "%Y", d3_true ] ]); + d3_time_scaleUtcMethods.year = d3_time.year.utc; + d3_time.scale.utc = function() { + return d3_time_scale(d3.scale.linear(), d3_time_scaleUtcMethods, d3_time_scaleUtcFormat); + }; + d3.text = d3_xhrType(function(request) { + return request.responseText; + }); + d3.json = function(url, callback) { + return d3_xhr(url, "application/json", d3_json, callback); + }; + function d3_json(request) { + return JSON.parse(request.responseText); + } + d3.html = function(url, callback) { + return d3_xhr(url, "text/html", d3_html, callback); + }; + function d3_html(request) { + var range = d3_document.createRange(); + range.selectNode(d3_document.body); + return range.createContextualFragment(request.responseText); + } + d3.xml = d3_xhrType(function(request) { + return request.responseXML; + }); + if (typeof define === "function" && define.amd) { + define(d3); + } else if (typeof module === "object" && module.exports) { + module.exports = d3; + } else { + this.d3 = d3; + } +}();
\ No newline at end of file diff --git a/devtools/client/shared/vendor/dagre-d3.js b/devtools/client/shared/vendor/dagre-d3.js new file mode 100644 index 000000000..482ce827f --- /dev/null +++ b/devtools/client/shared/vendor/dagre-d3.js @@ -0,0 +1,4560 @@ +;(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ +var global=self;/** + * @license + * Copyright (c) 2012-2013 Chris Pettitt + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +global.dagreD3 = require('./index'); + +},{"./index":2}],2:[function(require,module,exports){ +/** + * @license + * Copyright (c) 2012-2013 Chris Pettitt + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +module.exports = { + Digraph: require('graphlib').Digraph, + Renderer: require('./lib/Renderer'), + json: require('graphlib').converter.json, + layout: require('dagre').layout, + version: require('./lib/version') +}; + +},{"./lib/Renderer":3,"./lib/version":4,"dagre":11,"graphlib":28}],3:[function(require,module,exports){ +var layout = require('dagre').layout; + +var d3; +try { d3 = require('d3'); } catch (_) { d3 = window.d3; } + +module.exports = Renderer; + +function Renderer() { + // Set up defaults... + this._layout = layout(); + + this.drawNodes(defaultDrawNodes); + this.drawEdgeLabels(defaultDrawEdgeLabels); + this.drawEdgePaths(defaultDrawEdgePaths); + this.positionNodes(defaultPositionNodes); + this.positionEdgeLabels(defaultPositionEdgeLabels); + this.positionEdgePaths(defaultPositionEdgePaths); + this.transition(defaultTransition); + this.postLayout(defaultPostLayout); + this.postRender(defaultPostRender); + + this.edgeInterpolate('bundle'); + this.edgeTension(0.95); +} + +Renderer.prototype.layout = function(layout) { + if (!arguments.length) { return this._layout; } + this._layout = layout; + return this; +}; + +Renderer.prototype.drawNodes = function(drawNodes) { + if (!arguments.length) { return this._drawNodes; } + this._drawNodes = bind(drawNodes, this); + return this; +}; + +Renderer.prototype.drawEdgeLabels = function(drawEdgeLabels) { + if (!arguments.length) { return this._drawEdgeLabels; } + this._drawEdgeLabels = bind(drawEdgeLabels, this); + return this; +}; + +Renderer.prototype.drawEdgePaths = function(drawEdgePaths) { + if (!arguments.length) { return this._drawEdgePaths; } + this._drawEdgePaths = bind(drawEdgePaths, this); + return this; +}; + +Renderer.prototype.positionNodes = function(positionNodes) { + if (!arguments.length) { return this._positionNodes; } + this._positionNodes = bind(positionNodes, this); + return this; +}; + +Renderer.prototype.positionEdgeLabels = function(positionEdgeLabels) { + if (!arguments.length) { return this._positionEdgeLabels; } + this._positionEdgeLabels = bind(positionEdgeLabels, this); + return this; +}; + +Renderer.prototype.positionEdgePaths = function(positionEdgePaths) { + if (!arguments.length) { return this._positionEdgePaths; } + this._positionEdgePaths = bind(positionEdgePaths, this); + return this; +}; + +Renderer.prototype.transition = function(transition) { + if (!arguments.length) { return this._transition; } + this._transition = bind(transition, this); + return this; +}; + +Renderer.prototype.postLayout = function(postLayout) { + if (!arguments.length) { return this._postLayout; } + this._postLayout = bind(postLayout, this); + return this; +}; + +Renderer.prototype.postRender = function(postRender) { + if (!arguments.length) { return this._postRender; } + this._postRender = bind(postRender, this); + return this; +}; + +Renderer.prototype.edgeInterpolate = function(edgeInterpolate) { + if (!arguments.length) { return this._edgeInterpolate; } + this._edgeInterpolate = edgeInterpolate; + return this; +}; + +Renderer.prototype.edgeTension = function(edgeTension) { + if (!arguments.length) { return this._edgeTension; } + this._edgeTension = edgeTension; + return this; +}; + +Renderer.prototype.run = function(graph, svg) { + // First copy the input graph so that it is not changed by the rendering + // process. + graph = copyAndInitGraph(graph); + + // Create layers + svg + .selectAll('g.edgePaths, g.edgeLabels, g.nodes') + .data(['edgePaths', 'edgeLabels', 'nodes']) + .enter() + .append('g') + .attr('class', function(d) { return d; }); + + + // Create node and edge roots, attach labels, and capture dimension + // information for use with layout. + var svgNodes = this._drawNodes(graph, svg.select('g.nodes')); + var svgEdgeLabels = this._drawEdgeLabels(graph, svg.select('g.edgeLabels')); + + svgNodes.each(function(u) { calculateDimensions(this, graph.node(u)); }); + svgEdgeLabels.each(function(e) { calculateDimensions(this, graph.edge(e)); }); + + // Now apply the layout function + var result = runLayout(graph, this._layout); + + // Run any user-specified post layout processing + this._postLayout(result, svg); + + var svgEdgePaths = this._drawEdgePaths(graph, svg.select('g.edgePaths')); + + // Apply the layout information to the graph + this._positionNodes(result, svgNodes); + this._positionEdgeLabels(result, svgEdgeLabels); + this._positionEdgePaths(result, svgEdgePaths); + + this._postRender(result, svg); + + return result; +}; + +function copyAndInitGraph(graph) { + var copy = graph.copy(); + + // Init labels if they were not present in the source graph + copy.nodes().forEach(function(u) { + var value = copy.node(u); + if (value === undefined) { + value = {}; + copy.node(u, value); + } + if (!('label' in value)) { value.label = ''; } + }); + + copy.edges().forEach(function(e) { + var value = copy.edge(e); + if (value === undefined) { + value = {}; + copy.edge(e, value); + } + if (!('label' in value)) { value.label = ''; } + }); + + return copy; +} + +function calculateDimensions(group, value) { + var bbox = group.getBBox(); + value.width = bbox.width; + value.height = bbox.height; +} + +function runLayout(graph, layout) { + var result = layout.run(graph); + + // Copy labels to the result graph + graph.eachNode(function(u, value) { result.node(u).label = value.label; }); + graph.eachEdge(function(e, u, v, value) { result.edge(e).label = value.label; }); + + return result; +} + +function defaultDrawNodes(g, root) { + var nodes = g.nodes().filter(function(u) { return !isComposite(g, u); }); + + var svgNodes = root + .selectAll('g.node') + .classed('enter', false) + .data(nodes, function(u) { return u; }); + + svgNodes.selectAll('*').remove(); + + svgNodes + .enter() + .append('g') + .style('opacity', 0) + .attr('class', 'node enter'); + + svgNodes.each(function(u) { addLabel(g.node(u), d3.select(this), 10, 10); }); + + this._transition(svgNodes.exit()) + .style('opacity', 0) + .remove(); + + return svgNodes; +} + +function defaultDrawEdgeLabels(g, root) { + var svgEdgeLabels = root + .selectAll('g.edgeLabel') + .classed('enter', false) + .data(g.edges(), function (e) { return e; }); + + svgEdgeLabels.selectAll('*').remove(); + + svgEdgeLabels + .enter() + .append('g') + .style('opacity', 0) + .attr('class', 'edgeLabel enter'); + + svgEdgeLabels.each(function(e) { addLabel(g.edge(e), d3.select(this), 0, 0); }); + + this._transition(svgEdgeLabels.exit()) + .style('opacity', 0) + .remove(); + + return svgEdgeLabels; +} + +var defaultDrawEdgePaths = function(g, root) { + var svgEdgePaths = root + .selectAll('g.edgePath') + .classed('enter', false) + .data(g.edges(), function(e) { return e; }); + + svgEdgePaths + .enter() + .append('g') + .attr('class', 'edgePath enter') + .append('path') + .style('opacity', 0) + .attr('marker-end', 'url(#arrowhead)'); + + this._transition(svgEdgePaths.exit()) + .style('opacity', 0) + .remove(); + + return svgEdgePaths; +}; + +function defaultPositionNodes(g, svgNodes, svgNodesEnter) { + function transform(u) { + var value = g.node(u); + return 'translate(' + value.x + ',' + value.y + ')'; + } + + // For entering nodes, position immediately without transition + svgNodes.filter('.enter').attr('transform', transform); + + this._transition(svgNodes) + .style('opacity', 1) + .attr('transform', transform); +} + +function defaultPositionEdgeLabels(g, svgEdgeLabels) { + function transform(e) { + var value = g.edge(e); + var point = findMidPoint(value.points); + return 'translate(' + point.x + ',' + point.y + ')'; + } + + // For entering edge labels, position immediately without transition + svgEdgeLabels.filter('.enter').attr('transform', transform); + + this._transition(svgEdgeLabels) + .style('opacity', 1) + .attr('transform', transform); +} + +function defaultPositionEdgePaths(g, svgEdgePaths) { + var interpolate = this._edgeInterpolate, + tension = this._edgeTension; + + function calcPoints(e) { + var value = g.edge(e); + var source = g.node(g.incidentNodes(e)[0]); + var target = g.node(g.incidentNodes(e)[1]); + var points = value.points.slice(); + + var p0 = points.length === 0 ? target : points[0]; + var p1 = points.length === 0 ? source : points[points.length - 1]; + + points.unshift(intersectRect(source, p0)); + // TODO: use bpodgursky's shortening algorithm here + points.push(intersectRect(target, p1)); + + return d3.svg.line() + .x(function(d) { return d.x; }) + .y(function(d) { return d.y; }) + .interpolate(interpolate) + .tension(tension) + (points); + } + + svgEdgePaths.filter('.enter').selectAll('path') + .attr('d', calcPoints); + + this._transition(svgEdgePaths.selectAll('path')) + .attr('d', calcPoints) + .style('opacity', 1); +} + +// By default we do not use transitions +function defaultTransition(selection) { + return selection; +} + +function defaultPostLayout() { + // Do nothing +} + +function defaultPostRender(graph, root) { + if (graph.isDirected() && root.select('#arrowhead').empty()) { + root + .append('svg:defs') + .append('svg:marker') + .attr('id', 'arrowhead') + .attr('viewBox', '0 0 10 10') + .attr('refX', 8) + .attr('refY', 5) + .attr('markerUnits', 'strokewidth') + .attr('markerWidth', 8) + .attr('markerHeight', 5) + .attr('orient', 'auto') + .attr('style', 'fill: #333') + .append('svg:path') + .attr('d', 'M 0 0 L 10 5 L 0 10 z'); + } +} + +function addLabel(node, root, marginX, marginY) { + // Add the rect first so that it appears behind the label + var label = node.label; + var rect = root.append('rect'); + var labelSvg = root.append('g'); + + if (label[0] === '<') { + addForeignObjectLabel(label, labelSvg); + // No margin for HTML elements + marginX = marginY = 0; + } else { + addTextLabel(label, + labelSvg, + Math.floor(node.labelCols), + node.labelCut); + } + + var bbox = root.node().getBBox(); + + labelSvg.attr('transform', + 'translate(' + (-bbox.width / 2) + ',' + (-bbox.height / 2) + ')'); + + rect + .attr('rx', 5) + .attr('ry', 5) + .attr('x', -(bbox.width / 2 + marginX)) + .attr('y', -(bbox.height / 2 + marginY)) + .attr('width', bbox.width + 2 * marginX) + .attr('height', bbox.height + 2 * marginY); +} + +function addForeignObjectLabel(label, root) { + var fo = root + .append('foreignObject') + .attr('width', '100000'); + + var w, h; + fo + .append('xhtml:div') + .style('float', 'left') + // TODO find a better way to get dimensions for foreignObjects... + .html(function() { return label; }) + .each(function() { + w = this.clientWidth; + h = this.clientHeight; + }); + + fo + .attr('width', w) + .attr('height', h); +} + +function addTextLabel(label, root, labelCols, labelCut) { + if (labelCut === undefined) labelCut = "false"; + labelCut = (labelCut.toString().toLowerCase() === "true"); + + var node = root + .append('text') + .attr('text-anchor', 'left'); + + label = label.replace(/\\n/g, "\n"); + + var arr = labelCols ? wordwrap(label, labelCols, labelCut) : label; + arr = arr.split("\n"); + for (var i = 0; i < arr.length; i++) { + node + .append('tspan') + .attr('dy', '1em') + .attr('x', '1') + .text(arr[i]); + } +} + +// Thanks to +// http://james.padolsey.com/javascript/wordwrap-for-javascript/ +function wordwrap (str, width, cut, brk) { + brk = brk || '\n'; + width = width || 75; + cut = cut || false; + + if (!str) { return str; } + + var regex = '.{1,' +width+ '}(\\s|$)' + (cut ? '|.{' +width+ '}|.+$' : '|\\S+?(\\s|$)'); + + return str.match( RegExp(regex, 'g') ).join( brk ); +} + +function findMidPoint(points) { + var midIdx = points.length / 2; + if (points.length % 2) { + return points[Math.floor(midIdx)]; + } else { + var p0 = points[midIdx - 1]; + var p1 = points[midIdx]; + return {x: (p0.x + p1.x) / 2, y: (p0.y + p1.y) / 2}; + } +} + +function intersectRect(rect, point) { + var x = rect.x; + var y = rect.y; + + // For now we only support rectangles + + // Rectangle intersection algorithm from: + // http://math.stackexchange.com/questions/108113/find-edge-between-two-boxes + var dx = point.x - x; + var dy = point.y - y; + var w = rect.width / 2; + var h = rect.height / 2; + + var sx, sy; + if (Math.abs(dy) * w > Math.abs(dx) * h) { + // Intersection is top or bottom of rect. + if (dy < 0) { + h = -h; + } + sx = dy === 0 ? 0 : h * dx / dy; + sy = h; + } else { + // Intersection is left or right of rect. + if (dx < 0) { + w = -w; + } + sx = w; + sy = dx === 0 ? 0 : w * dy / dx; + } + + return {x: x + sx, y: y + sy}; +} + +function isComposite(g, u) { + return 'children' in g && g.children(u).length; +} + +function bind(func, thisArg) { + // For some reason PhantomJS occassionally fails when using the builtin bind, + // so we check if it is available and if not, use a degenerate polyfill. + if (func.bind) { + return func.bind(thisArg); + } + + return function() { + return func.apply(thisArg, arguments); + }; +} + +},{"d3":10,"dagre":11}],4:[function(require,module,exports){ +module.exports = '0.1.5'; + +},{}],5:[function(require,module,exports){ +exports.Set = require('./lib/Set'); +exports.PriorityQueue = require('./lib/PriorityQueue'); +exports.version = require('./lib/version'); + +},{"./lib/PriorityQueue":6,"./lib/Set":7,"./lib/version":9}],6:[function(require,module,exports){ +module.exports = PriorityQueue; + +/** + * A min-priority queue data structure. This algorithm is derived from Cormen, + * et al., "Introduction to Algorithms". The basic idea of a min-priority + * queue is that you can efficiently (in O(1) time) get the smallest key in + * the queue. Adding and removing elements takes O(log n) time. A key can + * have its priority decreased in O(log n) time. + */ +function PriorityQueue() { + this._arr = []; + this._keyIndices = {}; +} + +/** + * Returns the number of elements in the queue. Takes `O(1)` time. + */ +PriorityQueue.prototype.size = function() { + return this._arr.length; +}; + +/** + * Returns the keys that are in the queue. Takes `O(n)` time. + */ +PriorityQueue.prototype.keys = function() { + return this._arr.map(function(x) { return x.key; }); +}; + +/** + * Returns `true` if **key** is in the queue and `false` if not. + */ +PriorityQueue.prototype.has = function(key) { + return key in this._keyIndices; +}; + +/** + * Returns the priority for **key**. If **key** is not present in the queue + * then this function returns `undefined`. Takes `O(1)` time. + * + * @param {Object} key + */ +PriorityQueue.prototype.priority = function(key) { + var index = this._keyIndices[key]; + if (index !== undefined) { + return this._arr[index].priority; + } +}; + +/** + * Returns the key for the minimum element in this queue. If the queue is + * empty this function throws an Error. Takes `O(1)` time. + */ +PriorityQueue.prototype.min = function() { + if (this.size() === 0) { + throw new Error("Queue underflow"); + } + return this._arr[0].key; +}; + +/** + * Inserts a new key into the priority queue. If the key already exists in + * the queue this function returns `false`; otherwise it will return `true`. + * Takes `O(n)` time. + * + * @param {Object} key the key to add + * @param {Number} priority the initial priority for the key + */ +PriorityQueue.prototype.add = function(key, priority) { + var keyIndices = this._keyIndices; + if (!(key in keyIndices)) { + var arr = this._arr; + var index = arr.length; + keyIndices[key] = index; + arr.push({key: key, priority: priority}); + this._decrease(index); + return true; + } + return false; +}; + +/** + * Removes and returns the smallest key in the queue. Takes `O(log n)` time. + */ +PriorityQueue.prototype.removeMin = function() { + this._swap(0, this._arr.length - 1); + var min = this._arr.pop(); + delete this._keyIndices[min.key]; + this._heapify(0); + return min.key; +}; + +/** + * Decreases the priority for **key** to **priority**. If the new priority is + * greater than the previous priority, this function will throw an Error. + * + * @param {Object} key the key for which to raise priority + * @param {Number} priority the new priority for the key + */ +PriorityQueue.prototype.decrease = function(key, priority) { + var index = this._keyIndices[key]; + if (priority > this._arr[index].priority) { + throw new Error("New priority is greater than current priority. " + + "Key: " + key + " Old: " + this._arr[index].priority + " New: " + priority); + } + this._arr[index].priority = priority; + this._decrease(index); +}; + +PriorityQueue.prototype._heapify = function(i) { + var arr = this._arr; + var l = 2 * i, + r = l + 1, + largest = i; + if (l < arr.length) { + largest = arr[l].priority < arr[largest].priority ? l : largest; + if (r < arr.length) { + largest = arr[r].priority < arr[largest].priority ? r : largest; + } + if (largest !== i) { + this._swap(i, largest); + this._heapify(largest); + } + } +}; + +PriorityQueue.prototype._decrease = function(index) { + var arr = this._arr; + var priority = arr[index].priority; + var parent; + while (index !== 0) { + parent = index >> 1; + if (arr[parent].priority < priority) { + break; + } + this._swap(index, parent); + index = parent; + } +}; + +PriorityQueue.prototype._swap = function(i, j) { + var arr = this._arr; + var keyIndices = this._keyIndices; + var origArrI = arr[i]; + var origArrJ = arr[j]; + arr[i] = origArrJ; + arr[j] = origArrI; + keyIndices[origArrJ.key] = i; + keyIndices[origArrI.key] = j; +}; + +},{}],7:[function(require,module,exports){ +var util = require('./util'); + +module.exports = Set; + +/** + * Constructs a new Set with an optional set of `initialKeys`. + * + * It is important to note that keys are coerced to String for most purposes + * with this object, similar to the behavior of JavaScript's Object. For + * example, the following will add only one key: + * + * var s = new Set(); + * s.add(1); + * s.add("1"); + * + * However, the type of the key is preserved internally so that `keys` returns + * the original key set uncoerced. For the above example, `keys` would return + * `[1]`. + */ +function Set(initialKeys) { + this._size = 0; + this._keys = {}; + + if (initialKeys) { + for (var i = 0, il = initialKeys.length; i < il; ++i) { + this.add(initialKeys[i]); + } + } +} + +/** + * Returns a new Set that represents the set intersection of the array of given + * sets. + */ +Set.intersect = function(sets) { + if (sets.length === 0) { + return new Set(); + } + + var result = new Set(!util.isArray(sets[0]) ? sets[0].keys() : sets[0]); + for (var i = 1, il = sets.length; i < il; ++i) { + var resultKeys = result.keys(), + other = !util.isArray(sets[i]) ? sets[i] : new Set(sets[i]); + for (var j = 0, jl = resultKeys.length; j < jl; ++j) { + var key = resultKeys[j]; + if (!other.has(key)) { + result.remove(key); + } + } + } + + return result; +}; + +/** + * Returns a new Set that represents the set union of the array of given sets. + */ +Set.union = function(sets) { + var totalElems = util.reduce(sets, function(lhs, rhs) { + return lhs + (rhs.size ? rhs.size() : rhs.length); + }, 0); + var arr = new Array(totalElems); + + var k = 0; + for (var i = 0, il = sets.length; i < il; ++i) { + var cur = sets[i], + keys = !util.isArray(cur) ? cur.keys() : cur; + for (var j = 0, jl = keys.length; j < jl; ++j) { + arr[k++] = keys[j]; + } + } + + return new Set(arr); +}; + +/** + * Returns the size of this set in `O(1)` time. + */ +Set.prototype.size = function() { + return this._size; +}; + +/** + * Returns the keys in this set. Takes `O(n)` time. + */ +Set.prototype.keys = function() { + return values(this._keys); +}; + +/** + * Tests if a key is present in this Set. Returns `true` if it is and `false` + * if not. Takes `O(1)` time. + */ +Set.prototype.has = function(key) { + return key in this._keys; +}; + +/** + * Adds a new key to this Set if it is not already present. Returns `true` if + * the key was added and `false` if it was already present. Takes `O(1)` time. + */ +Set.prototype.add = function(key) { + if (!(key in this._keys)) { + this._keys[key] = key; + ++this._size; + return true; + } + return false; +}; + +/** + * Removes a key from this Set. If the key was removed this function returns + * `true`. If not, it returns `false`. Takes `O(1)` time. + */ +Set.prototype.remove = function(key) { + if (key in this._keys) { + delete this._keys[key]; + --this._size; + return true; + } + return false; +}; + +/* + * Returns an array of all values for properties of **o**. + */ +function values(o) { + var ks = Object.keys(o), + len = ks.length, + result = new Array(len), + i; + for (i = 0; i < len; ++i) { + result[i] = o[ks[i]]; + } + return result; +} + +},{"./util":8}],8:[function(require,module,exports){ +/* + * This polyfill comes from + * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray + */ +if(!Array.isArray) { + exports.isArray = function (vArg) { + return Object.prototype.toString.call(vArg) === '[object Array]'; + }; +} else { + exports.isArray = Array.isArray; +} + +/* + * Slightly adapted polyfill from + * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce + */ +if ('function' !== typeof Array.prototype.reduce) { + exports.reduce = function(array, callback, opt_initialValue) { + 'use strict'; + if (null === array || 'undefined' === typeof array) { + // At the moment all modern browsers, that support strict mode, have + // native implementation of Array.prototype.reduce. For instance, IE8 + // does not support strict mode, so this check is actually useless. + throw new TypeError( + 'Array.prototype.reduce called on null or undefined'); + } + if ('function' !== typeof callback) { + throw new TypeError(callback + ' is not a function'); + } + var index, value, + length = array.length >>> 0, + isValueSet = false; + if (1 < arguments.length) { + value = opt_initialValue; + isValueSet = true; + } + for (index = 0; length > index; ++index) { + if (array.hasOwnProperty(index)) { + if (isValueSet) { + value = callback(value, array[index], index, array); + } + else { + value = array[index]; + isValueSet = true; + } + } + } + if (!isValueSet) { + throw new TypeError('Reduce of empty array with no initial value'); + } + return value; + }; +} else { + exports.reduce = function(array, callback, opt_initialValue) { + return array.reduce(callback, opt_initialValue); + }; +} + +},{}],9:[function(require,module,exports){ +module.exports = '1.1.3'; + +},{}],10:[function(require,module,exports){ +require("./d3"); +module.exports = d3; +(function () { delete this.d3; })(); // unset global + +},{}],11:[function(require,module,exports){ +/* +Copyright (c) 2012-2013 Chris Pettitt + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +exports.Digraph = require("graphlib").Digraph; +exports.Graph = require("graphlib").Graph; +exports.layout = require("./lib/layout"); +exports.version = require("./lib/version"); + +},{"./lib/layout":12,"./lib/version":27,"graphlib":28}],12:[function(require,module,exports){ +var util = require('./util'), + rank = require('./rank'), + order = require('./order'), + CGraph = require('graphlib').CGraph, + CDigraph = require('graphlib').CDigraph; + +module.exports = function() { + // External configuration + var config = { + // How much debug information to include? + debugLevel: 0, + // Max number of sweeps to perform in order phase + orderMaxSweeps: order.DEFAULT_MAX_SWEEPS, + // Use network simplex algorithm in ranking + rankSimplex: false, + // Rank direction. Valid values are (TB, LR) + rankDir: 'TB' + }; + + // Phase functions + var position = require('./position')(); + + // This layout object + var self = {}; + + self.orderIters = util.propertyAccessor(self, config, 'orderMaxSweeps'); + + self.rankSimplex = util.propertyAccessor(self, config, 'rankSimplex'); + + self.nodeSep = delegateProperty(position.nodeSep); + self.edgeSep = delegateProperty(position.edgeSep); + self.universalSep = delegateProperty(position.universalSep); + self.rankSep = delegateProperty(position.rankSep); + self.rankDir = util.propertyAccessor(self, config, 'rankDir'); + self.debugAlignment = delegateProperty(position.debugAlignment); + + self.debugLevel = util.propertyAccessor(self, config, 'debugLevel', function(x) { + util.log.level = x; + position.debugLevel(x); + }); + + self.run = util.time('Total layout', run); + + self._normalize = normalize; + + return self; + + /* + * Constructs an adjacency graph using the nodes and edges specified through + * config. For each node and edge we add a property `dagre` that contains an + * object that will hold intermediate and final layout information. Some of + * the contents include: + * + * 1) A generated ID that uniquely identifies the object. + * 2) Dimension information for nodes (copied from the source node). + * 3) Optional dimension information for edges. + * + * After the adjacency graph is constructed the code no longer needs to use + * the original nodes and edges passed in via config. + */ + function initLayoutGraph(inputGraph) { + var g = new CDigraph(); + + inputGraph.eachNode(function(u, value) { + if (value === undefined) value = {}; + g.addNode(u, { + width: value.width, + height: value.height + }); + if (value.hasOwnProperty('rank')) { + g.node(u).prefRank = value.rank; + } + }); + + // Set up subgraphs + if (inputGraph.parent) { + inputGraph.nodes().forEach(function(u) { + g.parent(u, inputGraph.parent(u)); + }); + } + + inputGraph.eachEdge(function(e, u, v, value) { + if (value === undefined) value = {}; + var newValue = { + e: e, + minLen: value.minLen || 1, + width: value.width || 0, + height: value.height || 0, + points: [] + }; + + g.addEdge(null, u, v, newValue); + }); + + // Initial graph attributes + var graphValue = inputGraph.graph() || {}; + g.graph({ + rankDir: graphValue.rankDir || config.rankDir, + orderRestarts: graphValue.orderRestarts + }); + + return g; + } + + function run(inputGraph) { + var rankSep = self.rankSep(); + var g; + try { + // Build internal graph + g = util.time('initLayoutGraph', initLayoutGraph)(inputGraph); + + if (g.order() === 0) { + return g; + } + + // Make space for edge labels + g.eachEdge(function(e, s, t, a) { + a.minLen *= 2; + }); + self.rankSep(rankSep / 2); + + // Determine the rank for each node. Nodes with a lower rank will appear + // above nodes of higher rank. + util.time('rank.run', rank.run)(g, config.rankSimplex); + + // Normalize the graph by ensuring that every edge is proper (each edge has + // a length of 1). We achieve this by adding dummy nodes to long edges, + // thus shortening them. + util.time('normalize', normalize)(g); + + // Order the nodes so that edge crossings are minimized. + util.time('order', order)(g, config.orderMaxSweeps); + + // Find the x and y coordinates for every node in the graph. + util.time('position', position.run)(g); + + // De-normalize the graph by removing dummy nodes and augmenting the + // original long edges with coordinate information. + util.time('undoNormalize', undoNormalize)(g); + + // Reverses points for edges that are in a reversed state. + util.time('fixupEdgePoints', fixupEdgePoints)(g); + + // Restore delete edges and reverse edges that were reversed in the rank + // phase. + util.time('rank.restoreEdges', rank.restoreEdges)(g); + + // Construct final result graph and return it + return util.time('createFinalGraph', createFinalGraph)(g, inputGraph.isDirected()); + } finally { + self.rankSep(rankSep); + } + } + + /* + * This function is responsible for 'normalizing' the graph. The process of + * normalization ensures that no edge in the graph has spans more than one + * rank. To do this it inserts dummy nodes as needed and links them by adding + * dummy edges. This function keeps enough information in the dummy nodes and + * edges to ensure that the original graph can be reconstructed later. + * + * This method assumes that the input graph is cycle free. + */ + function normalize(g) { + var dummyCount = 0; + g.eachEdge(function(e, s, t, a) { + var sourceRank = g.node(s).rank; + var targetRank = g.node(t).rank; + if (sourceRank + 1 < targetRank) { + for (var u = s, rank = sourceRank + 1, i = 0; rank < targetRank; ++rank, ++i) { + var v = '_D' + (++dummyCount); + var node = { + width: a.width, + height: a.height, + edge: { id: e, source: s, target: t, attrs: a }, + rank: rank, + dummy: true + }; + + // If this node represents a bend then we will use it as a control + // point. For edges with 2 segments this will be the center dummy + // node. For edges with more than two segments, this will be the + // first and last dummy node. + if (i === 0) node.index = 0; + else if (rank + 1 === targetRank) node.index = 1; + + g.addNode(v, node); + g.addEdge(null, u, v, {}); + u = v; + } + g.addEdge(null, u, t, {}); + g.delEdge(e); + } + }); + } + + /* + * Reconstructs the graph as it was before normalization. The positions of + * dummy nodes are used to build an array of points for the original 'long' + * edge. Dummy nodes and edges are removed. + */ + function undoNormalize(g) { + g.eachNode(function(u, a) { + if (a.dummy) { + if ('index' in a) { + var edge = a.edge; + if (!g.hasEdge(edge.id)) { + g.addEdge(edge.id, edge.source, edge.target, edge.attrs); + } + var points = g.edge(edge.id).points; + points[a.index] = { x: a.x, y: a.y, ul: a.ul, ur: a.ur, dl: a.dl, dr: a.dr }; + } + g.delNode(u); + } + }); + } + + /* + * For each edge that was reversed during the `acyclic` step, reverse its + * array of points. + */ + function fixupEdgePoints(g) { + g.eachEdge(function(e, s, t, a) { if (a.reversed) a.points.reverse(); }); + } + + function createFinalGraph(g, isDirected) { + var out = isDirected ? new CDigraph() : new CGraph(); + out.graph(g.graph()); + g.eachNode(function(u, value) { out.addNode(u, value); }); + g.eachNode(function(u) { out.parent(u, g.parent(u)); }); + g.eachEdge(function(e, u, v, value) { + out.addEdge(value.e, u, v, value); + }); + + // Attach bounding box information + var maxX = 0, maxY = 0; + g.eachNode(function(u, value) { + if (!g.children(u).length) { + maxX = Math.max(maxX, value.x + value.width / 2); + maxY = Math.max(maxY, value.y + value.height / 2); + } + }); + g.eachEdge(function(e, u, v, value) { + var maxXPoints = Math.max.apply(Math, value.points.map(function(p) { return p.x; })); + var maxYPoints = Math.max.apply(Math, value.points.map(function(p) { return p.y; })); + maxX = Math.max(maxX, maxXPoints + value.width / 2); + maxY = Math.max(maxY, maxYPoints + value.height / 2); + }); + out.graph().width = maxX; + out.graph().height = maxY; + + return out; + } + + /* + * Given a function, a new function is returned that invokes the given + * function. The return value from the function is always the `self` object. + */ + function delegateProperty(f) { + return function() { + if (!arguments.length) return f(); + f.apply(null, arguments); + return self; + }; + } +}; + + +},{"./order":13,"./position":18,"./rank":19,"./util":26,"graphlib":28}],13:[function(require,module,exports){ +var util = require('./util'), + crossCount = require('./order/crossCount'), + initLayerGraphs = require('./order/initLayerGraphs'), + initOrder = require('./order/initOrder'), + sortLayer = require('./order/sortLayer'); + +module.exports = order; + +// The maximum number of sweeps to perform before finishing the order phase. +var DEFAULT_MAX_SWEEPS = 24; +order.DEFAULT_MAX_SWEEPS = DEFAULT_MAX_SWEEPS; + +/* + * Runs the order phase with the specified `graph, `maxSweeps`, and + * `debugLevel`. If `maxSweeps` is not specified we use `DEFAULT_MAX_SWEEPS`. + * If `debugLevel` is not set we assume 0. + */ +function order(g, maxSweeps) { + if (arguments.length < 2) { + maxSweeps = DEFAULT_MAX_SWEEPS; + } + + var restarts = g.graph().orderRestarts || 0; + + var layerGraphs = initLayerGraphs(g); + // TODO: remove this when we add back support for ordering clusters + layerGraphs.forEach(function(lg) { + lg = lg.filterNodes(function(u) { return !g.children(u).length; }); + }); + + var iters = 0, + currentBestCC, + allTimeBestCC = Number.MAX_VALUE, + allTimeBest = {}; + + function saveAllTimeBest() { + g.eachNode(function(u, value) { allTimeBest[u] = value.order; }); + } + + for (var j = 0; j < Number(restarts) + 1 && allTimeBestCC !== 0; ++j) { + currentBestCC = Number.MAX_VALUE; + initOrder(g, restarts > 0); + + util.log(2, 'Order phase start cross count: ' + g.graph().orderInitCC); + + var i, lastBest, cc; + for (i = 0, lastBest = 0; lastBest < 4 && i < maxSweeps && currentBestCC > 0; ++i, ++lastBest, ++iters) { + sweep(g, layerGraphs, i); + cc = crossCount(g); + if (cc < currentBestCC) { + lastBest = 0; + currentBestCC = cc; + if (cc < allTimeBestCC) { + saveAllTimeBest(); + allTimeBestCC = cc; + } + } + util.log(3, 'Order phase start ' + j + ' iter ' + i + ' cross count: ' + cc); + } + } + + Object.keys(allTimeBest).forEach(function(u) { + if (!g.children || !g.children(u).length) { + g.node(u).order = allTimeBest[u]; + } + }); + g.graph().orderCC = allTimeBestCC; + + util.log(2, 'Order iterations: ' + iters); + util.log(2, 'Order phase best cross count: ' + g.graph().orderCC); +} + +function predecessorWeights(g, nodes) { + var weights = {}; + nodes.forEach(function(u) { + weights[u] = g.inEdges(u).map(function(e) { + return g.node(g.source(e)).order; + }); + }); + return weights; +} + +function successorWeights(g, nodes) { + var weights = {}; + nodes.forEach(function(u) { + weights[u] = g.outEdges(u).map(function(e) { + return g.node(g.target(e)).order; + }); + }); + return weights; +} + +function sweep(g, layerGraphs, iter) { + if (iter % 2 === 0) { + sweepDown(g, layerGraphs, iter); + } else { + sweepUp(g, layerGraphs, iter); + } +} + +function sweepDown(g, layerGraphs) { + var cg; + for (i = 1; i < layerGraphs.length; ++i) { + cg = sortLayer(layerGraphs[i], cg, predecessorWeights(g, layerGraphs[i].nodes())); + } +} + +function sweepUp(g, layerGraphs) { + var cg; + for (i = layerGraphs.length - 2; i >= 0; --i) { + sortLayer(layerGraphs[i], cg, successorWeights(g, layerGraphs[i].nodes())); + } +} + +},{"./order/crossCount":14,"./order/initLayerGraphs":15,"./order/initOrder":16,"./order/sortLayer":17,"./util":26}],14:[function(require,module,exports){ +var util = require('../util'); + +module.exports = crossCount; + +/* + * Returns the cross count for the given graph. + */ +function crossCount(g) { + var cc = 0; + var ordering = util.ordering(g); + for (var i = 1; i < ordering.length; ++i) { + cc += twoLayerCrossCount(g, ordering[i-1], ordering[i]); + } + return cc; +} + +/* + * This function searches through a ranked and ordered graph and counts the + * number of edges that cross. This algorithm is derived from: + * + * W. Barth et al., Bilayer Cross Counting, JGAA, 8(2) 179–194 (2004) + */ +function twoLayerCrossCount(g, layer1, layer2) { + var indices = []; + layer1.forEach(function(u) { + var nodeIndices = []; + g.outEdges(u).forEach(function(e) { nodeIndices.push(g.node(g.target(e)).order); }); + nodeIndices.sort(function(x, y) { return x - y; }); + indices = indices.concat(nodeIndices); + }); + + var firstIndex = 1; + while (firstIndex < layer2.length) firstIndex <<= 1; + + var treeSize = 2 * firstIndex - 1; + firstIndex -= 1; + + var tree = []; + for (var i = 0; i < treeSize; ++i) { tree[i] = 0; } + + var cc = 0; + indices.forEach(function(i) { + var treeIndex = i + firstIndex; + ++tree[treeIndex]; + while (treeIndex > 0) { + if (treeIndex % 2) { + cc += tree[treeIndex + 1]; + } + treeIndex = (treeIndex - 1) >> 1; + ++tree[treeIndex]; + } + }); + + return cc; +} + +},{"../util":26}],15:[function(require,module,exports){ +var nodesFromList = require('graphlib').filter.nodesFromList, + /* jshint -W079 */ + Set = require('cp-data').Set; + +module.exports = initLayerGraphs; + +/* + * This function takes a compound layered graph, g, and produces an array of + * layer graphs. Each entry in the array represents a subgraph of nodes + * relevant for performing crossing reduction on that layer. + */ +function initLayerGraphs(g) { + var ranks = []; + + function dfs(u) { + if (u === null) { + g.children(u).forEach(function(v) { dfs(v); }); + return; + } + + var value = g.node(u); + value.minRank = ('rank' in value) ? value.rank : Number.MAX_VALUE; + value.maxRank = ('rank' in value) ? value.rank : Number.MIN_VALUE; + var uRanks = new Set(); + g.children(u).forEach(function(v) { + var rs = dfs(v); + uRanks = Set.union([uRanks, rs]); + value.minRank = Math.min(value.minRank, g.node(v).minRank); + value.maxRank = Math.max(value.maxRank, g.node(v).maxRank); + }); + + if ('rank' in value) uRanks.add(value.rank); + + uRanks.keys().forEach(function(r) { + if (!(r in ranks)) ranks[r] = []; + ranks[r].push(u); + }); + + return uRanks; + } + dfs(null); + + var layerGraphs = []; + ranks.forEach(function(us, rank) { + layerGraphs[rank] = g.filterNodes(nodesFromList(us)); + }); + + return layerGraphs; +} + +},{"cp-data":5,"graphlib":28}],16:[function(require,module,exports){ +var crossCount = require('./crossCount'), + util = require('../util'); + +module.exports = initOrder; + +/* + * Given a graph with a set of layered nodes (i.e. nodes that have a `rank` + * attribute) this function attaches an `order` attribute that uniquely + * arranges each node of each rank. If no constraint graph is provided the + * order of the nodes in each rank is entirely arbitrary. + */ +function initOrder(g, random) { + var layers = []; + + g.eachNode(function(u, value) { + var layer = layers[value.rank]; + if (g.children && g.children(u).length > 0) return; + if (!layer) { + layer = layers[value.rank] = []; + } + layer.push(u); + }); + + layers.forEach(function(layer) { + if (random) { + util.shuffle(layer); + } + layer.forEach(function(u, i) { + g.node(u).order = i; + }); + }); + + var cc = crossCount(g); + g.graph().orderInitCC = cc; + g.graph().orderCC = Number.MAX_VALUE; +} + +},{"../util":26,"./crossCount":14}],17:[function(require,module,exports){ +var util = require('../util'); +/* + Digraph = require('graphlib').Digraph, + topsort = require('graphlib').alg.topsort, + nodesFromList = require('graphlib').filter.nodesFromList; +*/ + +module.exports = sortLayer; + +/* +function sortLayer(g, cg, weights) { + var result = sortLayerSubgraph(g, null, cg, weights); + result.list.forEach(function(u, i) { + g.node(u).order = i; + }); + return result.constraintGraph; +} +*/ + +function sortLayer(g, cg, weights) { + var ordering = []; + var bs = {}; + g.eachNode(function(u, value) { + ordering[value.order] = u; + var ws = weights[u]; + if (ws.length) { + bs[u] = util.sum(ws) / ws.length; + } + }); + + var toSort = g.nodes().filter(function(u) { return bs[u] !== undefined; }); + toSort.sort(function(x, y) { + return bs[x] - bs[y] || g.node(x).order - g.node(y).order; + }); + + for (var i = 0, j = 0, jl = toSort.length; j < jl; ++i) { + if (bs[ordering[i]] !== undefined) { + g.node(toSort[j++]).order = i; + } + } +} + +// TOOD: re-enable constrained sorting once we have a strategy for handling +// undefined barycenters. +/* +function sortLayerSubgraph(g, sg, cg, weights) { + cg = cg ? cg.filterNodes(nodesFromList(g.children(sg))) : new Digraph(); + + var nodeData = {}; + g.children(sg).forEach(function(u) { + if (g.children(u).length) { + nodeData[u] = sortLayerSubgraph(g, u, cg, weights); + nodeData[u].firstSG = u; + nodeData[u].lastSG = u; + } else { + var ws = weights[u]; + nodeData[u] = { + degree: ws.length, + barycenter: ws.length > 0 ? util.sum(ws) / ws.length : 0, + list: [u] + }; + } + }); + + resolveViolatedConstraints(g, cg, nodeData); + + var keys = Object.keys(nodeData); + keys.sort(function(x, y) { + return nodeData[x].barycenter - nodeData[y].barycenter; + }); + + var result = keys.map(function(u) { return nodeData[u]; }) + .reduce(function(lhs, rhs) { return mergeNodeData(g, lhs, rhs); }); + return result; +} + +/* +function mergeNodeData(g, lhs, rhs) { + var cg = mergeDigraphs(lhs.constraintGraph, rhs.constraintGraph); + + if (lhs.lastSG !== undefined && rhs.firstSG !== undefined) { + if (cg === undefined) { + cg = new Digraph(); + } + if (!cg.hasNode(lhs.lastSG)) { cg.addNode(lhs.lastSG); } + cg.addNode(rhs.firstSG); + cg.addEdge(null, lhs.lastSG, rhs.firstSG); + } + + return { + degree: lhs.degree + rhs.degree, + barycenter: (lhs.barycenter * lhs.degree + rhs.barycenter * rhs.degree) / + (lhs.degree + rhs.degree), + list: lhs.list.concat(rhs.list), + firstSG: lhs.firstSG !== undefined ? lhs.firstSG : rhs.firstSG, + lastSG: rhs.lastSG !== undefined ? rhs.lastSG : lhs.lastSG, + constraintGraph: cg + }; +} + +function mergeDigraphs(lhs, rhs) { + if (lhs === undefined) return rhs; + if (rhs === undefined) return lhs; + + lhs = lhs.copy(); + rhs.nodes().forEach(function(u) { lhs.addNode(u); }); + rhs.edges().forEach(function(e, u, v) { lhs.addEdge(null, u, v); }); + return lhs; +} + +function resolveViolatedConstraints(g, cg, nodeData) { + // Removes nodes `u` and `v` from `cg` and makes any edges incident on them + // incident on `w` instead. + function collapseNodes(u, v, w) { + // TODO original paper removes self loops, but it is not obvious when this would happen + cg.inEdges(u).forEach(function(e) { + cg.delEdge(e); + cg.addEdge(null, cg.source(e), w); + }); + + cg.outEdges(v).forEach(function(e) { + cg.delEdge(e); + cg.addEdge(null, w, cg.target(e)); + }); + + cg.delNode(u); + cg.delNode(v); + } + + var violated; + while ((violated = findViolatedConstraint(cg, nodeData)) !== undefined) { + var source = cg.source(violated), + target = cg.target(violated); + + var v; + while ((v = cg.addNode(null)) && g.hasNode(v)) { + cg.delNode(v); + } + + // Collapse barycenter and list + nodeData[v] = mergeNodeData(g, nodeData[source], nodeData[target]); + delete nodeData[source]; + delete nodeData[target]; + + collapseNodes(source, target, v); + if (cg.incidentEdges(v).length === 0) { cg.delNode(v); } + } +} + +function findViolatedConstraint(cg, nodeData) { + var us = topsort(cg); + for (var i = 0; i < us.length; ++i) { + var u = us[i]; + var inEdges = cg.inEdges(u); + for (var j = 0; j < inEdges.length; ++j) { + var e = inEdges[j]; + if (nodeData[cg.source(e)].barycenter >= nodeData[u].barycenter) { + return e; + } + } + } +} +*/ + +},{"../util":26}],18:[function(require,module,exports){ +var util = require('./util'); + +/* + * The algorithms here are based on Brandes and Köpf, "Fast and Simple + * Horizontal Coordinate Assignment". + */ +module.exports = function() { + // External configuration + var config = { + nodeSep: 50, + edgeSep: 10, + universalSep: null, + rankSep: 30 + }; + + var self = {}; + + self.nodeSep = util.propertyAccessor(self, config, 'nodeSep'); + self.edgeSep = util.propertyAccessor(self, config, 'edgeSep'); + // If not null this separation value is used for all nodes and edges + // regardless of their widths. `nodeSep` and `edgeSep` are ignored with this + // option. + self.universalSep = util.propertyAccessor(self, config, 'universalSep'); + self.rankSep = util.propertyAccessor(self, config, 'rankSep'); + self.debugLevel = util.propertyAccessor(self, config, 'debugLevel'); + + self.run = run; + + return self; + + function run(g) { + g = g.filterNodes(util.filterNonSubgraphs(g)); + + var layering = util.ordering(g); + + var conflicts = findConflicts(g, layering); + + var xss = {}; + ['u', 'd'].forEach(function(vertDir) { + if (vertDir === 'd') layering.reverse(); + + ['l', 'r'].forEach(function(horizDir) { + if (horizDir === 'r') reverseInnerOrder(layering); + + var dir = vertDir + horizDir; + var align = verticalAlignment(g, layering, conflicts, vertDir === 'u' ? 'predecessors' : 'successors'); + xss[dir]= horizontalCompaction(g, layering, align.pos, align.root, align.align); + + if (config.debugLevel >= 3) + debugPositioning(vertDir + horizDir, g, layering, xss[dir]); + + if (horizDir === 'r') flipHorizontally(xss[dir]); + + if (horizDir === 'r') reverseInnerOrder(layering); + }); + + if (vertDir === 'd') layering.reverse(); + }); + + balance(g, layering, xss); + + g.eachNode(function(v) { + var xs = []; + for (var alignment in xss) { + var alignmentX = xss[alignment][v]; + posXDebug(alignment, g, v, alignmentX); + xs.push(alignmentX); + } + xs.sort(function(x, y) { return x - y; }); + posX(g, v, (xs[1] + xs[2]) / 2); + }); + + // Align y coordinates with ranks + var y = 0, reverseY = g.graph().rankDir === 'BT' || g.graph().rankDir === 'RL'; + layering.forEach(function(layer) { + var maxHeight = util.max(layer.map(function(u) { return height(g, u); })); + y += maxHeight / 2; + layer.forEach(function(u) { + posY(g, u, reverseY ? -y : y); + }); + y += maxHeight / 2 + config.rankSep; + }); + + // Translate layout so that top left corner of bounding rectangle has + // coordinate (0, 0). + var minX = util.min(g.nodes().map(function(u) { return posX(g, u) - width(g, u) / 2; })); + var minY = util.min(g.nodes().map(function(u) { return posY(g, u) - height(g, u) / 2; })); + g.eachNode(function(u) { + posX(g, u, posX(g, u) - minX); + posY(g, u, posY(g, u) - minY); + }); + } + + /* + * Generate an ID that can be used to represent any undirected edge that is + * incident on `u` and `v`. + */ + function undirEdgeId(u, v) { + return u < v + ? u.toString().length + ':' + u + '-' + v + : v.toString().length + ':' + v + '-' + u; + } + + function findConflicts(g, layering) { + var conflicts = {}, // Set of conflicting edge ids + pos = {}, // Position of node in its layer + prevLayer, + currLayer, + k0, // Position of the last inner segment in the previous layer + l, // Current position in the current layer (for iteration up to `l1`) + k1; // Position of the next inner segment in the previous layer or + // the position of the last element in the previous layer + + if (layering.length <= 2) return conflicts; + + function updateConflicts(v) { + var k = pos[v]; + if (k < k0 || k > k1) { + conflicts[undirEdgeId(currLayer[l], v)] = true; + } + } + + layering[1].forEach(function(u, i) { pos[u] = i; }); + for (var i = 1; i < layering.length - 1; ++i) { + prevLayer = layering[i]; + currLayer = layering[i+1]; + k0 = 0; + l = 0; + + // Scan current layer for next node that is incident to an inner segement + // between layering[i+1] and layering[i]. + for (var l1 = 0; l1 < currLayer.length; ++l1) { + var u = currLayer[l1]; // Next inner segment in the current layer or + // last node in the current layer + pos[u] = l1; + k1 = undefined; + + if (g.node(u).dummy) { + var uPred = g.predecessors(u)[0]; + // Note: In the case of self loops and sideways edges it is possible + // for a dummy not to have a predecessor. + if (uPred !== undefined && g.node(uPred).dummy) + k1 = pos[uPred]; + } + if (k1 === undefined && l1 === currLayer.length - 1) + k1 = prevLayer.length - 1; + + if (k1 !== undefined) { + for (; l <= l1; ++l) { + g.predecessors(currLayer[l]).forEach(updateConflicts); + } + k0 = k1; + } + } + } + + return conflicts; + } + + function verticalAlignment(g, layering, conflicts, relationship) { + var pos = {}, // Position for a node in its layer + root = {}, // Root of the block that the node participates in + align = {}; // Points to the next node in the block or, if the last + // element in the block, points to the first block's root + + layering.forEach(function(layer) { + layer.forEach(function(u, i) { + root[u] = u; + align[u] = u; + pos[u] = i; + }); + }); + + layering.forEach(function(layer) { + var prevIdx = -1; + layer.forEach(function(v) { + var related = g[relationship](v), // Adjacent nodes from the previous layer + mid; // The mid point in the related array + + if (related.length > 0) { + related.sort(function(x, y) { return pos[x] - pos[y]; }); + mid = (related.length - 1) / 2; + related.slice(Math.floor(mid), Math.ceil(mid) + 1).forEach(function(u) { + if (align[v] === v) { + if (!conflicts[undirEdgeId(u, v)] && prevIdx < pos[u]) { + align[u] = v; + align[v] = root[v] = root[u]; + prevIdx = pos[u]; + } + } + }); + } + }); + }); + + return { pos: pos, root: root, align: align }; + } + + // This function deviates from the standard BK algorithm in two ways. First + // it takes into account the size of the nodes. Second it includes a fix to + // the original algorithm that is described in Carstens, "Node and Label + // Placement in a Layered Layout Algorithm". + function horizontalCompaction(g, layering, pos, root, align) { + var sink = {}, // Mapping of node id -> sink node id for class + maybeShift = {}, // Mapping of sink node id -> { class node id, min shift } + shift = {}, // Mapping of sink node id -> shift + pred = {}, // Mapping of node id -> predecessor node (or null) + xs = {}; // Calculated X positions + + layering.forEach(function(layer) { + layer.forEach(function(u, i) { + sink[u] = u; + maybeShift[u] = {}; + if (i > 0) + pred[u] = layer[i - 1]; + }); + }); + + function updateShift(toShift, neighbor, delta) { + if (!(neighbor in maybeShift[toShift])) { + maybeShift[toShift][neighbor] = delta; + } else { + maybeShift[toShift][neighbor] = Math.min(maybeShift[toShift][neighbor], delta); + } + } + + function placeBlock(v) { + if (!(v in xs)) { + xs[v] = 0; + var w = v; + do { + if (pos[w] > 0) { + var u = root[pred[w]]; + placeBlock(u); + if (sink[v] === v) { + sink[v] = sink[u]; + } + var delta = sep(g, pred[w]) + sep(g, w); + if (sink[v] !== sink[u]) { + updateShift(sink[u], sink[v], xs[v] - xs[u] - delta); + } else { + xs[v] = Math.max(xs[v], xs[u] + delta); + } + } + w = align[w]; + } while (w !== v); + } + } + + // Root coordinates relative to sink + util.values(root).forEach(function(v) { + placeBlock(v); + }); + + // Absolute coordinates + // There is an assumption here that we've resolved shifts for any classes + // that begin at an earlier layer. We guarantee this by visiting layers in + // order. + layering.forEach(function(layer) { + layer.forEach(function(v) { + xs[v] = xs[root[v]]; + if (v === root[v] && v === sink[v]) { + var minShift = 0; + if (v in maybeShift && Object.keys(maybeShift[v]).length > 0) { + minShift = util.min(Object.keys(maybeShift[v]) + .map(function(u) { + return maybeShift[v][u] + (u in shift ? shift[u] : 0); + } + )); + } + shift[v] = minShift; + } + }); + }); + + layering.forEach(function(layer) { + layer.forEach(function(v) { + xs[v] += shift[sink[root[v]]] || 0; + }); + }); + + return xs; + } + + function findMinCoord(g, layering, xs) { + return util.min(layering.map(function(layer) { + var u = layer[0]; + return xs[u]; + })); + } + + function findMaxCoord(g, layering, xs) { + return util.max(layering.map(function(layer) { + var u = layer[layer.length - 1]; + return xs[u]; + })); + } + + function balance(g, layering, xss) { + var min = {}, // Min coordinate for the alignment + max = {}, // Max coordinate for the alginment + smallestAlignment, + shift = {}; // Amount to shift a given alignment + + function updateAlignment(v) { + xss[alignment][v] += shift[alignment]; + } + + var smallest = Number.POSITIVE_INFINITY; + for (var alignment in xss) { + var xs = xss[alignment]; + min[alignment] = findMinCoord(g, layering, xs); + max[alignment] = findMaxCoord(g, layering, xs); + var w = max[alignment] - min[alignment]; + if (w < smallest) { + smallest = w; + smallestAlignment = alignment; + } + } + + // Determine how much to adjust positioning for each alignment + ['u', 'd'].forEach(function(vertDir) { + ['l', 'r'].forEach(function(horizDir) { + var alignment = vertDir + horizDir; + shift[alignment] = horizDir === 'l' + ? min[smallestAlignment] - min[alignment] + : max[smallestAlignment] - max[alignment]; + }); + }); + + // Find average of medians for xss array + for (alignment in xss) { + g.eachNode(updateAlignment); + } + } + + function flipHorizontally(xs) { + for (var u in xs) { + xs[u] = -xs[u]; + } + } + + function reverseInnerOrder(layering) { + layering.forEach(function(layer) { + layer.reverse(); + }); + } + + function width(g, u) { + switch (g.graph().rankDir) { + case 'LR': return g.node(u).height; + case 'RL': return g.node(u).height; + default: return g.node(u).width; + } + } + + function height(g, u) { + switch(g.graph().rankDir) { + case 'LR': return g.node(u).width; + case 'RL': return g.node(u).width; + default: return g.node(u).height; + } + } + + function sep(g, u) { + if (config.universalSep !== null) { + return config.universalSep; + } + var w = width(g, u); + var s = g.node(u).dummy ? config.edgeSep : config.nodeSep; + return (w + s) / 2; + } + + function posX(g, u, x) { + if (g.graph().rankDir === 'LR' || g.graph().rankDir === 'RL') { + if (arguments.length < 3) { + return g.node(u).y; + } else { + g.node(u).y = x; + } + } else { + if (arguments.length < 3) { + return g.node(u).x; + } else { + g.node(u).x = x; + } + } + } + + function posXDebug(name, g, u, x) { + if (g.graph().rankDir === 'LR' || g.graph().rankDir === 'RL') { + if (arguments.length < 3) { + return g.node(u)[name]; + } else { + g.node(u)[name] = x; + } + } else { + if (arguments.length < 3) { + return g.node(u)[name]; + } else { + g.node(u)[name] = x; + } + } + } + + function posY(g, u, y) { + if (g.graph().rankDir === 'LR' || g.graph().rankDir === 'RL') { + if (arguments.length < 3) { + return g.node(u).x; + } else { + g.node(u).x = y; + } + } else { + if (arguments.length < 3) { + return g.node(u).y; + } else { + g.node(u).y = y; + } + } + } + + function debugPositioning(align, g, layering, xs) { + layering.forEach(function(l, li) { + var u, xU; + l.forEach(function(v) { + var xV = xs[v]; + if (u) { + var s = sep(g, u) + sep(g, v); + if (xV - xU < s) + console.log('Position phase: sep violation. Align: ' + align + '. Layer: ' + li + '. ' + + 'U: ' + u + ' V: ' + v + '. Actual sep: ' + (xV - xU) + ' Expected sep: ' + s); + } + u = v; + xU = xV; + }); + }); + } +}; + +},{"./util":26}],19:[function(require,module,exports){ +var util = require('./util'), + acyclic = require('./rank/acyclic'), + initRank = require('./rank/initRank'), + feasibleTree = require('./rank/feasibleTree'), + constraints = require('./rank/constraints'), + simplex = require('./rank/simplex'), + components = require('graphlib').alg.components, + filter = require('graphlib').filter; + +exports.run = run; +exports.restoreEdges = restoreEdges; + +/* + * Heuristic function that assigns a rank to each node of the input graph with + * the intent of minimizing edge lengths, while respecting the `minLen` + * attribute of incident edges. + * + * Prerequisites: + * + * * Each edge in the input graph must have an assigned 'minLen' attribute + */ +function run(g, useSimplex) { + expandSelfLoops(g); + + // If there are rank constraints on nodes, then build a new graph that + // encodes the constraints. + util.time('constraints.apply', constraints.apply)(g); + + expandSidewaysEdges(g); + + // Reverse edges to get an acyclic graph, we keep the graph in an acyclic + // state until the very end. + util.time('acyclic', acyclic)(g); + + // Convert the graph into a flat graph for ranking + var flatGraph = g.filterNodes(util.filterNonSubgraphs(g)); + + // Assign an initial ranking using DFS. + initRank(flatGraph); + + // For each component improve the assigned ranks. + components(flatGraph).forEach(function(cmpt) { + var subgraph = flatGraph.filterNodes(filter.nodesFromList(cmpt)); + rankComponent(subgraph, useSimplex); + }); + + // Relax original constraints + util.time('constraints.relax', constraints.relax(g)); + + // When handling nodes with constrained ranks it is possible to end up with + // edges that point to previous ranks. Most of the subsequent algorithms assume + // that edges are pointing to successive ranks only. Here we reverse any "back + // edges" and mark them as such. The acyclic algorithm will reverse them as a + // post processing step. + util.time('reorientEdges', reorientEdges)(g); +} + +function restoreEdges(g) { + acyclic.undo(g); +} + +/* + * Expand self loops into three dummy nodes. One will sit above the incident + * node, one will be at the same level, and one below. The result looks like: + * + * /--<--x--->--\ + * node y + * \--<--z--->--/ + * + * Dummy nodes x, y, z give us the shape of a loop and node y is where we place + * the label. + * + * TODO: consolidate knowledge of dummy node construction. + * TODO: support minLen = 2 + */ +function expandSelfLoops(g) { + g.eachEdge(function(e, u, v, a) { + if (u === v) { + var x = addDummyNode(g, e, u, v, a, 0, false), + y = addDummyNode(g, e, u, v, a, 1, true), + z = addDummyNode(g, e, u, v, a, 2, false); + g.addEdge(null, x, u, {minLen: 1, selfLoop: true}); + g.addEdge(null, x, y, {minLen: 1, selfLoop: true}); + g.addEdge(null, u, z, {minLen: 1, selfLoop: true}); + g.addEdge(null, y, z, {minLen: 1, selfLoop: true}); + g.delEdge(e); + } + }); +} + +function expandSidewaysEdges(g) { + g.eachEdge(function(e, u, v, a) { + if (u === v) { + var origEdge = a.originalEdge, + dummy = addDummyNode(g, origEdge.e, origEdge.u, origEdge.v, origEdge.value, 0, true); + g.addEdge(null, u, dummy, {minLen: 1}); + g.addEdge(null, dummy, v, {minLen: 1}); + g.delEdge(e); + } + }); +} + +function addDummyNode(g, e, u, v, a, index, isLabel) { + return g.addNode(null, { + width: isLabel ? a.width : 0, + height: isLabel ? a.height : 0, + edge: { id: e, source: u, target: v, attrs: a }, + dummy: true, + index: index + }); +} + +function reorientEdges(g) { + g.eachEdge(function(e, u, v, value) { + if (g.node(u).rank > g.node(v).rank) { + g.delEdge(e); + value.reversed = true; + g.addEdge(e, v, u, value); + } + }); +} + +function rankComponent(subgraph, useSimplex) { + var spanningTree = feasibleTree(subgraph); + + if (useSimplex) { + util.log(1, 'Using network simplex for ranking'); + simplex(subgraph, spanningTree); + } + normalize(subgraph); +} + +function normalize(g) { + var m = util.min(g.nodes().map(function(u) { return g.node(u).rank; })); + g.eachNode(function(u, node) { node.rank -= m; }); +} + +},{"./rank/acyclic":20,"./rank/constraints":21,"./rank/feasibleTree":22,"./rank/initRank":23,"./rank/simplex":25,"./util":26,"graphlib":28}],20:[function(require,module,exports){ +var util = require('../util'); + +module.exports = acyclic; +module.exports.undo = undo; + +/* + * This function takes a directed graph that may have cycles and reverses edges + * as appropriate to break these cycles. Each reversed edge is assigned a + * `reversed` attribute with the value `true`. + * + * There should be no self loops in the graph. + */ +function acyclic(g) { + var onStack = {}, + visited = {}, + reverseCount = 0; + + function dfs(u) { + if (u in visited) return; + visited[u] = onStack[u] = true; + g.outEdges(u).forEach(function(e) { + var t = g.target(e), + value; + + if (u === t) { + console.error('Warning: found self loop "' + e + '" for node "' + u + '"'); + } else if (t in onStack) { + value = g.edge(e); + g.delEdge(e); + value.reversed = true; + ++reverseCount; + g.addEdge(e, t, u, value); + } else { + dfs(t); + } + }); + + delete onStack[u]; + } + + g.eachNode(function(u) { dfs(u); }); + + util.log(2, 'Acyclic Phase: reversed ' + reverseCount + ' edge(s)'); + + return reverseCount; +} + +/* + * Given a graph that has had the acyclic operation applied, this function + * undoes that operation. More specifically, any edge with the `reversed` + * attribute is again reversed to restore the original direction of the edge. + */ +function undo(g) { + g.eachEdge(function(e, s, t, a) { + if (a.reversed) { + delete a.reversed; + g.delEdge(e); + g.addEdge(e, t, s, a); + } + }); +} + +},{"../util":26}],21:[function(require,module,exports){ +exports.apply = function(g) { + function dfs(sg) { + var rankSets = {}; + g.children(sg).forEach(function(u) { + if (g.children(u).length) { + dfs(u); + return; + } + + var value = g.node(u), + prefRank = value.prefRank; + if (prefRank !== undefined) { + if (!checkSupportedPrefRank(prefRank)) { return; } + + if (!(prefRank in rankSets)) { + rankSets.prefRank = [u]; + } else { + rankSets.prefRank.push(u); + } + + var newU = rankSets[prefRank]; + if (newU === undefined) { + newU = rankSets[prefRank] = g.addNode(null, { originalNodes: [] }); + g.parent(newU, sg); + } + + redirectInEdges(g, u, newU, prefRank === 'min'); + redirectOutEdges(g, u, newU, prefRank === 'max'); + + // Save original node and remove it from reduced graph + g.node(newU).originalNodes.push({ u: u, value: value, parent: sg }); + g.delNode(u); + } + }); + + addLightEdgesFromMinNode(g, sg, rankSets.min); + addLightEdgesToMaxNode(g, sg, rankSets.max); + } + + dfs(null); +}; + +function checkSupportedPrefRank(prefRank) { + if (prefRank !== 'min' && prefRank !== 'max' && prefRank.indexOf('same_') !== 0) { + console.error('Unsupported rank type: ' + prefRank); + return false; + } + return true; +} + +function redirectInEdges(g, u, newU, reverse) { + g.inEdges(u).forEach(function(e) { + var origValue = g.edge(e), + value; + if (origValue.originalEdge) { + value = origValue; + } else { + value = { + originalEdge: { e: e, u: g.source(e), v: g.target(e), value: origValue }, + minLen: g.edge(e).minLen + }; + } + + // Do not reverse edges for self-loops. + if (origValue.selfLoop) { + reverse = false; + } + + if (reverse) { + // Ensure that all edges to min are reversed + g.addEdge(null, newU, g.source(e), value); + value.reversed = true; + } else { + g.addEdge(null, g.source(e), newU, value); + } + }); +} + +function redirectOutEdges(g, u, newU, reverse) { + g.outEdges(u).forEach(function(e) { + var origValue = g.edge(e), + value; + if (origValue.originalEdge) { + value = origValue; + } else { + value = { + originalEdge: { e: e, u: g.source(e), v: g.target(e), value: origValue }, + minLen: g.edge(e).minLen + }; + } + + // Do not reverse edges for self-loops. + if (origValue.selfLoop) { + reverse = false; + } + + if (reverse) { + // Ensure that all edges from max are reversed + g.addEdge(null, g.target(e), newU, value); + value.reversed = true; + } else { + g.addEdge(null, newU, g.target(e), value); + } + }); +} + +function addLightEdgesFromMinNode(g, sg, minNode) { + if (minNode !== undefined) { + g.children(sg).forEach(function(u) { + // The dummy check ensures we don't add an edge if the node is involved + // in a self loop or sideways edge. + if (u !== minNode && !g.outEdges(minNode, u).length && !g.node(u).dummy) { + g.addEdge(null, minNode, u, { minLen: 0 }); + } + }); + } +} + +function addLightEdgesToMaxNode(g, sg, maxNode) { + if (maxNode !== undefined) { + g.children(sg).forEach(function(u) { + // The dummy check ensures we don't add an edge if the node is involved + // in a self loop or sideways edge. + if (u !== maxNode && !g.outEdges(u, maxNode).length && !g.node(u).dummy) { + g.addEdge(null, u, maxNode, { minLen: 0 }); + } + }); + } +} + +/* + * This function "relaxes" the constraints applied previously by the "apply" + * function. It expands any nodes that were collapsed and assigns the rank of + * the collapsed node to each of the expanded nodes. It also restores the + * original edges and removes any dummy edges pointing at the collapsed nodes. + * + * Note that the process of removing collapsed nodes also removes dummy edges + * automatically. + */ +exports.relax = function(g) { + // Save original edges + var originalEdges = []; + g.eachEdge(function(e, u, v, value) { + var originalEdge = value.originalEdge; + if (originalEdge) { + originalEdges.push(originalEdge); + } + }); + + // Expand collapsed nodes + g.eachNode(function(u, value) { + var originalNodes = value.originalNodes; + if (originalNodes) { + originalNodes.forEach(function(originalNode) { + originalNode.value.rank = value.rank; + g.addNode(originalNode.u, originalNode.value); + g.parent(originalNode.u, originalNode.parent); + }); + g.delNode(u); + } + }); + + // Restore original edges + originalEdges.forEach(function(edge) { + g.addEdge(edge.e, edge.u, edge.v, edge.value); + }); +}; + +},{}],22:[function(require,module,exports){ +/* jshint -W079 */ +var Set = require('cp-data').Set, +/* jshint +W079 */ + Digraph = require('graphlib').Digraph, + util = require('../util'); + +module.exports = feasibleTree; + +/* + * Given an acyclic graph with each node assigned a `rank` attribute, this + * function constructs and returns a spanning tree. This function may reduce + * the length of some edges from the initial rank assignment while maintaining + * the `minLen` specified by each edge. + * + * Prerequisites: + * + * * The input graph is acyclic + * * Each node in the input graph has an assigned `rank` attribute + * * Each edge in the input graph has an assigned `minLen` attribute + * + * Outputs: + * + * A feasible spanning tree for the input graph (i.e. a spanning tree that + * respects each graph edge's `minLen` attribute) represented as a Digraph with + * a `root` attribute on graph. + * + * Nodes have the same id and value as that in the input graph. + * + * Edges in the tree have arbitrarily assigned ids. The attributes for edges + * include `reversed`. `reversed` indicates that the edge is a + * back edge in the input graph. + */ +function feasibleTree(g) { + var remaining = new Set(g.nodes()), + tree = new Digraph(); + + if (remaining.size() === 1) { + var root = g.nodes()[0]; + tree.addNode(root, {}); + tree.graph({ root: root }); + return tree; + } + + function addTightEdges(v) { + var continueToScan = true; + g.predecessors(v).forEach(function(u) { + if (remaining.has(u) && !slack(g, u, v)) { + if (remaining.has(v)) { + tree.addNode(v, {}); + remaining.remove(v); + tree.graph({ root: v }); + } + + tree.addNode(u, {}); + tree.addEdge(null, u, v, { reversed: true }); + remaining.remove(u); + addTightEdges(u); + continueToScan = false; + } + }); + + g.successors(v).forEach(function(w) { + if (remaining.has(w) && !slack(g, v, w)) { + if (remaining.has(v)) { + tree.addNode(v, {}); + remaining.remove(v); + tree.graph({ root: v }); + } + + tree.addNode(w, {}); + tree.addEdge(null, v, w, {}); + remaining.remove(w); + addTightEdges(w); + continueToScan = false; + } + }); + return continueToScan; + } + + function createTightEdge() { + var minSlack = Number.MAX_VALUE; + remaining.keys().forEach(function(v) { + g.predecessors(v).forEach(function(u) { + if (!remaining.has(u)) { + var edgeSlack = slack(g, u, v); + if (Math.abs(edgeSlack) < Math.abs(minSlack)) { + minSlack = -edgeSlack; + } + } + }); + + g.successors(v).forEach(function(w) { + if (!remaining.has(w)) { + var edgeSlack = slack(g, v, w); + if (Math.abs(edgeSlack) < Math.abs(minSlack)) { + minSlack = edgeSlack; + } + } + }); + }); + + tree.eachNode(function(u) { g.node(u).rank -= minSlack; }); + } + + while (remaining.size()) { + var nodesToSearch = !tree.order() ? remaining.keys() : tree.nodes(); + for (var i = 0, il = nodesToSearch.length; + i < il && addTightEdges(nodesToSearch[i]); + ++i); + if (remaining.size()) { + createTightEdge(); + } + } + + return tree; +} + +function slack(g, u, v) { + var rankDiff = g.node(v).rank - g.node(u).rank; + var maxMinLen = util.max(g.outEdges(u, v) + .map(function(e) { return g.edge(e).minLen; })); + return rankDiff - maxMinLen; +} + +},{"../util":26,"cp-data":5,"graphlib":28}],23:[function(require,module,exports){ +var util = require('../util'), + topsort = require('graphlib').alg.topsort; + +module.exports = initRank; + +/* + * Assigns a `rank` attribute to each node in the input graph and ensures that + * this rank respects the `minLen` attribute of incident edges. + * + * Prerequisites: + * + * * The input graph must be acyclic + * * Each edge in the input graph must have an assigned 'minLen' attribute + */ +function initRank(g) { + var sorted = topsort(g); + + sorted.forEach(function(u) { + var inEdges = g.inEdges(u); + if (inEdges.length === 0) { + g.node(u).rank = 0; + return; + } + + var minLens = inEdges.map(function(e) { + return g.node(g.source(e)).rank + g.edge(e).minLen; + }); + g.node(u).rank = util.max(minLens); + }); +} + +},{"../util":26,"graphlib":28}],24:[function(require,module,exports){ +module.exports = { + slack: slack +}; + +/* + * A helper to calculate the slack between two nodes (`u` and `v`) given a + * `minLen` constraint. The slack represents how much the distance between `u` + * and `v` could shrink while maintaining the `minLen` constraint. If the value + * is negative then the constraint is currently violated. + * + This function requires that `u` and `v` are in `graph` and they both have a + `rank` attribute. + */ +function slack(graph, u, v, minLen) { + return Math.abs(graph.node(u).rank - graph.node(v).rank) - minLen; +} + +},{}],25:[function(require,module,exports){ +var util = require('../util'), + rankUtil = require('./rankUtil'); + +module.exports = simplex; + +function simplex(graph, spanningTree) { + // The network simplex algorithm repeatedly replaces edges of + // the spanning tree with negative cut values until no such + // edge exists. + initCutValues(graph, spanningTree); + while (true) { + var e = leaveEdge(spanningTree); + if (e === null) break; + var f = enterEdge(graph, spanningTree, e); + exchange(graph, spanningTree, e, f); + } +} + +/* + * Set the cut values of edges in the spanning tree by a depth-first + * postorder traversal. The cut value corresponds to the cost, in + * terms of a ranking's edge length sum, of lengthening an edge. + * Negative cut values typically indicate edges that would yield a + * smaller edge length sum if they were lengthened. + */ +function initCutValues(graph, spanningTree) { + computeLowLim(spanningTree); + + spanningTree.eachEdge(function(id, u, v, treeValue) { + treeValue.cutValue = 0; + }); + + // Propagate cut values up the tree. + function dfs(n) { + var children = spanningTree.successors(n); + for (var c in children) { + var child = children[c]; + dfs(child); + } + if (n !== spanningTree.graph().root) { + setCutValue(graph, spanningTree, n); + } + } + dfs(spanningTree.graph().root); +} + +/* + * Perform a DFS postorder traversal, labeling each node v with + * its traversal order 'lim(v)' and the minimum traversal number + * of any of its descendants 'low(v)'. This provides an efficient + * way to test whether u is an ancestor of v since + * low(u) <= lim(v) <= lim(u) if and only if u is an ancestor. + */ +function computeLowLim(tree) { + var postOrderNum = 0; + + function dfs(n) { + var children = tree.successors(n); + var low = postOrderNum; + for (var c in children) { + var child = children[c]; + dfs(child); + low = Math.min(low, tree.node(child).low); + } + tree.node(n).low = low; + tree.node(n).lim = postOrderNum++; + } + + dfs(tree.graph().root); +} + +/* + * To compute the cut value of the edge parent -> child, we consider + * it and any other graph edges to or from the child. + * parent + * | + * child + * / \ + * u v + */ +function setCutValue(graph, tree, child) { + var parentEdge = tree.inEdges(child)[0]; + + // List of child's children in the spanning tree. + var grandchildren = []; + var grandchildEdges = tree.outEdges(child); + for (var gce in grandchildEdges) { + grandchildren.push(tree.target(grandchildEdges[gce])); + } + + var cutValue = 0; + + // TODO: Replace unit increment/decrement with edge weights. + var E = 0; // Edges from child to grandchild's subtree. + var F = 0; // Edges to child from grandchild's subtree. + var G = 0; // Edges from child to nodes outside of child's subtree. + var H = 0; // Edges from nodes outside of child's subtree to child. + + // Consider all graph edges from child. + var outEdges = graph.outEdges(child); + var gc; + for (var oe in outEdges) { + var succ = graph.target(outEdges[oe]); + for (gc in grandchildren) { + if (inSubtree(tree, succ, grandchildren[gc])) { + E++; + } + } + if (!inSubtree(tree, succ, child)) { + G++; + } + } + + // Consider all graph edges to child. + var inEdges = graph.inEdges(child); + for (var ie in inEdges) { + var pred = graph.source(inEdges[ie]); + for (gc in grandchildren) { + if (inSubtree(tree, pred, grandchildren[gc])) { + F++; + } + } + if (!inSubtree(tree, pred, child)) { + H++; + } + } + + // Contributions depend on the alignment of the parent -> child edge + // and the child -> u or v edges. + var grandchildCutSum = 0; + for (gc in grandchildren) { + var cv = tree.edge(grandchildEdges[gc]).cutValue; + if (!tree.edge(grandchildEdges[gc]).reversed) { + grandchildCutSum += cv; + } else { + grandchildCutSum -= cv; + } + } + + if (!tree.edge(parentEdge).reversed) { + cutValue += grandchildCutSum - E + F - G + H; + } else { + cutValue -= grandchildCutSum - E + F - G + H; + } + + tree.edge(parentEdge).cutValue = cutValue; +} + +/* + * Return whether n is a node in the subtree with the given + * root. + */ +function inSubtree(tree, n, root) { + return (tree.node(root).low <= tree.node(n).lim && + tree.node(n).lim <= tree.node(root).lim); +} + +/* + * Return an edge from the tree with a negative cut value, or null if there + * is none. + */ +function leaveEdge(tree) { + var edges = tree.edges(); + for (var n in edges) { + var e = edges[n]; + var treeValue = tree.edge(e); + if (treeValue.cutValue < 0) { + return e; + } + } + return null; +} + +/* + * The edge e should be an edge in the tree, with an underlying edge + * in the graph, with a negative cut value. Of the two nodes incident + * on the edge, take the lower one. enterEdge returns an edge with + * minimum slack going from outside of that node's subtree to inside + * of that node's subtree. + */ +function enterEdge(graph, tree, e) { + var source = tree.source(e); + var target = tree.target(e); + var lower = tree.node(target).lim < tree.node(source).lim ? target : source; + + // Is the tree edge aligned with the graph edge? + var aligned = !tree.edge(e).reversed; + + var minSlack = Number.POSITIVE_INFINITY; + var minSlackEdge; + if (aligned) { + graph.eachEdge(function(id, u, v, value) { + if (id !== e && inSubtree(tree, u, lower) && !inSubtree(tree, v, lower)) { + var slack = rankUtil.slack(graph, u, v, value.minLen); + if (slack < minSlack) { + minSlack = slack; + minSlackEdge = id; + } + } + }); + } else { + graph.eachEdge(function(id, u, v, value) { + if (id !== e && !inSubtree(tree, u, lower) && inSubtree(tree, v, lower)) { + var slack = rankUtil.slack(graph, u, v, value.minLen); + if (slack < minSlack) { + minSlack = slack; + minSlackEdge = id; + } + } + }); + } + + if (minSlackEdge === undefined) { + var outside = []; + var inside = []; + graph.eachNode(function(id) { + if (!inSubtree(tree, id, lower)) { + outside.push(id); + } else { + inside.push(id); + } + }); + throw new Error('No edge found from outside of tree to inside'); + } + + return minSlackEdge; +} + +/* + * Replace edge e with edge f in the tree, recalculating the tree root, + * the nodes' low and lim properties and the edges' cut values. + */ +function exchange(graph, tree, e, f) { + tree.delEdge(e); + var source = graph.source(f); + var target = graph.target(f); + + // Redirect edges so that target is the root of its subtree. + function redirect(v) { + var edges = tree.inEdges(v); + for (var i in edges) { + var e = edges[i]; + var u = tree.source(e); + var value = tree.edge(e); + redirect(u); + tree.delEdge(e); + value.reversed = !value.reversed; + tree.addEdge(e, v, u, value); + } + } + + redirect(target); + + var root = source; + var edges = tree.inEdges(root); + while (edges.length > 0) { + root = tree.source(edges[0]); + edges = tree.inEdges(root); + } + + tree.graph().root = root; + + tree.addEdge(null, source, target, {cutValue: 0}); + + initCutValues(graph, tree); + + adjustRanks(graph, tree); +} + +/* + * Reset the ranks of all nodes based on the current spanning tree. + * The rank of the tree's root remains unchanged, while all other + * nodes are set to the sum of minimum length constraints along + * the path from the root. + */ +function adjustRanks(graph, tree) { + function dfs(p) { + var children = tree.successors(p); + children.forEach(function(c) { + var minLen = minimumLength(graph, p, c); + graph.node(c).rank = graph.node(p).rank + minLen; + dfs(c); + }); + } + + dfs(tree.graph().root); +} + +/* + * If u and v are connected by some edges in the graph, return the + * minimum length of those edges, as a positive number if v succeeds + * u and as a negative number if v precedes u. + */ +function minimumLength(graph, u, v) { + var outEdges = graph.outEdges(u, v); + if (outEdges.length > 0) { + return util.max(outEdges.map(function(e) { + return graph.edge(e).minLen; + })); + } + + var inEdges = graph.inEdges(u, v); + if (inEdges.length > 0) { + return -util.max(inEdges.map(function(e) { + return graph.edge(e).minLen; + })); + } +} + +},{"../util":26,"./rankUtil":24}],26:[function(require,module,exports){ +/* + * Returns the smallest value in the array. + */ +exports.min = function(values) { + return Math.min.apply(Math, values); +}; + +/* + * Returns the largest value in the array. + */ +exports.max = function(values) { + return Math.max.apply(Math, values); +}; + +/* + * Returns `true` only if `f(x)` is `true` for all `x` in `xs`. Otherwise + * returns `false`. This function will return immediately if it finds a + * case where `f(x)` does not hold. + */ +exports.all = function(xs, f) { + for (var i = 0; i < xs.length; ++i) { + if (!f(xs[i])) { + return false; + } + } + return true; +}; + +/* + * Accumulates the sum of elements in the given array using the `+` operator. + */ +exports.sum = function(values) { + return values.reduce(function(acc, x) { return acc + x; }, 0); +}; + +/* + * Returns an array of all values in the given object. + */ +exports.values = function(obj) { + return Object.keys(obj).map(function(k) { return obj[k]; }); +}; + +exports.shuffle = function(array) { + for (i = array.length - 1; i > 0; --i) { + var j = Math.floor(Math.random() * (i + 1)); + var aj = array[j]; + array[j] = array[i]; + array[i] = aj; + } +}; + +exports.propertyAccessor = function(self, config, field, setHook) { + return function(x) { + if (!arguments.length) return config[field]; + config[field] = x; + if (setHook) setHook(x); + return self; + }; +}; + +/* + * Given a layered, directed graph with `rank` and `order` node attributes, + * this function returns an array of ordered ranks. Each rank contains an array + * of the ids of the nodes in that rank in the order specified by the `order` + * attribute. + */ +exports.ordering = function(g) { + var ordering = []; + g.eachNode(function(u, value) { + var rank = ordering[value.rank] || (ordering[value.rank] = []); + rank[value.order] = u; + }); + return ordering; +}; + +/* + * A filter that can be used with `filterNodes` to get a graph that only + * includes nodes that do not contain others nodes. + */ +exports.filterNonSubgraphs = function(g) { + return function(u) { + return g.children(u).length === 0; + }; +}; + +/* + * Returns a new function that wraps `func` with a timer. The wrapper logs the + * time it takes to execute the function. + * + * The timer will be enabled provided `log.level >= 1`. + */ +function time(name, func) { + return function() { + var start = new Date().getTime(); + try { + return func.apply(null, arguments); + } finally { + log(1, name + ' time: ' + (new Date().getTime() - start) + 'ms'); + } + }; +} +time.enabled = false; + +exports.time = time; + +/* + * A global logger with the specification `log(level, message, ...)` that + * will log a message to the console if `log.level >= level`. + */ +function log(level) { + if (log.level >= level) { + console.log.apply(console, Array.prototype.slice.call(arguments, 1)); + } +} +log.level = 0; + +exports.log = log; + +},{}],27:[function(require,module,exports){ +module.exports = '0.4.5'; + +},{}],28:[function(require,module,exports){ +exports.Graph = require("./lib/Graph"); +exports.Digraph = require("./lib/Digraph"); +exports.CGraph = require("./lib/CGraph"); +exports.CDigraph = require("./lib/CDigraph"); +require("./lib/graph-converters"); + +exports.alg = { + isAcyclic: require("./lib/alg/isAcyclic"), + components: require("./lib/alg/components"), + dijkstra: require("./lib/alg/dijkstra"), + dijkstraAll: require("./lib/alg/dijkstraAll"), + findCycles: require("./lib/alg/findCycles"), + floydWarshall: require("./lib/alg/floydWarshall"), + postorder: require("./lib/alg/postorder"), + preorder: require("./lib/alg/preorder"), + prim: require("./lib/alg/prim"), + tarjan: require("./lib/alg/tarjan"), + topsort: require("./lib/alg/topsort") +}; + +exports.converter = { + json: require("./lib/converter/json.js") +}; + +var filter = require("./lib/filter"); +exports.filter = { + all: filter.all, + nodesFromList: filter.nodesFromList +}; + +exports.version = require("./lib/version"); + +},{"./lib/CDigraph":30,"./lib/CGraph":31,"./lib/Digraph":32,"./lib/Graph":33,"./lib/alg/components":34,"./lib/alg/dijkstra":35,"./lib/alg/dijkstraAll":36,"./lib/alg/findCycles":37,"./lib/alg/floydWarshall":38,"./lib/alg/isAcyclic":39,"./lib/alg/postorder":40,"./lib/alg/preorder":41,"./lib/alg/prim":42,"./lib/alg/tarjan":43,"./lib/alg/topsort":44,"./lib/converter/json.js":46,"./lib/filter":47,"./lib/graph-converters":48,"./lib/version":50}],29:[function(require,module,exports){ +/* jshint -W079 */ +var Set = require("cp-data").Set; +/* jshint +W079 */ + +module.exports = BaseGraph; + +function BaseGraph() { + // The value assigned to the graph itself. + this._value = undefined; + + // Map of node id -> { id, value } + this._nodes = {}; + + // Map of edge id -> { id, u, v, value } + this._edges = {}; + + // Used to generate a unique id in the graph + this._nextId = 0; +} + +// Number of nodes +BaseGraph.prototype.order = function() { + return Object.keys(this._nodes).length; +}; + +// Number of edges +BaseGraph.prototype.size = function() { + return Object.keys(this._edges).length; +}; + +// Accessor for graph level value +BaseGraph.prototype.graph = function(value) { + if (arguments.length === 0) { + return this._value; + } + this._value = value; +}; + +BaseGraph.prototype.hasNode = function(u) { + return u in this._nodes; +}; + +BaseGraph.prototype.node = function(u, value) { + var node = this._strictGetNode(u); + if (arguments.length === 1) { + return node.value; + } + node.value = value; +}; + +BaseGraph.prototype.nodes = function() { + var nodes = []; + this.eachNode(function(id) { nodes.push(id); }); + return nodes; +}; + +BaseGraph.prototype.eachNode = function(func) { + for (var k in this._nodes) { + var node = this._nodes[k]; + func(node.id, node.value); + } +}; + +BaseGraph.prototype.hasEdge = function(e) { + return e in this._edges; +}; + +BaseGraph.prototype.edge = function(e, value) { + var edge = this._strictGetEdge(e); + if (arguments.length === 1) { + return edge.value; + } + edge.value = value; +}; + +BaseGraph.prototype.edges = function() { + var es = []; + this.eachEdge(function(id) { es.push(id); }); + return es; +}; + +BaseGraph.prototype.eachEdge = function(func) { + for (var k in this._edges) { + var edge = this._edges[k]; + func(edge.id, edge.u, edge.v, edge.value); + } +}; + +BaseGraph.prototype.incidentNodes = function(e) { + var edge = this._strictGetEdge(e); + return [edge.u, edge.v]; +}; + +BaseGraph.prototype.addNode = function(u, value) { + if (u === undefined || u === null) { + do { + u = "_" + (++this._nextId); + } while (this.hasNode(u)); + } else if (this.hasNode(u)) { + throw new Error("Graph already has node '" + u + "'"); + } + this._nodes[u] = { id: u, value: value }; + return u; +}; + +BaseGraph.prototype.delNode = function(u) { + this._strictGetNode(u); + this.incidentEdges(u).forEach(function(e) { this.delEdge(e); }, this); + delete this._nodes[u]; +}; + +// inMap and outMap are opposite sides of an incidence map. For example, for +// Graph these would both come from the _incidentEdges map, while for Digraph +// they would come from _inEdges and _outEdges. +BaseGraph.prototype._addEdge = function(e, u, v, value, inMap, outMap) { + this._strictGetNode(u); + this._strictGetNode(v); + + if (e === undefined || e === null) { + do { + e = "_" + (++this._nextId); + } while (this.hasEdge(e)); + } + else if (this.hasEdge(e)) { + throw new Error("Graph already has edge '" + e + "'"); + } + + this._edges[e] = { id: e, u: u, v: v, value: value }; + addEdgeToMap(inMap[v], u, e); + addEdgeToMap(outMap[u], v, e); + + return e; +}; + +// See note for _addEdge regarding inMap and outMap. +BaseGraph.prototype._delEdge = function(e, inMap, outMap) { + var edge = this._strictGetEdge(e); + delEdgeFromMap(inMap[edge.v], edge.u, e); + delEdgeFromMap(outMap[edge.u], edge.v, e); + delete this._edges[e]; +}; + +BaseGraph.prototype.copy = function() { + var copy = new this.constructor(); + copy.graph(this.graph()); + this.eachNode(function(u, value) { copy.addNode(u, value); }); + this.eachEdge(function(e, u, v, value) { copy.addEdge(e, u, v, value); }); + copy._nextId = this._nextId; + return copy; +}; + +BaseGraph.prototype.filterNodes = function(filter) { + var copy = new this.constructor(); + copy.graph(this.graph()); + this.eachNode(function(u, value) { + if (filter(u)) { + copy.addNode(u, value); + } + }); + this.eachEdge(function(e, u, v, value) { + if (copy.hasNode(u) && copy.hasNode(v)) { + copy.addEdge(e, u, v, value); + } + }); + return copy; +}; + +BaseGraph.prototype._strictGetNode = function(u) { + var node = this._nodes[u]; + if (node === undefined) { + throw new Error("Node '" + u + "' is not in graph"); + } + return node; +}; + +BaseGraph.prototype._strictGetEdge = function(e) { + var edge = this._edges[e]; + if (edge === undefined) { + throw new Error("Edge '" + e + "' is not in graph"); + } + return edge; +}; + +function addEdgeToMap(map, v, e) { + (map[v] || (map[v] = new Set())).add(e); +} + +function delEdgeFromMap(map, v, e) { + var vEntry = map[v]; + vEntry.remove(e); + if (vEntry.size() === 0) { + delete map[v]; + } +} + + +},{"cp-data":5}],30:[function(require,module,exports){ +var Digraph = require("./Digraph"), + compoundify = require("./compoundify"); + +var CDigraph = compoundify(Digraph); + +module.exports = CDigraph; + +CDigraph.fromDigraph = function(src) { + var g = new CDigraph(), + graphValue = src.graph(); + + if (graphValue !== undefined) { + g.graph(graphValue); + } + + src.eachNode(function(u, value) { + if (value === undefined) { + g.addNode(u); + } else { + g.addNode(u, value); + } + }); + src.eachEdge(function(e, u, v, value) { + if (value === undefined) { + g.addEdge(null, u, v); + } else { + g.addEdge(null, u, v, value); + } + }); + return g; +}; + +CDigraph.prototype.toString = function() { + return "CDigraph " + JSON.stringify(this, null, 2); +}; + +},{"./Digraph":32,"./compoundify":45}],31:[function(require,module,exports){ +var Graph = require("./Graph"), + compoundify = require("./compoundify"); + +var CGraph = compoundify(Graph); + +module.exports = CGraph; + +CGraph.fromGraph = function(src) { + var g = new CGraph(), + graphValue = src.graph(); + + if (graphValue !== undefined) { + g.graph(graphValue); + } + + src.eachNode(function(u, value) { + if (value === undefined) { + g.addNode(u); + } else { + g.addNode(u, value); + } + }); + src.eachEdge(function(e, u, v, value) { + if (value === undefined) { + g.addEdge(null, u, v); + } else { + g.addEdge(null, u, v, value); + } + }); + return g; +}; + +CGraph.prototype.toString = function() { + return "CGraph " + JSON.stringify(this, null, 2); +}; + +},{"./Graph":33,"./compoundify":45}],32:[function(require,module,exports){ +/* + * This file is organized with in the following order: + * + * Exports + * Graph constructors + * Graph queries (e.g. nodes(), edges() + * Graph mutators + * Helper functions + */ + +var util = require("./util"), + BaseGraph = require("./BaseGraph"), +/* jshint -W079 */ + Set = require("cp-data").Set; +/* jshint +W079 */ + +module.exports = Digraph; + +/* + * Constructor to create a new directed multi-graph. + */ +function Digraph() { + BaseGraph.call(this); + + /*! Map of sourceId -> {targetId -> Set of edge ids} */ + this._inEdges = {}; + + /*! Map of targetId -> {sourceId -> Set of edge ids} */ + this._outEdges = {}; +} + +Digraph.prototype = new BaseGraph(); +Digraph.prototype.constructor = Digraph; + +/* + * Always returns `true`. + */ +Digraph.prototype.isDirected = function() { + return true; +}; + +/* + * Returns all successors of the node with the id `u`. That is, all nodes + * that have the node `u` as their source are returned. + * + * If no node `u` exists in the graph this function throws an Error. + * + * @param {String} u a node id + */ +Digraph.prototype.successors = function(u) { + this._strictGetNode(u); + return Object.keys(this._outEdges[u]) + .map(function(v) { return this._nodes[v].id; }, this); +}; + +/* + * Returns all predecessors of the node with the id `u`. That is, all nodes + * that have the node `u` as their target are returned. + * + * If no node `u` exists in the graph this function throws an Error. + * + * @param {String} u a node id + */ +Digraph.prototype.predecessors = function(u) { + this._strictGetNode(u); + return Object.keys(this._inEdges[u]) + .map(function(v) { return this._nodes[v].id; }, this); +}; + +/* + * Returns all nodes that are adjacent to the node with the id `u`. In other + * words, this function returns the set of all successors and predecessors of + * node `u`. + * + * @param {String} u a node id + */ +Digraph.prototype.neighbors = function(u) { + return Set.union([this.successors(u), this.predecessors(u)]).keys(); +}; + +/* + * Returns all nodes in the graph that have no in-edges. + */ +Digraph.prototype.sources = function() { + var self = this; + return this._filterNodes(function(u) { + // This could have better space characteristics if we had an inDegree function. + return self.inEdges(u).length === 0; + }); +}; + +/* + * Returns all nodes in the graph that have no out-edges. + */ +Digraph.prototype.sinks = function() { + var self = this; + return this._filterNodes(function(u) { + // This could have better space characteristics if we have an outDegree function. + return self.outEdges(u).length === 0; + }); +}; + +/* + * Returns the source node incident on the edge identified by the id `e`. If no + * such edge exists in the graph this function throws an Error. + * + * @param {String} e an edge id + */ +Digraph.prototype.source = function(e) { + return this._strictGetEdge(e).u; +}; + +/* + * Returns the target node incident on the edge identified by the id `e`. If no + * such edge exists in the graph this function throws an Error. + * + * @param {String} e an edge id + */ +Digraph.prototype.target = function(e) { + return this._strictGetEdge(e).v; +}; + +/* + * Returns an array of ids for all edges in the graph that have the node + * `target` as their target. If the node `target` is not in the graph this + * function raises an Error. + * + * Optionally a `source` node can also be specified. This causes the results + * to be filtered such that only edges from `source` to `target` are included. + * If the node `source` is specified but is not in the graph then this function + * raises an Error. + * + * @param {String} target the target node id + * @param {String} [source] an optional source node id + */ +Digraph.prototype.inEdges = function(target, source) { + this._strictGetNode(target); + var results = Set.union(util.values(this._inEdges[target])).keys(); + if (arguments.length > 1) { + this._strictGetNode(source); + results = results.filter(function(e) { return this.source(e) === source; }, this); + } + return results; +}; + +/* + * Returns an array of ids for all edges in the graph that have the node + * `source` as their source. If the node `source` is not in the graph this + * function raises an Error. + * + * Optionally a `target` node may also be specified. This causes the results + * to be filtered such that only edges from `source` to `target` are included. + * If the node `target` is specified but is not in the graph then this function + * raises an Error. + * + * @param {String} source the source node id + * @param {String} [target] an optional target node id + */ +Digraph.prototype.outEdges = function(source, target) { + this._strictGetNode(source); + var results = Set.union(util.values(this._outEdges[source])).keys(); + if (arguments.length > 1) { + this._strictGetNode(target); + results = results.filter(function(e) { return this.target(e) === target; }, this); + } + return results; +}; + +/* + * Returns an array of ids for all edges in the graph that have the `u` as + * their source or their target. If the node `u` is not in the graph this + * function raises an Error. + * + * Optionally a `v` node may also be specified. This causes the results to be + * filtered such that only edges between `u` and `v` - in either direction - + * are included. IF the node `v` is specified but not in the graph then this + * function raises an Error. + * + * @param {String} u the node for which to find incident edges + * @param {String} [v] option node that must be adjacent to `u` + */ +Digraph.prototype.incidentEdges = function(u, v) { + if (arguments.length > 1) { + return Set.union([this.outEdges(u, v), this.outEdges(v, u)]).keys(); + } else { + return Set.union([this.inEdges(u), this.outEdges(u)]).keys(); + } +}; + +/* + * Returns a string representation of this graph. + */ +Digraph.prototype.toString = function() { + return "Digraph " + JSON.stringify(this, null, 2); +}; + +/* + * Adds a new node with the id `u` to the graph and assigns it the value + * `value`. If a node with the id is already a part of the graph this function + * throws an Error. + * + * @param {String} u a node id + * @param {Object} [value] an optional value to attach to the node + */ +Digraph.prototype.addNode = function(u, value) { + u = BaseGraph.prototype.addNode.call(this, u, value); + this._inEdges[u] = {}; + this._outEdges[u] = {}; + return u; +}; + +/* + * Removes a node from the graph that has the id `u`. Any edges incident on the + * node are also removed. If the graph does not contain a node with the id this + * function will throw an Error. + * + * @param {String} u a node id + */ +Digraph.prototype.delNode = function(u) { + BaseGraph.prototype.delNode.call(this, u); + delete this._inEdges[u]; + delete this._outEdges[u]; +}; + +/* + * Adds a new edge to the graph with the id `e` from a node with the id `source` + * to a node with an id `target` and assigns it the value `value`. This graph + * allows more than one edge from `source` to `target` as long as the id `e` + * is unique in the set of edges. If `e` is `null` the graph will assign a + * unique identifier to the edge. + * + * If `source` or `target` are not present in the graph this function will + * throw an Error. + * + * @param {String} [e] an edge id + * @param {String} source the source node id + * @param {String} target the target node id + * @param {Object} [value] an optional value to attach to the edge + */ +Digraph.prototype.addEdge = function(e, source, target, value) { + return BaseGraph.prototype._addEdge.call(this, e, source, target, value, + this._inEdges, this._outEdges); +}; + +/* + * Removes an edge in the graph with the id `e`. If no edge in the graph has + * the id `e` this function will throw an Error. + * + * @param {String} e an edge id + */ +Digraph.prototype.delEdge = function(e) { + BaseGraph.prototype._delEdge.call(this, e, this._inEdges, this._outEdges); +}; + +// Unlike BaseGraph.filterNodes, this helper just returns nodes that +// satisfy a predicate. +Digraph.prototype._filterNodes = function(pred) { + var filtered = []; + this.eachNode(function(u) { + if (pred(u)) { + filtered.push(u); + } + }); + return filtered; +}; + + +},{"./BaseGraph":29,"./util":49,"cp-data":5}],33:[function(require,module,exports){ +/* + * This file is organized with in the following order: + * + * Exports + * Graph constructors + * Graph queries (e.g. nodes(), edges() + * Graph mutators + * Helper functions + */ + +var util = require("./util"), + BaseGraph = require("./BaseGraph"), +/* jshint -W079 */ + Set = require("cp-data").Set; +/* jshint +W079 */ + +module.exports = Graph; + +/* + * Constructor to create a new undirected multi-graph. + */ +function Graph() { + BaseGraph.call(this); + + /*! Map of nodeId -> { otherNodeId -> Set of edge ids } */ + this._incidentEdges = {}; +} + +Graph.prototype = new BaseGraph(); +Graph.prototype.constructor = Graph; + +/* + * Always returns `false`. + */ +Graph.prototype.isDirected = function() { + return false; +}; + +/* + * Returns all nodes that are adjacent to the node with the id `u`. + * + * @param {String} u a node id + */ +Graph.prototype.neighbors = function(u) { + this._strictGetNode(u); + return Object.keys(this._incidentEdges[u]) + .map(function(v) { return this._nodes[v].id; }, this); +}; + +/* + * Returns an array of ids for all edges in the graph that are incident on `u`. + * If the node `u` is not in the graph this function raises an Error. + * + * Optionally a `v` node may also be specified. This causes the results to be + * filtered such that only edges between `u` and `v` are included. If the node + * `v` is specified but not in the graph then this function raises an Error. + * + * @param {String} u the node for which to find incident edges + * @param {String} [v] option node that must be adjacent to `u` + */ +Graph.prototype.incidentEdges = function(u, v) { + this._strictGetNode(u); + if (arguments.length > 1) { + this._strictGetNode(v); + return v in this._incidentEdges[u] ? this._incidentEdges[u][v].keys() : []; + } else { + return Set.union(util.values(this._incidentEdges[u])).keys(); + } +}; + +/* + * Returns a string representation of this graph. + */ +Graph.prototype.toString = function() { + return "Graph " + JSON.stringify(this, null, 2); +}; + +/* + * Adds a new node with the id `u` to the graph and assigns it the value + * `value`. If a node with the id is already a part of the graph this function + * throws an Error. + * + * @param {String} u a node id + * @param {Object} [value] an optional value to attach to the node + */ +Graph.prototype.addNode = function(u, value) { + u = BaseGraph.prototype.addNode.call(this, u, value); + this._incidentEdges[u] = {}; + return u; +}; + +/* + * Removes a node from the graph that has the id `u`. Any edges incident on the + * node are also removed. If the graph does not contain a node with the id this + * function will throw an Error. + * + * @param {String} u a node id + */ +Graph.prototype.delNode = function(u) { + BaseGraph.prototype.delNode.call(this, u); + delete this._incidentEdges[u]; +}; + +/* + * Adds a new edge to the graph with the id `e` between a node with the id `u` + * and a node with an id `v` and assigns it the value `value`. This graph + * allows more than one edge between `u` and `v` as long as the id `e` + * is unique in the set of edges. If `e` is `null` the graph will assign a + * unique identifier to the edge. + * + * If `u` or `v` are not present in the graph this function will throw an + * Error. + * + * @param {String} [e] an edge id + * @param {String} u the node id of one of the adjacent nodes + * @param {String} v the node id of the other adjacent node + * @param {Object} [value] an optional value to attach to the edge + */ +Graph.prototype.addEdge = function(e, u, v, value) { + return BaseGraph.prototype._addEdge.call(this, e, u, v, value, + this._incidentEdges, this._incidentEdges); +}; + +/* + * Removes an edge in the graph with the id `e`. If no edge in the graph has + * the id `e` this function will throw an Error. + * + * @param {String} e an edge id + */ +Graph.prototype.delEdge = function(e) { + BaseGraph.prototype._delEdge.call(this, e, this._incidentEdges, this._incidentEdges); +}; + + +},{"./BaseGraph":29,"./util":49,"cp-data":5}],34:[function(require,module,exports){ +/* jshint -W079 */ +var Set = require("cp-data").Set; +/* jshint +W079 */ + +module.exports = components; + +/** + * Finds all [connected components][] in a graph and returns an array of these + * components. Each component is itself an array that contains the ids of nodes + * in the component. + * + * This function only works with undirected Graphs. + * + * [connected components]: http://en.wikipedia.org/wiki/Connected_component_(graph_theory) + * + * @param {Graph} g the graph to search for components + */ +function components(g) { + var results = []; + var visited = new Set(); + + function dfs(v, component) { + if (!visited.has(v)) { + visited.add(v); + component.push(v); + g.neighbors(v).forEach(function(w) { + dfs(w, component); + }); + } + } + + g.nodes().forEach(function(v) { + var component = []; + dfs(v, component); + if (component.length > 0) { + results.push(component); + } + }); + + return results; +} + +},{"cp-data":5}],35:[function(require,module,exports){ +var PriorityQueue = require("cp-data").PriorityQueue; + +module.exports = dijkstra; + +/** + * This function is an implementation of [Dijkstra's algorithm][] which finds + * the shortest path from **source** to all other nodes in **g**. This + * function returns a map of `u -> { distance, predecessor }`. The distance + * property holds the sum of the weights from **source** to `u` along the + * shortest path or `Number.POSITIVE_INFINITY` if there is no path from + * **source**. The predecessor property can be used to walk the individual + * elements of the path from **source** to **u** in reverse order. + * + * This function takes an optional `weightFunc(e)` which returns the + * weight of the edge `e`. If no weightFunc is supplied then each edge is + * assumed to have a weight of 1. This function throws an Error if any of + * the traversed edges have a negative edge weight. + * + * This function takes an optional `incidentFunc(u)` which returns the ids of + * all edges incident to the node `u` for the purposes of shortest path + * traversal. By default this function uses the `g.outEdges` for Digraphs and + * `g.incidentEdges` for Graphs. + * + * This function takes `O((|E| + |V|) * log |V|)` time. + * + * [Dijkstra's algorithm]: http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm + * + * @param {Graph} g the graph to search for shortest paths from **source** + * @param {Object} source the source from which to start the search + * @param {Function} [weightFunc] optional weight function + * @param {Function} [incidentFunc] optional incident function + */ +function dijkstra(g, source, weightFunc, incidentFunc) { + var results = {}, + pq = new PriorityQueue(); + + function updateNeighbors(e) { + var incidentNodes = g.incidentNodes(e), + v = incidentNodes[0] !== u ? incidentNodes[0] : incidentNodes[1], + vEntry = results[v], + weight = weightFunc(e), + distance = uEntry.distance + weight; + + if (weight < 0) { + throw new Error("dijkstra does not allow negative edge weights. Bad edge: " + e + " Weight: " + weight); + } + + if (distance < vEntry.distance) { + vEntry.distance = distance; + vEntry.predecessor = u; + pq.decrease(v, distance); + } + } + + weightFunc = weightFunc || function() { return 1; }; + incidentFunc = incidentFunc || (g.isDirected() + ? function(u) { return g.outEdges(u); } + : function(u) { return g.incidentEdges(u); }); + + g.eachNode(function(u) { + var distance = u === source ? 0 : Number.POSITIVE_INFINITY; + results[u] = { distance: distance }; + pq.add(u, distance); + }); + + var u, uEntry; + while (pq.size() > 0) { + u = pq.removeMin(); + uEntry = results[u]; + if (uEntry.distance === Number.POSITIVE_INFINITY) { + break; + } + + incidentFunc(u).forEach(updateNeighbors); + } + + return results; +} + +},{"cp-data":5}],36:[function(require,module,exports){ +var dijkstra = require("./dijkstra"); + +module.exports = dijkstraAll; + +/** + * This function finds the shortest path from each node to every other + * reachable node in the graph. It is similar to [alg.dijkstra][], but + * instead of returning a single-source array, it returns a mapping of + * of `source -> alg.dijksta(g, source, weightFunc, incidentFunc)`. + * + * This function takes an optional `weightFunc(e)` which returns the + * weight of the edge `e`. If no weightFunc is supplied then each edge is + * assumed to have a weight of 1. This function throws an Error if any of + * the traversed edges have a negative edge weight. + * + * This function takes an optional `incidentFunc(u)` which returns the ids of + * all edges incident to the node `u` for the purposes of shortest path + * traversal. By default this function uses the `outEdges` function on the + * supplied graph. + * + * This function takes `O(|V| * (|E| + |V|) * log |V|)` time. + * + * [alg.dijkstra]: dijkstra.js.html#dijkstra + * + * @param {Graph} g the graph to search for shortest paths from **source** + * @param {Function} [weightFunc] optional weight function + * @param {Function} [incidentFunc] optional incident function + */ +function dijkstraAll(g, weightFunc, incidentFunc) { + var results = {}; + g.eachNode(function(u) { + results[u] = dijkstra(g, u, weightFunc, incidentFunc); + }); + return results; +} + +},{"./dijkstra":35}],37:[function(require,module,exports){ +var tarjan = require("./tarjan"); + +module.exports = findCycles; + +/* + * Given a Digraph **g** this function returns all nodes that are part of a + * cycle. Since there may be more than one cycle in a graph this function + * returns an array of these cycles, where each cycle is itself represented + * by an array of ids for each node involved in that cycle. + * + * [alg.isAcyclic][] is more efficient if you only need to determine whether + * a graph has a cycle or not. + * + * [alg.isAcyclic]: isAcyclic.js.html#isAcyclic + * + * @param {Digraph} g the graph to search for cycles. + */ +function findCycles(g) { + return tarjan(g).filter(function(cmpt) { return cmpt.length > 1; }); +} + +},{"./tarjan":43}],38:[function(require,module,exports){ +module.exports = floydWarshall; + +/** + * This function is an implementation of the [Floyd-Warshall algorithm][], + * which finds the shortest path from each node to every other reachable node + * in the graph. It is similar to [alg.dijkstraAll][], but it handles negative + * edge weights and is more efficient for some types of graphs. This function + * returns a map of `source -> { target -> { distance, predecessor }`. The + * distance property holds the sum of the weights from `source` to `target` + * along the shortest path of `Number.POSITIVE_INFINITY` if there is no path + * from `source`. The predecessor property can be used to walk the individual + * elements of the path from `source` to `target` in reverse order. + * + * This function takes an optional `weightFunc(e)` which returns the + * weight of the edge `e`. If no weightFunc is supplied then each edge is + * assumed to have a weight of 1. + * + * This function takes an optional `incidentFunc(u)` which returns the ids of + * all edges incident to the node `u` for the purposes of shortest path + * traversal. By default this function uses the `outEdges` function on the + * supplied graph. + * + * This algorithm takes O(|V|^3) time. + * + * [Floyd-Warshall algorithm]: https://en.wikipedia.org/wiki/Floyd-Warshall_algorithm + * [alg.dijkstraAll]: dijkstraAll.js.html#dijkstraAll + * + * @param {Graph} g the graph to search for shortest paths from **source** + * @param {Function} [weightFunc] optional weight function + * @param {Function} [incidentFunc] optional incident function + */ +function floydWarshall(g, weightFunc, incidentFunc) { + var results = {}, + nodes = g.nodes(); + + weightFunc = weightFunc || function() { return 1; }; + incidentFunc = incidentFunc || (g.isDirected() + ? function(u) { return g.outEdges(u); } + : function(u) { return g.incidentEdges(u); }); + + nodes.forEach(function(u) { + results[u] = {}; + results[u][u] = { distance: 0 }; + nodes.forEach(function(v) { + if (u !== v) { + results[u][v] = { distance: Number.POSITIVE_INFINITY }; + } + }); + incidentFunc(u).forEach(function(e) { + var incidentNodes = g.incidentNodes(e), + v = incidentNodes[0] !== u ? incidentNodes[0] : incidentNodes[1], + d = weightFunc(e); + if (d < results[u][v].distance) { + results[u][v] = { distance: d, predecessor: u }; + } + }); + }); + + nodes.forEach(function(k) { + var rowK = results[k]; + nodes.forEach(function(i) { + var rowI = results[i]; + nodes.forEach(function(j) { + var ik = rowI[k]; + var kj = rowK[j]; + var ij = rowI[j]; + var altDistance = ik.distance + kj.distance; + if (altDistance < ij.distance) { + ij.distance = altDistance; + ij.predecessor = kj.predecessor; + } + }); + }); + }); + + return results; +} + +},{}],39:[function(require,module,exports){ +var topsort = require("./topsort"); + +module.exports = isAcyclic; + +/* + * Given a Digraph **g** this function returns `true` if the graph has no + * cycles and returns `false` if it does. This algorithm returns as soon as it + * detects the first cycle. + * + * Use [alg.findCycles][] if you need the actual list of cycles in a graph. + * + * [alg.findCycles]: findCycles.js.html#findCycles + * + * @param {Digraph} g the graph to test for cycles + */ +function isAcyclic(g) { + try { + topsort(g); + } catch (e) { + if (e instanceof topsort.CycleException) return false; + throw e; + } + return true; +} + +},{"./topsort":44}],40:[function(require,module,exports){ +/* jshint -W079 */ +var Set = require("cp-data").Set; +/* jshint +W079 */ + +module.exports = postorder; + +// Postorder traversal of g, calling f for each visited node. Assumes the graph +// is a tree. +function postorder(g, root, f) { + var visited = new Set(); + if (g.isDirected()) { + throw new Error("This function only works for undirected graphs"); + } + function dfs(u, prev) { + if (visited.has(u)) { + throw new Error("The input graph is not a tree: " + g); + } + visited.add(u); + g.neighbors(u).forEach(function(v) { + if (v !== prev) dfs(v, u); + }); + f(u); + } + dfs(root); +} + +},{"cp-data":5}],41:[function(require,module,exports){ +/* jshint -W079 */ +var Set = require("cp-data").Set; +/* jshint +W079 */ + +module.exports = preorder; + +// Preorder traversal of g, calling f for each visited node. Assumes the graph +// is a tree. +function preorder(g, root, f) { + var visited = new Set(); + if (g.isDirected()) { + throw new Error("This function only works for undirected graphs"); + } + function dfs(u, prev) { + if (visited.has(u)) { + throw new Error("The input graph is not a tree: " + g); + } + visited.add(u); + f(u); + g.neighbors(u).forEach(function(v) { + if (v !== prev) dfs(v, u); + }); + } + dfs(root); +} + +},{"cp-data":5}],42:[function(require,module,exports){ +var Graph = require("../Graph"), + PriorityQueue = require("cp-data").PriorityQueue; + +module.exports = prim; + +/** + * [Prim's algorithm][] takes a connected undirected graph and generates a + * [minimum spanning tree][]. This function returns the minimum spanning + * tree as an undirected graph. This algorithm is derived from the description + * in "Introduction to Algorithms", Third Edition, Cormen, et al., Pg 634. + * + * This function takes a `weightFunc(e)` which returns the weight of the edge + * `e`. It throws an Error if the graph is not connected. + * + * This function takes `O(|E| log |V|)` time. + * + * [Prim's algorithm]: https://en.wikipedia.org/wiki/Prim's_algorithm + * [minimum spanning tree]: https://en.wikipedia.org/wiki/Minimum_spanning_tree + * + * @param {Graph} g the graph used to generate the minimum spanning tree + * @param {Function} weightFunc the weight function to use + */ +function prim(g, weightFunc) { + var result = new Graph(), + parents = {}, + pq = new PriorityQueue(), + u; + + function updateNeighbors(e) { + var incidentNodes = g.incidentNodes(e), + v = incidentNodes[0] !== u ? incidentNodes[0] : incidentNodes[1], + pri = pq.priority(v); + if (pri !== undefined) { + var edgeWeight = weightFunc(e); + if (edgeWeight < pri) { + parents[v] = u; + pq.decrease(v, edgeWeight); + } + } + } + + if (g.order() === 0) { + return result; + } + + g.eachNode(function(u) { + pq.add(u, Number.POSITIVE_INFINITY); + result.addNode(u); + }); + + // Start from an arbitrary node + pq.decrease(g.nodes()[0], 0); + + var init = false; + while (pq.size() > 0) { + u = pq.removeMin(); + if (u in parents) { + result.addEdge(null, u, parents[u]); + } else if (init) { + throw new Error("Input graph is not connected: " + g); + } else { + init = true; + } + + g.incidentEdges(u).forEach(updateNeighbors); + } + + return result; +} + +},{"../Graph":33,"cp-data":5}],43:[function(require,module,exports){ +module.exports = tarjan; + +/** + * This function is an implementation of [Tarjan's algorithm][] which finds + * all [strongly connected components][] in the directed graph **g**. Each + * strongly connected component is composed of nodes that can reach all other + * nodes in the component via directed edges. A strongly connected component + * can consist of a single node if that node cannot both reach and be reached + * by any other specific node in the graph. Components of more than one node + * are guaranteed to have at least one cycle. + * + * This function returns an array of components. Each component is itself an + * array that contains the ids of all nodes in the component. + * + * [Tarjan's algorithm]: http://en.wikipedia.org/wiki/Tarjan's_strongly_connected_components_algorithm + * [strongly connected components]: http://en.wikipedia.org/wiki/Strongly_connected_component + * + * @param {Digraph} g the graph to search for strongly connected components + */ +function tarjan(g) { + if (!g.isDirected()) { + throw new Error("tarjan can only be applied to a directed graph. Bad input: " + g); + } + + var index = 0, + stack = [], + visited = {}, // node id -> { onStack, lowlink, index } + results = []; + + function dfs(u) { + var entry = visited[u] = { + onStack: true, + lowlink: index, + index: index++ + }; + stack.push(u); + + g.successors(u).forEach(function(v) { + if (!(v in visited)) { + dfs(v); + entry.lowlink = Math.min(entry.lowlink, visited[v].lowlink); + } else if (visited[v].onStack) { + entry.lowlink = Math.min(entry.lowlink, visited[v].index); + } + }); + + if (entry.lowlink === entry.index) { + var cmpt = [], + v; + do { + v = stack.pop(); + visited[v].onStack = false; + cmpt.push(v); + } while (u !== v); + results.push(cmpt); + } + } + + g.nodes().forEach(function(u) { + if (!(u in visited)) { + dfs(u); + } + }); + + return results; +} + +},{}],44:[function(require,module,exports){ +module.exports = topsort; +topsort.CycleException = CycleException; + +/* + * Given a graph **g**, this function returns an ordered list of nodes such + * that for each edge `u -> v`, `u` appears before `v` in the list. If the + * graph has a cycle it is impossible to generate such a list and + * **CycleException** is thrown. + * + * See [topological sorting](https://en.wikipedia.org/wiki/Topological_sorting) + * for more details about how this algorithm works. + * + * @param {Digraph} g the graph to sort + */ +function topsort(g) { + if (!g.isDirected()) { + throw new Error("topsort can only be applied to a directed graph. Bad input: " + g); + } + + var visited = {}; + var stack = {}; + var results = []; + + function visit(node) { + if (node in stack) { + throw new CycleException(); + } + + if (!(node in visited)) { + stack[node] = true; + visited[node] = true; + g.predecessors(node).forEach(function(pred) { + visit(pred); + }); + delete stack[node]; + results.push(node); + } + } + + var sinks = g.sinks(); + if (g.order() !== 0 && sinks.length === 0) { + throw new CycleException(); + } + + g.sinks().forEach(function(sink) { + visit(sink); + }); + + return results; +} + +function CycleException() {} + +CycleException.prototype.toString = function() { + return "Graph has at least one cycle"; +}; + +},{}],45:[function(require,module,exports){ +// This file provides a helper function that mixes-in Dot behavior to an +// existing graph prototype. + +/* jshint -W079 */ +var Set = require("cp-data").Set; +/* jshint +W079 */ + +module.exports = compoundify; + +// Extends the given SuperConstructor with the ability for nodes to contain +// other nodes. A special node id `null` is used to indicate the root graph. +function compoundify(SuperConstructor) { + function Constructor() { + SuperConstructor.call(this); + + // Map of object id -> parent id (or null for root graph) + this._parents = {}; + + // Map of id (or null) -> children set + this._children = {}; + this._children[null] = new Set(); + } + + Constructor.prototype = new SuperConstructor(); + Constructor.prototype.constructor = Constructor; + + Constructor.prototype.parent = function(u, parent) { + this._strictGetNode(u); + + if (arguments.length < 2) { + return this._parents[u]; + } + + if (u === parent) { + throw new Error("Cannot make " + u + " a parent of itself"); + } + if (parent !== null) { + this._strictGetNode(parent); + } + + this._children[this._parents[u]].remove(u); + this._parents[u] = parent; + this._children[parent].add(u); + }; + + Constructor.prototype.children = function(u) { + if (u !== null) { + this._strictGetNode(u); + } + return this._children[u].keys(); + }; + + Constructor.prototype.addNode = function(u, value) { + u = SuperConstructor.prototype.addNode.call(this, u, value); + this._parents[u] = null; + this._children[u] = new Set(); + this._children[null].add(u); + return u; + }; + + Constructor.prototype.delNode = function(u) { + // Promote all children to the parent of the subgraph + var parent = this.parent(u); + this._children[u].keys().forEach(function(child) { + this.parent(child, parent); + }, this); + + this._children[parent].remove(u); + delete this._parents[u]; + delete this._children[u]; + + return SuperConstructor.prototype.delNode.call(this, u); + }; + + Constructor.prototype.copy = function() { + var copy = SuperConstructor.prototype.copy.call(this); + this.nodes().forEach(function(u) { + copy.parent(u, this.parent(u)); + }, this); + return copy; + }; + + Constructor.prototype.filterNodes = function(filter) { + var self = this, + copy = SuperConstructor.prototype.filterNodes.call(this, filter); + + var parents = {}; + function findParent(u) { + var parent = self.parent(u); + if (parent === null || copy.hasNode(parent)) { + parents[u] = parent; + return parent; + } else if (parent in parents) { + return parents[parent]; + } else { + return findParent(parent); + } + } + + copy.eachNode(function(u) { copy.parent(u, findParent(u)); }); + + return copy; + }; + + return Constructor; +} + +},{"cp-data":5}],46:[function(require,module,exports){ +var Graph = require("../Graph"), + Digraph = require("../Digraph"), + CGraph = require("../CGraph"), + CDigraph = require("../CDigraph"); + +exports.decode = function(nodes, edges, Ctor) { + Ctor = Ctor || Digraph; + + if (typeOf(nodes) !== "Array") { + throw new Error("nodes is not an Array"); + } + + if (typeOf(edges) !== "Array") { + throw new Error("edges is not an Array"); + } + + if (typeof Ctor === "string") { + switch(Ctor) { + case "graph": Ctor = Graph; break; + case "digraph": Ctor = Digraph; break; + case "cgraph": Ctor = CGraph; break; + case "cdigraph": Ctor = CDigraph; break; + default: throw new Error("Unrecognized graph type: " + Ctor); + } + } + + var graph = new Ctor(); + + nodes.forEach(function(u) { + graph.addNode(u.id, u.value); + }); + + // If the graph is compound, set up children... + if (graph.parent) { + nodes.forEach(function(u) { + if (u.children) { + u.children.forEach(function(v) { + graph.parent(v, u.id); + }); + } + }); + } + + edges.forEach(function(e) { + graph.addEdge(e.id, e.u, e.v, e.value); + }); + + return graph; +}; + +exports.encode = function(graph) { + var nodes = []; + var edges = []; + + graph.eachNode(function(u, value) { + var node = {id: u, value: value}; + if (graph.children) { + var children = graph.children(u); + if (children.length) { + node.children = children; + } + } + nodes.push(node); + }); + + graph.eachEdge(function(e, u, v, value) { + edges.push({id: e, u: u, v: v, value: value}); + }); + + var type; + if (graph instanceof CDigraph) { + type = "cdigraph"; + } else if (graph instanceof CGraph) { + type = "cgraph"; + } else if (graph instanceof Digraph) { + type = "digraph"; + } else if (graph instanceof Graph) { + type = "graph"; + } else { + throw new Error("Couldn't determine type of graph: " + graph); + } + + return { nodes: nodes, edges: edges, type: type }; +}; + +function typeOf(obj) { + return Object.prototype.toString.call(obj).slice(8, -1); +} + +},{"../CDigraph":30,"../CGraph":31,"../Digraph":32,"../Graph":33}],47:[function(require,module,exports){ +/* jshint -W079 */ +var Set = require("cp-data").Set; +/* jshint +W079 */ + +exports.all = function() { + return function() { return true; }; +}; + +exports.nodesFromList = function(nodes) { + var set = new Set(nodes); + return function(u) { + return set.has(u); + }; +}; + +},{"cp-data":5}],48:[function(require,module,exports){ +var Graph = require("./Graph"), + Digraph = require("./Digraph"); + +// Side-effect based changes are lousy, but node doesn't seem to resolve the +// requires cycle. + +/** + * Returns a new directed graph using the nodes and edges from this graph. The + * new graph will have the same nodes, but will have twice the number of edges: + * each edge is split into two edges with opposite directions. Edge ids, + * consequently, are not preserved by this transformation. + */ +Graph.prototype.toDigraph = +Graph.prototype.asDirected = function() { + var g = new Digraph(); + this.eachNode(function(u, value) { g.addNode(u, value); }); + this.eachEdge(function(e, u, v, value) { + g.addEdge(null, u, v, value); + g.addEdge(null, v, u, value); + }); + return g; +}; + +/** + * Returns a new undirected graph using the nodes and edges from this graph. + * The new graph will have the same nodes, but the edges will be made + * undirected. Edge ids are preserved in this transformation. + */ +Digraph.prototype.toGraph = +Digraph.prototype.asUndirected = function() { + var g = new Graph(); + this.eachNode(function(u, value) { g.addNode(u, value); }); + this.eachEdge(function(e, u, v, value) { + g.addEdge(e, u, v, value); + }); + return g; +}; + +},{"./Digraph":32,"./Graph":33}],49:[function(require,module,exports){ +// Returns an array of all values for properties of **o**. +exports.values = function(o) { + var ks = Object.keys(o), + len = ks.length, + result = new Array(len), + i; + for (i = 0; i < len; ++i) { + result[i] = o[ks[i]]; + } + return result; +}; + +},{}],50:[function(require,module,exports){ +module.exports = '0.7.4'; + +},{}]},{},[1]) +;
\ No newline at end of file diff --git a/devtools/client/shared/vendor/immutable.js b/devtools/client/shared/vendor/immutable.js new file mode 100644 index 000000000..4903f34b3 --- /dev/null +++ b/devtools/client/shared/vendor/immutable.js @@ -0,0 +1,4997 @@ +/** + * Copyright (c) 2014-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + */ + +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global.Immutable = factory()); +}(this, function () { 'use strict';var SLICE$0 = Array.prototype.slice; + + function createClass(ctor, superClass) { + if (superClass) { + ctor.prototype = Object.create(superClass.prototype); + } + ctor.prototype.constructor = ctor; + } + + function Iterable(value) { + return isIterable(value) ? value : Seq(value); + } + + + createClass(KeyedIterable, Iterable); + function KeyedIterable(value) { + return isKeyed(value) ? value : KeyedSeq(value); + } + + + createClass(IndexedIterable, Iterable); + function IndexedIterable(value) { + return isIndexed(value) ? value : IndexedSeq(value); + } + + + createClass(SetIterable, Iterable); + function SetIterable(value) { + return isIterable(value) && !isAssociative(value) ? value : SetSeq(value); + } + + + + function isIterable(maybeIterable) { + return !!(maybeIterable && maybeIterable[IS_ITERABLE_SENTINEL]); + } + + function isKeyed(maybeKeyed) { + return !!(maybeKeyed && maybeKeyed[IS_KEYED_SENTINEL]); + } + + function isIndexed(maybeIndexed) { + return !!(maybeIndexed && maybeIndexed[IS_INDEXED_SENTINEL]); + } + + function isAssociative(maybeAssociative) { + return isKeyed(maybeAssociative) || isIndexed(maybeAssociative); + } + + function isOrdered(maybeOrdered) { + return !!(maybeOrdered && maybeOrdered[IS_ORDERED_SENTINEL]); + } + + Iterable.isIterable = isIterable; + Iterable.isKeyed = isKeyed; + Iterable.isIndexed = isIndexed; + Iterable.isAssociative = isAssociative; + Iterable.isOrdered = isOrdered; + + Iterable.Keyed = KeyedIterable; + Iterable.Indexed = IndexedIterable; + Iterable.Set = SetIterable; + + + var IS_ITERABLE_SENTINEL = '@@__IMMUTABLE_ITERABLE__@@'; + var IS_KEYED_SENTINEL = '@@__IMMUTABLE_KEYED__@@'; + var IS_INDEXED_SENTINEL = '@@__IMMUTABLE_INDEXED__@@'; + var IS_ORDERED_SENTINEL = '@@__IMMUTABLE_ORDERED__@@'; + + // Used for setting prototype methods that IE8 chokes on. + var DELETE = 'delete'; + + // Constants describing the size of trie nodes. + var SHIFT = 5; // Resulted in best performance after ______? + var SIZE = 1 << SHIFT; + var MASK = SIZE - 1; + + // A consistent shared value representing "not set" which equals nothing other + // than itself, and nothing that could be provided externally. + var NOT_SET = {}; + + // Boolean references, Rough equivalent of `bool &`. + var CHANGE_LENGTH = { value: false }; + var DID_ALTER = { value: false }; + + function MakeRef(ref) { + ref.value = false; + return ref; + } + + function SetRef(ref) { + ref && (ref.value = true); + } + + // A function which returns a value representing an "owner" for transient writes + // to tries. The return value will only ever equal itself, and will not equal + // the return of any subsequent call of this function. + function OwnerID() {} + + // http://jsperf.com/copy-array-inline + function arrCopy(arr, offset) { + offset = offset || 0; + var len = Math.max(0, arr.length - offset); + var newArr = new Array(len); + for (var ii = 0; ii < len; ii++) { + newArr[ii] = arr[ii + offset]; + } + return newArr; + } + + function ensureSize(iter) { + if (iter.size === undefined) { + iter.size = iter.__iterate(returnTrue); + } + return iter.size; + } + + function wrapIndex(iter, index) { + // This implements "is array index" which the ECMAString spec defines as: + // + // A String property name P is an array index if and only if + // ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal + // to 2^32−1. + // + // http://www.ecma-international.org/ecma-262/6.0/#sec-array-exotic-objects + if (typeof index !== 'number') { + var uint32Index = index >>> 0; // N >>> 0 is shorthand for ToUint32 + if ('' + uint32Index !== index || uint32Index === 4294967295) { + return NaN; + } + index = uint32Index; + } + return index < 0 ? ensureSize(iter) + index : index; + } + + function returnTrue() { + return true; + } + + function wholeSlice(begin, end, size) { + return (begin === 0 || (size !== undefined && begin <= -size)) && + (end === undefined || (size !== undefined && end >= size)); + } + + function resolveBegin(begin, size) { + return resolveIndex(begin, size, 0); + } + + function resolveEnd(end, size) { + return resolveIndex(end, size, size); + } + + function resolveIndex(index, size, defaultIndex) { + return index === undefined ? + defaultIndex : + index < 0 ? + Math.max(0, size + index) : + size === undefined ? + index : + Math.min(size, index); + } + + /* global Symbol */ + + var ITERATE_KEYS = 0; + var ITERATE_VALUES = 1; + var ITERATE_ENTRIES = 2; + + var REAL_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; + var FAUX_ITERATOR_SYMBOL = '@@iterator'; + + var ITERATOR_SYMBOL = REAL_ITERATOR_SYMBOL || FAUX_ITERATOR_SYMBOL; + + + function Iterator(next) { + this.next = next; + } + + Iterator.prototype.toString = function() { + return '[Iterator]'; + }; + + + Iterator.KEYS = ITERATE_KEYS; + Iterator.VALUES = ITERATE_VALUES; + Iterator.ENTRIES = ITERATE_ENTRIES; + + Iterator.prototype.inspect = + Iterator.prototype.toSource = function () { return this.toString(); } + Iterator.prototype[ITERATOR_SYMBOL] = function () { + return this; + }; + + + function iteratorValue(type, k, v, iteratorResult) { + var value = type === 0 ? k : type === 1 ? v : [k, v]; + iteratorResult ? (iteratorResult.value = value) : (iteratorResult = { + value: value, done: false + }); + return iteratorResult; + } + + function iteratorDone() { + return { value: undefined, done: true }; + } + + function hasIterator(maybeIterable) { + return !!getIteratorFn(maybeIterable); + } + + function isIterator(maybeIterator) { + return maybeIterator && typeof maybeIterator.next === 'function'; + } + + function getIterator(iterable) { + var iteratorFn = getIteratorFn(iterable); + return iteratorFn && iteratorFn.call(iterable); + } + + function getIteratorFn(iterable) { + var iteratorFn = iterable && ( + (REAL_ITERATOR_SYMBOL && iterable[REAL_ITERATOR_SYMBOL]) || + iterable[FAUX_ITERATOR_SYMBOL] + ); + if (typeof iteratorFn === 'function') { + return iteratorFn; + } + } + + function isArrayLike(value) { + return value && typeof value.length === 'number'; + } + + createClass(Seq, Iterable); + function Seq(value) { + return value === null || value === undefined ? emptySequence() : + isIterable(value) ? value.toSeq() : seqFromValue(value); + } + + Seq.of = function(/*...values*/) { + return Seq(arguments); + }; + + Seq.prototype.toSeq = function() { + return this; + }; + + Seq.prototype.toString = function() { + return this.__toString('Seq {', '}'); + }; + + Seq.prototype.cacheResult = function() { + if (!this._cache && this.__iterateUncached) { + this._cache = this.entrySeq().toArray(); + this.size = this._cache.length; + } + return this; + }; + + // abstract __iterateUncached(fn, reverse) + + Seq.prototype.__iterate = function(fn, reverse) { + return seqIterate(this, fn, reverse, true); + }; + + // abstract __iteratorUncached(type, reverse) + + Seq.prototype.__iterator = function(type, reverse) { + return seqIterator(this, type, reverse, true); + }; + + + + createClass(KeyedSeq, Seq); + function KeyedSeq(value) { + return value === null || value === undefined ? + emptySequence().toKeyedSeq() : + isIterable(value) ? + (isKeyed(value) ? value.toSeq() : value.fromEntrySeq()) : + keyedSeqFromValue(value); + } + + KeyedSeq.prototype.toKeyedSeq = function() { + return this; + }; + + + + createClass(IndexedSeq, Seq); + function IndexedSeq(value) { + return value === null || value === undefined ? emptySequence() : + !isIterable(value) ? indexedSeqFromValue(value) : + isKeyed(value) ? value.entrySeq() : value.toIndexedSeq(); + } + + IndexedSeq.of = function(/*...values*/) { + return IndexedSeq(arguments); + }; + + IndexedSeq.prototype.toIndexedSeq = function() { + return this; + }; + + IndexedSeq.prototype.toString = function() { + return this.__toString('Seq [', ']'); + }; + + IndexedSeq.prototype.__iterate = function(fn, reverse) { + return seqIterate(this, fn, reverse, false); + }; + + IndexedSeq.prototype.__iterator = function(type, reverse) { + return seqIterator(this, type, reverse, false); + }; + + + + createClass(SetSeq, Seq); + function SetSeq(value) { + return ( + value === null || value === undefined ? emptySequence() : + !isIterable(value) ? indexedSeqFromValue(value) : + isKeyed(value) ? value.entrySeq() : value + ).toSetSeq(); + } + + SetSeq.of = function(/*...values*/) { + return SetSeq(arguments); + }; + + SetSeq.prototype.toSetSeq = function() { + return this; + }; + + + + Seq.isSeq = isSeq; + Seq.Keyed = KeyedSeq; + Seq.Set = SetSeq; + Seq.Indexed = IndexedSeq; + + var IS_SEQ_SENTINEL = '@@__IMMUTABLE_SEQ__@@'; + + Seq.prototype[IS_SEQ_SENTINEL] = true; + + + + createClass(ArraySeq, IndexedSeq); + function ArraySeq(array) { + this._array = array; + this.size = array.length; + } + + ArraySeq.prototype.get = function(index, notSetValue) { + return this.has(index) ? this._array[wrapIndex(this, index)] : notSetValue; + }; + + ArraySeq.prototype.__iterate = function(fn, reverse) { + var array = this._array; + var maxIndex = array.length - 1; + for (var ii = 0; ii <= maxIndex; ii++) { + if (fn(array[reverse ? maxIndex - ii : ii], ii, this) === false) { + return ii + 1; + } + } + return ii; + }; + + ArraySeq.prototype.__iterator = function(type, reverse) { + var array = this._array; + var maxIndex = array.length - 1; + var ii = 0; + return new Iterator(function() + {return ii > maxIndex ? + iteratorDone() : + iteratorValue(type, ii, array[reverse ? maxIndex - ii++ : ii++])} + ); + }; + + + + createClass(ObjectSeq, KeyedSeq); + function ObjectSeq(object) { + var keys = Object.keys(object); + this._object = object; + this._keys = keys; + this.size = keys.length; + } + + ObjectSeq.prototype.get = function(key, notSetValue) { + if (notSetValue !== undefined && !this.has(key)) { + return notSetValue; + } + return this._object[key]; + }; + + ObjectSeq.prototype.has = function(key) { + return this._object.hasOwnProperty(key); + }; + + ObjectSeq.prototype.__iterate = function(fn, reverse) { + var object = this._object; + var keys = this._keys; + var maxIndex = keys.length - 1; + for (var ii = 0; ii <= maxIndex; ii++) { + var key = keys[reverse ? maxIndex - ii : ii]; + if (fn(object[key], key, this) === false) { + return ii + 1; + } + } + return ii; + }; + + ObjectSeq.prototype.__iterator = function(type, reverse) { + var object = this._object; + var keys = this._keys; + var maxIndex = keys.length - 1; + var ii = 0; + return new Iterator(function() { + var key = keys[reverse ? maxIndex - ii : ii]; + return ii++ > maxIndex ? + iteratorDone() : + iteratorValue(type, key, object[key]); + }); + }; + + ObjectSeq.prototype[IS_ORDERED_SENTINEL] = true; + + + createClass(IterableSeq, IndexedSeq); + function IterableSeq(iterable) { + this._iterable = iterable; + this.size = iterable.length || iterable.size; + } + + IterableSeq.prototype.__iterateUncached = function(fn, reverse) { + if (reverse) { + return this.cacheResult().__iterate(fn, reverse); + } + var iterable = this._iterable; + var iterator = getIterator(iterable); + var iterations = 0; + if (isIterator(iterator)) { + var step; + while (!(step = iterator.next()).done) { + if (fn(step.value, iterations++, this) === false) { + break; + } + } + } + return iterations; + }; + + IterableSeq.prototype.__iteratorUncached = function(type, reverse) { + if (reverse) { + return this.cacheResult().__iterator(type, reverse); + } + var iterable = this._iterable; + var iterator = getIterator(iterable); + if (!isIterator(iterator)) { + return new Iterator(iteratorDone); + } + var iterations = 0; + return new Iterator(function() { + var step = iterator.next(); + return step.done ? step : iteratorValue(type, iterations++, step.value); + }); + }; + + + + createClass(IteratorSeq, IndexedSeq); + function IteratorSeq(iterator) { + this._iterator = iterator; + this._iteratorCache = []; + } + + IteratorSeq.prototype.__iterateUncached = function(fn, reverse) { + if (reverse) { + return this.cacheResult().__iterate(fn, reverse); + } + var iterator = this._iterator; + var cache = this._iteratorCache; + var iterations = 0; + while (iterations < cache.length) { + if (fn(cache[iterations], iterations++, this) === false) { + return iterations; + } + } + var step; + while (!(step = iterator.next()).done) { + var val = step.value; + cache[iterations] = val; + if (fn(val, iterations++, this) === false) { + break; + } + } + return iterations; + }; + + IteratorSeq.prototype.__iteratorUncached = function(type, reverse) { + if (reverse) { + return this.cacheResult().__iterator(type, reverse); + } + var iterator = this._iterator; + var cache = this._iteratorCache; + var iterations = 0; + return new Iterator(function() { + if (iterations >= cache.length) { + var step = iterator.next(); + if (step.done) { + return step; + } + cache[iterations] = step.value; + } + return iteratorValue(type, iterations, cache[iterations++]); + }); + }; + + + + + // # pragma Helper functions + + function isSeq(maybeSeq) { + return !!(maybeSeq && maybeSeq[IS_SEQ_SENTINEL]); + } + + var EMPTY_SEQ; + + function emptySequence() { + return EMPTY_SEQ || (EMPTY_SEQ = new ArraySeq([])); + } + + function keyedSeqFromValue(value) { + var seq = + Array.isArray(value) ? new ArraySeq(value).fromEntrySeq() : + isIterator(value) ? new IteratorSeq(value).fromEntrySeq() : + hasIterator(value) ? new IterableSeq(value).fromEntrySeq() : + typeof value === 'object' ? new ObjectSeq(value) : + undefined; + if (!seq) { + throw new TypeError( + 'Expected Array or iterable object of [k, v] entries, '+ + 'or keyed object: ' + value + ); + } + return seq; + } + + function indexedSeqFromValue(value) { + var seq = maybeIndexedSeqFromValue(value); + if (!seq) { + throw new TypeError( + 'Expected Array or iterable object of values: ' + value + ); + } + return seq; + } + + function seqFromValue(value) { + var seq = maybeIndexedSeqFromValue(value) || + (typeof value === 'object' && new ObjectSeq(value)); + if (!seq) { + throw new TypeError( + 'Expected Array or iterable object of values, or keyed object: ' + value + ); + } + return seq; + } + + function maybeIndexedSeqFromValue(value) { + return ( + isArrayLike(value) ? new ArraySeq(value) : + isIterator(value) ? new IteratorSeq(value) : + hasIterator(value) ? new IterableSeq(value) : + undefined + ); + } + + function seqIterate(seq, fn, reverse, useKeys) { + var cache = seq._cache; + if (cache) { + var maxIndex = cache.length - 1; + for (var ii = 0; ii <= maxIndex; ii++) { + var entry = cache[reverse ? maxIndex - ii : ii]; + if (fn(entry[1], useKeys ? entry[0] : ii, seq) === false) { + return ii + 1; + } + } + return ii; + } + return seq.__iterateUncached(fn, reverse); + } + + function seqIterator(seq, type, reverse, useKeys) { + var cache = seq._cache; + if (cache) { + var maxIndex = cache.length - 1; + var ii = 0; + return new Iterator(function() { + var entry = cache[reverse ? maxIndex - ii : ii]; + return ii++ > maxIndex ? + iteratorDone() : + iteratorValue(type, useKeys ? entry[0] : ii - 1, entry[1]); + }); + } + return seq.__iteratorUncached(type, reverse); + } + + function fromJS(json, converter) { + return converter ? + fromJSWith(converter, json, '', {'': json}) : + fromJSDefault(json); + } + + function fromJSWith(converter, json, key, parentJSON) { + if (Array.isArray(json)) { + return converter.call(parentJSON, key, IndexedSeq(json).map(function(v, k) {return fromJSWith(converter, v, k, json)})); + } + if (isPlainObj(json)) { + return converter.call(parentJSON, key, KeyedSeq(json).map(function(v, k) {return fromJSWith(converter, v, k, json)})); + } + return json; + } + + function fromJSDefault(json) { + if (Array.isArray(json)) { + return IndexedSeq(json).map(fromJSDefault).toList(); + } + if (isPlainObj(json)) { + return KeyedSeq(json).map(fromJSDefault).toMap(); + } + return json; + } + + function isPlainObj(value) { + return value && (value.constructor === Object || value.constructor === undefined); + } + + /** + * An extension of the "same-value" algorithm as [described for use by ES6 Map + * and Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Key_equality) + * + * NaN is considered the same as NaN, however -0 and 0 are considered the same + * value, which is different from the algorithm described by + * [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). + * + * This is extended further to allow Objects to describe the values they + * represent, by way of `valueOf` or `equals` (and `hashCode`). + * + * Note: because of this extension, the key equality of Immutable.Map and the + * value equality of Immutable.Set will differ from ES6 Map and Set. + * + * ### Defining custom values + * + * The easiest way to describe the value an object represents is by implementing + * `valueOf`. For example, `Date` represents a value by returning a unix + * timestamp for `valueOf`: + * + * var date1 = new Date(1234567890000); // Fri Feb 13 2009 ... + * var date2 = new Date(1234567890000); + * date1.valueOf(); // 1234567890000 + * assert( date1 !== date2 ); + * assert( Immutable.is( date1, date2 ) ); + * + * Note: overriding `valueOf` may have other implications if you use this object + * where JavaScript expects a primitive, such as implicit string coercion. + * + * For more complex types, especially collections, implementing `valueOf` may + * not be performant. An alternative is to implement `equals` and `hashCode`. + * + * `equals` takes another object, presumably of similar type, and returns true + * if the it is equal. Equality is symmetrical, so the same result should be + * returned if this and the argument are flipped. + * + * assert( a.equals(b) === b.equals(a) ); + * + * `hashCode` returns a 32bit integer number representing the object which will + * be used to determine how to store the value object in a Map or Set. You must + * provide both or neither methods, one must not exist without the other. + * + * Also, an important relationship between these methods must be upheld: if two + * values are equal, they *must* return the same hashCode. If the values are not + * equal, they might have the same hashCode; this is called a hash collision, + * and while undesirable for performance reasons, it is acceptable. + * + * if (a.equals(b)) { + * assert( a.hashCode() === b.hashCode() ); + * } + * + * All Immutable collections implement `equals` and `hashCode`. + * + */ + function is(valueA, valueB) { + if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) { + return true; + } + if (!valueA || !valueB) { + return false; + } + if (typeof valueA.valueOf === 'function' && + typeof valueB.valueOf === 'function') { + valueA = valueA.valueOf(); + valueB = valueB.valueOf(); + if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) { + return true; + } + if (!valueA || !valueB) { + return false; + } + } + if (typeof valueA.equals === 'function' && + typeof valueB.equals === 'function' && + valueA.equals(valueB)) { + return true; + } + return false; + } + + function deepEqual(a, b) { + if (a === b) { + return true; + } + + if ( + !isIterable(b) || + a.size !== undefined && b.size !== undefined && a.size !== b.size || + a.__hash !== undefined && b.__hash !== undefined && a.__hash !== b.__hash || + isKeyed(a) !== isKeyed(b) || + isIndexed(a) !== isIndexed(b) || + isOrdered(a) !== isOrdered(b) + ) { + return false; + } + + if (a.size === 0 && b.size === 0) { + return true; + } + + var notAssociative = !isAssociative(a); + + if (isOrdered(a)) { + var entries = a.entries(); + return b.every(function(v, k) { + var entry = entries.next().value; + return entry && is(entry[1], v) && (notAssociative || is(entry[0], k)); + }) && entries.next().done; + } + + var flipped = false; + + if (a.size === undefined) { + if (b.size === undefined) { + if (typeof a.cacheResult === 'function') { + a.cacheResult(); + } + } else { + flipped = true; + var _ = a; + a = b; + b = _; + } + } + + var allEqual = true; + var bSize = b.__iterate(function(v, k) { + if (notAssociative ? !a.has(v) : + flipped ? !is(v, a.get(k, NOT_SET)) : !is(a.get(k, NOT_SET), v)) { + allEqual = false; + return false; + } + }); + + return allEqual && a.size === bSize; + } + + createClass(Repeat, IndexedSeq); + + function Repeat(value, times) { + if (!(this instanceof Repeat)) { + return new Repeat(value, times); + } + this._value = value; + this.size = times === undefined ? Infinity : Math.max(0, times); + if (this.size === 0) { + if (EMPTY_REPEAT) { + return EMPTY_REPEAT; + } + EMPTY_REPEAT = this; + } + } + + Repeat.prototype.toString = function() { + if (this.size === 0) { + return 'Repeat []'; + } + return 'Repeat [ ' + this._value + ' ' + this.size + ' times ]'; + }; + + Repeat.prototype.get = function(index, notSetValue) { + return this.has(index) ? this._value : notSetValue; + }; + + Repeat.prototype.includes = function(searchValue) { + return is(this._value, searchValue); + }; + + Repeat.prototype.slice = function(begin, end) { + var size = this.size; + return wholeSlice(begin, end, size) ? this : + new Repeat(this._value, resolveEnd(end, size) - resolveBegin(begin, size)); + }; + + Repeat.prototype.reverse = function() { + return this; + }; + + Repeat.prototype.indexOf = function(searchValue) { + if (is(this._value, searchValue)) { + return 0; + } + return -1; + }; + + Repeat.prototype.lastIndexOf = function(searchValue) { + if (is(this._value, searchValue)) { + return this.size; + } + return -1; + }; + + Repeat.prototype.__iterate = function(fn, reverse) { + for (var ii = 0; ii < this.size; ii++) { + if (fn(this._value, ii, this) === false) { + return ii + 1; + } + } + return ii; + }; + + Repeat.prototype.__iterator = function(type, reverse) {var this$0 = this; + var ii = 0; + return new Iterator(function() + {return ii < this$0.size ? iteratorValue(type, ii++, this$0._value) : iteratorDone()} + ); + }; + + Repeat.prototype.equals = function(other) { + return other instanceof Repeat ? + is(this._value, other._value) : + deepEqual(other); + }; + + + var EMPTY_REPEAT; + + function invariant(condition, error) { + if (!condition) throw new Error(error); + } + + createClass(Range, IndexedSeq); + + function Range(start, end, step) { + if (!(this instanceof Range)) { + return new Range(start, end, step); + } + invariant(step !== 0, 'Cannot step a Range by 0'); + start = start || 0; + if (end === undefined) { + end = Infinity; + } + step = step === undefined ? 1 : Math.abs(step); + if (end < start) { + step = -step; + } + this._start = start; + this._end = end; + this._step = step; + this.size = Math.max(0, Math.ceil((end - start) / step - 1) + 1); + if (this.size === 0) { + if (EMPTY_RANGE) { + return EMPTY_RANGE; + } + EMPTY_RANGE = this; + } + } + + Range.prototype.toString = function() { + if (this.size === 0) { + return 'Range []'; + } + return 'Range [ ' + + this._start + '...' + this._end + + (this._step !== 1 ? ' by ' + this._step : '') + + ' ]'; + }; + + Range.prototype.get = function(index, notSetValue) { + return this.has(index) ? + this._start + wrapIndex(this, index) * this._step : + notSetValue; + }; + + Range.prototype.includes = function(searchValue) { + var possibleIndex = (searchValue - this._start) / this._step; + return possibleIndex >= 0 && + possibleIndex < this.size && + possibleIndex === Math.floor(possibleIndex); + }; + + Range.prototype.slice = function(begin, end) { + if (wholeSlice(begin, end, this.size)) { + return this; + } + begin = resolveBegin(begin, this.size); + end = resolveEnd(end, this.size); + if (end <= begin) { + return new Range(0, 0); + } + return new Range(this.get(begin, this._end), this.get(end, this._end), this._step); + }; + + Range.prototype.indexOf = function(searchValue) { + var offsetValue = searchValue - this._start; + if (offsetValue % this._step === 0) { + var index = offsetValue / this._step; + if (index >= 0 && index < this.size) { + return index + } + } + return -1; + }; + + Range.prototype.lastIndexOf = function(searchValue) { + return this.indexOf(searchValue); + }; + + Range.prototype.__iterate = function(fn, reverse) { + var maxIndex = this.size - 1; + var step = this._step; + var value = reverse ? this._start + maxIndex * step : this._start; + for (var ii = 0; ii <= maxIndex; ii++) { + if (fn(value, ii, this) === false) { + return ii + 1; + } + value += reverse ? -step : step; + } + return ii; + }; + + Range.prototype.__iterator = function(type, reverse) { + var maxIndex = this.size - 1; + var step = this._step; + var value = reverse ? this._start + maxIndex * step : this._start; + var ii = 0; + return new Iterator(function() { + var v = value; + value += reverse ? -step : step; + return ii > maxIndex ? iteratorDone() : iteratorValue(type, ii++, v); + }); + }; + + Range.prototype.equals = function(other) { + return other instanceof Range ? + this._start === other._start && + this._end === other._end && + this._step === other._step : + deepEqual(this, other); + }; + + + var EMPTY_RANGE; + + createClass(Collection, Iterable); + function Collection() { + throw TypeError('Abstract'); + } + + + createClass(KeyedCollection, Collection);function KeyedCollection() {} + + createClass(IndexedCollection, Collection);function IndexedCollection() {} + + createClass(SetCollection, Collection);function SetCollection() {} + + + Collection.Keyed = KeyedCollection; + Collection.Indexed = IndexedCollection; + Collection.Set = SetCollection; + + var imul = + typeof Math.imul === 'function' && Math.imul(0xffffffff, 2) === -2 ? + Math.imul : + function imul(a, b) { + a = a | 0; // int + b = b | 0; // int + var c = a & 0xffff; + var d = b & 0xffff; + // Shift by 0 fixes the sign on the high part. + return (c * d) + ((((a >>> 16) * d + c * (b >>> 16)) << 16) >>> 0) | 0; // int + }; + + // v8 has an optimization for storing 31-bit signed numbers. + // Values which have either 00 or 11 as the high order bits qualify. + // This function drops the highest order bit in a signed number, maintaining + // the sign bit. + function smi(i32) { + return ((i32 >>> 1) & 0x40000000) | (i32 & 0xBFFFFFFF); + } + + function hash(o) { + if (o === false || o === null || o === undefined) { + return 0; + } + if (typeof o.valueOf === 'function') { + o = o.valueOf(); + if (o === false || o === null || o === undefined) { + return 0; + } + } + if (o === true) { + return 1; + } + var type = typeof o; + if (type === 'number') { + var h = o | 0; + if (h !== o) { + h ^= o * 0xFFFFFFFF; + } + while (o > 0xFFFFFFFF) { + o /= 0xFFFFFFFF; + h ^= o; + } + return smi(h); + } + if (type === 'string') { + return o.length > STRING_HASH_CACHE_MIN_STRLEN ? cachedHashString(o) : hashString(o); + } + if (typeof o.hashCode === 'function') { + return o.hashCode(); + } + if (type === 'object') { + return hashJSObj(o); + } + if (typeof o.toString === 'function') { + return hashString(o.toString()); + } + throw new Error('Value type ' + type + ' cannot be hashed.'); + } + + function cachedHashString(string) { + var hash = stringHashCache[string]; + if (hash === undefined) { + hash = hashString(string); + if (STRING_HASH_CACHE_SIZE === STRING_HASH_CACHE_MAX_SIZE) { + STRING_HASH_CACHE_SIZE = 0; + stringHashCache = {}; + } + STRING_HASH_CACHE_SIZE++; + stringHashCache[string] = hash; + } + return hash; + } + + // http://jsperf.com/hashing-strings + function hashString(string) { + // This is the hash from JVM + // The hash code for a string is computed as + // s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1], + // where s[i] is the ith character of the string and n is the length of + // the string. We "mod" the result to make it between 0 (inclusive) and 2^31 + // (exclusive) by dropping high bits. + var hash = 0; + for (var ii = 0; ii < string.length; ii++) { + hash = 31 * hash + string.charCodeAt(ii) | 0; + } + return smi(hash); + } + + function hashJSObj(obj) { + var hash; + if (usingWeakMap) { + hash = weakMap.get(obj); + if (hash !== undefined) { + return hash; + } + } + + hash = obj[UID_HASH_KEY]; + if (hash !== undefined) { + return hash; + } + + if (!canDefineProperty) { + hash = obj.propertyIsEnumerable && obj.propertyIsEnumerable[UID_HASH_KEY]; + if (hash !== undefined) { + return hash; + } + + hash = getIENodeHash(obj); + if (hash !== undefined) { + return hash; + } + } + + hash = ++objHashUID; + if (objHashUID & 0x40000000) { + objHashUID = 0; + } + + if (usingWeakMap) { + weakMap.set(obj, hash); + } else if (isExtensible !== undefined && isExtensible(obj) === false) { + throw new Error('Non-extensible objects are not allowed as keys.'); + } else if (canDefineProperty) { + Object.defineProperty(obj, UID_HASH_KEY, { + 'enumerable': false, + 'configurable': false, + 'writable': false, + 'value': hash + }); + } else if (obj.propertyIsEnumerable !== undefined && + obj.propertyIsEnumerable === obj.constructor.prototype.propertyIsEnumerable) { + // Since we can't define a non-enumerable property on the object + // we'll hijack one of the less-used non-enumerable properties to + // save our hash on it. Since this is a function it will not show up in + // `JSON.stringify` which is what we want. + obj.propertyIsEnumerable = function() { + return this.constructor.prototype.propertyIsEnumerable.apply(this, arguments); + }; + obj.propertyIsEnumerable[UID_HASH_KEY] = hash; + } else if (obj.nodeType !== undefined) { + // At this point we couldn't get the IE `uniqueID` to use as a hash + // and we couldn't use a non-enumerable property to exploit the + // dontEnum bug so we simply add the `UID_HASH_KEY` on the node + // itself. + obj[UID_HASH_KEY] = hash; + } else { + throw new Error('Unable to set a non-enumerable property on object.'); + } + + return hash; + } + + // Get references to ES5 object methods. + var isExtensible = Object.isExtensible; + + // True if Object.defineProperty works as expected. IE8 fails this test. + var canDefineProperty = (function() { + try { + Object.defineProperty({}, '@', {}); + return true; + } catch (e) { + return false; + } + }()); + + // IE has a `uniqueID` property on DOM nodes. We can construct the hash from it + // and avoid memory leaks from the IE cloneNode bug. + function getIENodeHash(node) { + if (node && node.nodeType > 0) { + switch (node.nodeType) { + case 1: // Element + return node.uniqueID; + case 9: // Document + return node.documentElement && node.documentElement.uniqueID; + } + } + } + + // If possible, use a WeakMap. + var usingWeakMap = typeof WeakMap === 'function'; + var weakMap; + if (usingWeakMap) { + weakMap = new WeakMap(); + } + + var objHashUID = 0; + + var UID_HASH_KEY = '__immutablehash__'; + if (typeof Symbol === 'function') { + UID_HASH_KEY = Symbol(UID_HASH_KEY); + } + + var STRING_HASH_CACHE_MIN_STRLEN = 16; + var STRING_HASH_CACHE_MAX_SIZE = 255; + var STRING_HASH_CACHE_SIZE = 0; + var stringHashCache = {}; + + function assertNotInfinite(size) { + invariant( + size !== Infinity, + 'Cannot perform this action with an infinite size.' + ); + } + + createClass(Map, KeyedCollection); + + // @pragma Construction + + function Map(value) { + return value === null || value === undefined ? emptyMap() : + isMap(value) && !isOrdered(value) ? value : + emptyMap().withMutations(function(map ) { + var iter = KeyedIterable(value); + assertNotInfinite(iter.size); + iter.forEach(function(v, k) {return map.set(k, v)}); + }); + } + + Map.of = function() {var keyValues = SLICE$0.call(arguments, 0); + return emptyMap().withMutations(function(map ) { + for (var i = 0; i < keyValues.length; i += 2) { + if (i + 1 >= keyValues.length) { + throw new Error('Missing value for key: ' + keyValues[i]); + } + map.set(keyValues[i], keyValues[i + 1]); + } + }); + }; + + Map.prototype.toString = function() { + return this.__toString('Map {', '}'); + }; + + // @pragma Access + + Map.prototype.get = function(k, notSetValue) { + return this._root ? + this._root.get(0, undefined, k, notSetValue) : + notSetValue; + }; + + // @pragma Modification + + Map.prototype.set = function(k, v) { + return updateMap(this, k, v); + }; + + Map.prototype.setIn = function(keyPath, v) { + return this.updateIn(keyPath, NOT_SET, function() {return v}); + }; + + Map.prototype.remove = function(k) { + return updateMap(this, k, NOT_SET); + }; + + Map.prototype.deleteIn = function(keyPath) { + return this.updateIn(keyPath, function() {return NOT_SET}); + }; + + Map.prototype.update = function(k, notSetValue, updater) { + return arguments.length === 1 ? + k(this) : + this.updateIn([k], notSetValue, updater); + }; + + Map.prototype.updateIn = function(keyPath, notSetValue, updater) { + if (!updater) { + updater = notSetValue; + notSetValue = undefined; + } + var updatedValue = updateInDeepMap( + this, + forceIterator(keyPath), + notSetValue, + updater + ); + return updatedValue === NOT_SET ? undefined : updatedValue; + }; + + Map.prototype.clear = function() { + if (this.size === 0) { + return this; + } + if (this.__ownerID) { + this.size = 0; + this._root = null; + this.__hash = undefined; + this.__altered = true; + return this; + } + return emptyMap(); + }; + + // @pragma Composition + + Map.prototype.merge = function(/*...iters*/) { + return mergeIntoMapWith(this, undefined, arguments); + }; + + Map.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1); + return mergeIntoMapWith(this, merger, iters); + }; + + Map.prototype.mergeIn = function(keyPath) {var iters = SLICE$0.call(arguments, 1); + return this.updateIn( + keyPath, + emptyMap(), + function(m ) {return typeof m.merge === 'function' ? + m.merge.apply(m, iters) : + iters[iters.length - 1]} + ); + }; + + Map.prototype.mergeDeep = function(/*...iters*/) { + return mergeIntoMapWith(this, deepMerger, arguments); + }; + + Map.prototype.mergeDeepWith = function(merger) {var iters = SLICE$0.call(arguments, 1); + return mergeIntoMapWith(this, deepMergerWith(merger), iters); + }; + + Map.prototype.mergeDeepIn = function(keyPath) {var iters = SLICE$0.call(arguments, 1); + return this.updateIn( + keyPath, + emptyMap(), + function(m ) {return typeof m.mergeDeep === 'function' ? + m.mergeDeep.apply(m, iters) : + iters[iters.length - 1]} + ); + }; + + Map.prototype.sort = function(comparator) { + // Late binding + return OrderedMap(sortFactory(this, comparator)); + }; + + Map.prototype.sortBy = function(mapper, comparator) { + // Late binding + return OrderedMap(sortFactory(this, comparator, mapper)); + }; + + // @pragma Mutability + + Map.prototype.withMutations = function(fn) { + var mutable = this.asMutable(); + fn(mutable); + return mutable.wasAltered() ? mutable.__ensureOwner(this.__ownerID) : this; + }; + + Map.prototype.asMutable = function() { + return this.__ownerID ? this : this.__ensureOwner(new OwnerID()); + }; + + Map.prototype.asImmutable = function() { + return this.__ensureOwner(); + }; + + Map.prototype.wasAltered = function() { + return this.__altered; + }; + + Map.prototype.__iterator = function(type, reverse) { + return new MapIterator(this, type, reverse); + }; + + Map.prototype.__iterate = function(fn, reverse) {var this$0 = this; + var iterations = 0; + this._root && this._root.iterate(function(entry ) { + iterations++; + return fn(entry[1], entry[0], this$0); + }, reverse); + return iterations; + }; + + Map.prototype.__ensureOwner = function(ownerID) { + if (ownerID === this.__ownerID) { + return this; + } + if (!ownerID) { + this.__ownerID = ownerID; + this.__altered = false; + return this; + } + return makeMap(this.size, this._root, ownerID, this.__hash); + }; + + + function isMap(maybeMap) { + return !!(maybeMap && maybeMap[IS_MAP_SENTINEL]); + } + + Map.isMap = isMap; + + var IS_MAP_SENTINEL = '@@__IMMUTABLE_MAP__@@'; + + var MapPrototype = Map.prototype; + MapPrototype[IS_MAP_SENTINEL] = true; + MapPrototype[DELETE] = MapPrototype.remove; + MapPrototype.removeIn = MapPrototype.deleteIn; + + + // #pragma Trie Nodes + + + + function ArrayMapNode(ownerID, entries) { + this.ownerID = ownerID; + this.entries = entries; + } + + ArrayMapNode.prototype.get = function(shift, keyHash, key, notSetValue) { + var entries = this.entries; + for (var ii = 0, len = entries.length; ii < len; ii++) { + if (is(key, entries[ii][0])) { + return entries[ii][1]; + } + } + return notSetValue; + }; + + ArrayMapNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { + var removed = value === NOT_SET; + + var entries = this.entries; + var idx = 0; + for (var len = entries.length; idx < len; idx++) { + if (is(key, entries[idx][0])) { + break; + } + } + var exists = idx < len; + + if (exists ? entries[idx][1] === value : removed) { + return this; + } + + SetRef(didAlter); + (removed || !exists) && SetRef(didChangeSize); + + if (removed && entries.length === 1) { + return; // undefined + } + + if (!exists && !removed && entries.length >= MAX_ARRAY_MAP_SIZE) { + return createNodes(ownerID, entries, key, value); + } + + var isEditable = ownerID && ownerID === this.ownerID; + var newEntries = isEditable ? entries : arrCopy(entries); + + if (exists) { + if (removed) { + idx === len - 1 ? newEntries.pop() : (newEntries[idx] = newEntries.pop()); + } else { + newEntries[idx] = [key, value]; + } + } else { + newEntries.push([key, value]); + } + + if (isEditable) { + this.entries = newEntries; + return this; + } + + return new ArrayMapNode(ownerID, newEntries); + }; + + + + + function BitmapIndexedNode(ownerID, bitmap, nodes) { + this.ownerID = ownerID; + this.bitmap = bitmap; + this.nodes = nodes; + } + + BitmapIndexedNode.prototype.get = function(shift, keyHash, key, notSetValue) { + if (keyHash === undefined) { + keyHash = hash(key); + } + var bit = (1 << ((shift === 0 ? keyHash : keyHash >>> shift) & MASK)); + var bitmap = this.bitmap; + return (bitmap & bit) === 0 ? notSetValue : + this.nodes[popCount(bitmap & (bit - 1))].get(shift + SHIFT, keyHash, key, notSetValue); + }; + + BitmapIndexedNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { + if (keyHash === undefined) { + keyHash = hash(key); + } + var keyHashFrag = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; + var bit = 1 << keyHashFrag; + var bitmap = this.bitmap; + var exists = (bitmap & bit) !== 0; + + if (!exists && value === NOT_SET) { + return this; + } + + var idx = popCount(bitmap & (bit - 1)); + var nodes = this.nodes; + var node = exists ? nodes[idx] : undefined; + var newNode = updateNode(node, ownerID, shift + SHIFT, keyHash, key, value, didChangeSize, didAlter); + + if (newNode === node) { + return this; + } + + if (!exists && newNode && nodes.length >= MAX_BITMAP_INDEXED_SIZE) { + return expandNodes(ownerID, nodes, bitmap, keyHashFrag, newNode); + } + + if (exists && !newNode && nodes.length === 2 && isLeafNode(nodes[idx ^ 1])) { + return nodes[idx ^ 1]; + } + + if (exists && newNode && nodes.length === 1 && isLeafNode(newNode)) { + return newNode; + } + + var isEditable = ownerID && ownerID === this.ownerID; + var newBitmap = exists ? newNode ? bitmap : bitmap ^ bit : bitmap | bit; + var newNodes = exists ? newNode ? + setIn(nodes, idx, newNode, isEditable) : + spliceOut(nodes, idx, isEditable) : + spliceIn(nodes, idx, newNode, isEditable); + + if (isEditable) { + this.bitmap = newBitmap; + this.nodes = newNodes; + return this; + } + + return new BitmapIndexedNode(ownerID, newBitmap, newNodes); + }; + + + + + function HashArrayMapNode(ownerID, count, nodes) { + this.ownerID = ownerID; + this.count = count; + this.nodes = nodes; + } + + HashArrayMapNode.prototype.get = function(shift, keyHash, key, notSetValue) { + if (keyHash === undefined) { + keyHash = hash(key); + } + var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; + var node = this.nodes[idx]; + return node ? node.get(shift + SHIFT, keyHash, key, notSetValue) : notSetValue; + }; + + HashArrayMapNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { + if (keyHash === undefined) { + keyHash = hash(key); + } + var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; + var removed = value === NOT_SET; + var nodes = this.nodes; + var node = nodes[idx]; + + if (removed && !node) { + return this; + } + + var newNode = updateNode(node, ownerID, shift + SHIFT, keyHash, key, value, didChangeSize, didAlter); + if (newNode === node) { + return this; + } + + var newCount = this.count; + if (!node) { + newCount++; + } else if (!newNode) { + newCount--; + if (newCount < MIN_HASH_ARRAY_MAP_SIZE) { + return packNodes(ownerID, nodes, newCount, idx); + } + } + + var isEditable = ownerID && ownerID === this.ownerID; + var newNodes = setIn(nodes, idx, newNode, isEditable); + + if (isEditable) { + this.count = newCount; + this.nodes = newNodes; + return this; + } + + return new HashArrayMapNode(ownerID, newCount, newNodes); + }; + + + + + function HashCollisionNode(ownerID, keyHash, entries) { + this.ownerID = ownerID; + this.keyHash = keyHash; + this.entries = entries; + } + + HashCollisionNode.prototype.get = function(shift, keyHash, key, notSetValue) { + var entries = this.entries; + for (var ii = 0, len = entries.length; ii < len; ii++) { + if (is(key, entries[ii][0])) { + return entries[ii][1]; + } + } + return notSetValue; + }; + + HashCollisionNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { + if (keyHash === undefined) { + keyHash = hash(key); + } + + var removed = value === NOT_SET; + + if (keyHash !== this.keyHash) { + if (removed) { + return this; + } + SetRef(didAlter); + SetRef(didChangeSize); + return mergeIntoNode(this, ownerID, shift, keyHash, [key, value]); + } + + var entries = this.entries; + var idx = 0; + for (var len = entries.length; idx < len; idx++) { + if (is(key, entries[idx][0])) { + break; + } + } + var exists = idx < len; + + if (exists ? entries[idx][1] === value : removed) { + return this; + } + + SetRef(didAlter); + (removed || !exists) && SetRef(didChangeSize); + + if (removed && len === 2) { + return new ValueNode(ownerID, this.keyHash, entries[idx ^ 1]); + } + + var isEditable = ownerID && ownerID === this.ownerID; + var newEntries = isEditable ? entries : arrCopy(entries); + + if (exists) { + if (removed) { + idx === len - 1 ? newEntries.pop() : (newEntries[idx] = newEntries.pop()); + } else { + newEntries[idx] = [key, value]; + } + } else { + newEntries.push([key, value]); + } + + if (isEditable) { + this.entries = newEntries; + return this; + } + + return new HashCollisionNode(ownerID, this.keyHash, newEntries); + }; + + + + + function ValueNode(ownerID, keyHash, entry) { + this.ownerID = ownerID; + this.keyHash = keyHash; + this.entry = entry; + } + + ValueNode.prototype.get = function(shift, keyHash, key, notSetValue) { + return is(key, this.entry[0]) ? this.entry[1] : notSetValue; + }; + + ValueNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { + var removed = value === NOT_SET; + var keyMatch = is(key, this.entry[0]); + if (keyMatch ? value === this.entry[1] : removed) { + return this; + } + + SetRef(didAlter); + + if (removed) { + SetRef(didChangeSize); + return; // undefined + } + + if (keyMatch) { + if (ownerID && ownerID === this.ownerID) { + this.entry[1] = value; + return this; + } + return new ValueNode(ownerID, this.keyHash, [key, value]); + } + + SetRef(didChangeSize); + return mergeIntoNode(this, ownerID, shift, hash(key), [key, value]); + }; + + + + // #pragma Iterators + + ArrayMapNode.prototype.iterate = + HashCollisionNode.prototype.iterate = function (fn, reverse) { + var entries = this.entries; + for (var ii = 0, maxIndex = entries.length - 1; ii <= maxIndex; ii++) { + if (fn(entries[reverse ? maxIndex - ii : ii]) === false) { + return false; + } + } + } + + BitmapIndexedNode.prototype.iterate = + HashArrayMapNode.prototype.iterate = function (fn, reverse) { + var nodes = this.nodes; + for (var ii = 0, maxIndex = nodes.length - 1; ii <= maxIndex; ii++) { + var node = nodes[reverse ? maxIndex - ii : ii]; + if (node && node.iterate(fn, reverse) === false) { + return false; + } + } + } + + ValueNode.prototype.iterate = function (fn, reverse) { + return fn(this.entry); + } + + createClass(MapIterator, Iterator); + + function MapIterator(map, type, reverse) { + this._type = type; + this._reverse = reverse; + this._stack = map._root && mapIteratorFrame(map._root); + } + + MapIterator.prototype.next = function() { + var type = this._type; + var stack = this._stack; + while (stack) { + var node = stack.node; + var index = stack.index++; + var maxIndex; + if (node.entry) { + if (index === 0) { + return mapIteratorValue(type, node.entry); + } + } else if (node.entries) { + maxIndex = node.entries.length - 1; + if (index <= maxIndex) { + return mapIteratorValue(type, node.entries[this._reverse ? maxIndex - index : index]); + } + } else { + maxIndex = node.nodes.length - 1; + if (index <= maxIndex) { + var subNode = node.nodes[this._reverse ? maxIndex - index : index]; + if (subNode) { + if (subNode.entry) { + return mapIteratorValue(type, subNode.entry); + } + stack = this._stack = mapIteratorFrame(subNode, stack); + } + continue; + } + } + stack = this._stack = this._stack.__prev; + } + return iteratorDone(); + }; + + + function mapIteratorValue(type, entry) { + return iteratorValue(type, entry[0], entry[1]); + } + + function mapIteratorFrame(node, prev) { + return { + node: node, + index: 0, + __prev: prev + }; + } + + function makeMap(size, root, ownerID, hash) { + var map = Object.create(MapPrototype); + map.size = size; + map._root = root; + map.__ownerID = ownerID; + map.__hash = hash; + map.__altered = false; + return map; + } + + var EMPTY_MAP; + function emptyMap() { + return EMPTY_MAP || (EMPTY_MAP = makeMap(0)); + } + + function updateMap(map, k, v) { + var newRoot; + var newSize; + if (!map._root) { + if (v === NOT_SET) { + return map; + } + newSize = 1; + newRoot = new ArrayMapNode(map.__ownerID, [[k, v]]); + } else { + var didChangeSize = MakeRef(CHANGE_LENGTH); + var didAlter = MakeRef(DID_ALTER); + newRoot = updateNode(map._root, map.__ownerID, 0, undefined, k, v, didChangeSize, didAlter); + if (!didAlter.value) { + return map; + } + newSize = map.size + (didChangeSize.value ? v === NOT_SET ? -1 : 1 : 0); + } + if (map.__ownerID) { + map.size = newSize; + map._root = newRoot; + map.__hash = undefined; + map.__altered = true; + return map; + } + return newRoot ? makeMap(newSize, newRoot) : emptyMap(); + } + + function updateNode(node, ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { + if (!node) { + if (value === NOT_SET) { + return node; + } + SetRef(didAlter); + SetRef(didChangeSize); + return new ValueNode(ownerID, keyHash, [key, value]); + } + return node.update(ownerID, shift, keyHash, key, value, didChangeSize, didAlter); + } + + function isLeafNode(node) { + return node.constructor === ValueNode || node.constructor === HashCollisionNode; + } + + function mergeIntoNode(node, ownerID, shift, keyHash, entry) { + if (node.keyHash === keyHash) { + return new HashCollisionNode(ownerID, keyHash, [node.entry, entry]); + } + + var idx1 = (shift === 0 ? node.keyHash : node.keyHash >>> shift) & MASK; + var idx2 = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; + + var newNode; + var nodes = idx1 === idx2 ? + [mergeIntoNode(node, ownerID, shift + SHIFT, keyHash, entry)] : + ((newNode = new ValueNode(ownerID, keyHash, entry)), idx1 < idx2 ? [node, newNode] : [newNode, node]); + + return new BitmapIndexedNode(ownerID, (1 << idx1) | (1 << idx2), nodes); + } + + function createNodes(ownerID, entries, key, value) { + if (!ownerID) { + ownerID = new OwnerID(); + } + var node = new ValueNode(ownerID, hash(key), [key, value]); + for (var ii = 0; ii < entries.length; ii++) { + var entry = entries[ii]; + node = node.update(ownerID, 0, undefined, entry[0], entry[1]); + } + return node; + } + + function packNodes(ownerID, nodes, count, excluding) { + var bitmap = 0; + var packedII = 0; + var packedNodes = new Array(count); + for (var ii = 0, bit = 1, len = nodes.length; ii < len; ii++, bit <<= 1) { + var node = nodes[ii]; + if (node !== undefined && ii !== excluding) { + bitmap |= bit; + packedNodes[packedII++] = node; + } + } + return new BitmapIndexedNode(ownerID, bitmap, packedNodes); + } + + function expandNodes(ownerID, nodes, bitmap, including, node) { + var count = 0; + var expandedNodes = new Array(SIZE); + for (var ii = 0; bitmap !== 0; ii++, bitmap >>>= 1) { + expandedNodes[ii] = bitmap & 1 ? nodes[count++] : undefined; + } + expandedNodes[including] = node; + return new HashArrayMapNode(ownerID, count + 1, expandedNodes); + } + + function mergeIntoMapWith(map, merger, iterables) { + var iters = []; + for (var ii = 0; ii < iterables.length; ii++) { + var value = iterables[ii]; + var iter = KeyedIterable(value); + if (!isIterable(value)) { + iter = iter.map(function(v ) {return fromJS(v)}); + } + iters.push(iter); + } + return mergeIntoCollectionWith(map, merger, iters); + } + + function deepMerger(existing, value, key) { + return existing && existing.mergeDeep && isIterable(value) ? + existing.mergeDeep(value) : + is(existing, value) ? existing : value; + } + + function deepMergerWith(merger) { + return function(existing, value, key) { + if (existing && existing.mergeDeepWith && isIterable(value)) { + return existing.mergeDeepWith(merger, value); + } + var nextValue = merger(existing, value, key); + return is(existing, nextValue) ? existing : nextValue; + }; + } + + function mergeIntoCollectionWith(collection, merger, iters) { + iters = iters.filter(function(x ) {return x.size !== 0}); + if (iters.length === 0) { + return collection; + } + if (collection.size === 0 && !collection.__ownerID && iters.length === 1) { + return collection.constructor(iters[0]); + } + return collection.withMutations(function(collection ) { + var mergeIntoMap = merger ? + function(value, key) { + collection.update(key, NOT_SET, function(existing ) + {return existing === NOT_SET ? value : merger(existing, value, key)} + ); + } : + function(value, key) { + collection.set(key, value); + } + for (var ii = 0; ii < iters.length; ii++) { + iters[ii].forEach(mergeIntoMap); + } + }); + } + + function updateInDeepMap(existing, keyPathIter, notSetValue, updater) { + var isNotSet = existing === NOT_SET; + var step = keyPathIter.next(); + if (step.done) { + var existingValue = isNotSet ? notSetValue : existing; + var newValue = updater(existingValue); + return newValue === existingValue ? existing : newValue; + } + invariant( + isNotSet || (existing && existing.set), + 'invalid keyPath' + ); + var key = step.value; + var nextExisting = isNotSet ? NOT_SET : existing.get(key, NOT_SET); + var nextUpdated = updateInDeepMap( + nextExisting, + keyPathIter, + notSetValue, + updater + ); + return nextUpdated === nextExisting ? existing : + nextUpdated === NOT_SET ? existing.remove(key) : + (isNotSet ? emptyMap() : existing).set(key, nextUpdated); + } + + function popCount(x) { + x = x - ((x >> 1) & 0x55555555); + x = (x & 0x33333333) + ((x >> 2) & 0x33333333); + x = (x + (x >> 4)) & 0x0f0f0f0f; + x = x + (x >> 8); + x = x + (x >> 16); + return x & 0x7f; + } + + function setIn(array, idx, val, canEdit) { + var newArray = canEdit ? array : arrCopy(array); + newArray[idx] = val; + return newArray; + } + + function spliceIn(array, idx, val, canEdit) { + var newLen = array.length + 1; + if (canEdit && idx + 1 === newLen) { + array[idx] = val; + return array; + } + var newArray = new Array(newLen); + var after = 0; + for (var ii = 0; ii < newLen; ii++) { + if (ii === idx) { + newArray[ii] = val; + after = -1; + } else { + newArray[ii] = array[ii + after]; + } + } + return newArray; + } + + function spliceOut(array, idx, canEdit) { + var newLen = array.length - 1; + if (canEdit && idx === newLen) { + array.pop(); + return array; + } + var newArray = new Array(newLen); + var after = 0; + for (var ii = 0; ii < newLen; ii++) { + if (ii === idx) { + after = 1; + } + newArray[ii] = array[ii + after]; + } + return newArray; + } + + var MAX_ARRAY_MAP_SIZE = SIZE / 4; + var MAX_BITMAP_INDEXED_SIZE = SIZE / 2; + var MIN_HASH_ARRAY_MAP_SIZE = SIZE / 4; + + createClass(List, IndexedCollection); + + // @pragma Construction + + function List(value) { + var empty = emptyList(); + if (value === null || value === undefined) { + return empty; + } + if (isList(value)) { + return value; + } + var iter = IndexedIterable(value); + var size = iter.size; + if (size === 0) { + return empty; + } + assertNotInfinite(size); + if (size > 0 && size < SIZE) { + return makeList(0, size, SHIFT, null, new VNode(iter.toArray())); + } + return empty.withMutations(function(list ) { + list.setSize(size); + iter.forEach(function(v, i) {return list.set(i, v)}); + }); + } + + List.of = function(/*...values*/) { + return this(arguments); + }; + + List.prototype.toString = function() { + return this.__toString('List [', ']'); + }; + + // @pragma Access + + List.prototype.get = function(index, notSetValue) { + index = wrapIndex(this, index); + if (index >= 0 && index < this.size) { + index += this._origin; + var node = listNodeFor(this, index); + return node && node.array[index & MASK]; + } + return notSetValue; + }; + + // @pragma Modification + + List.prototype.set = function(index, value) { + return updateList(this, index, value); + }; + + List.prototype.remove = function(index) { + return !this.has(index) ? this : + index === 0 ? this.shift() : + index === this.size - 1 ? this.pop() : + this.splice(index, 1); + }; + + List.prototype.insert = function(index, value) { + return this.splice(index, 0, value); + }; + + List.prototype.clear = function() { + if (this.size === 0) { + return this; + } + if (this.__ownerID) { + this.size = this._origin = this._capacity = 0; + this._level = SHIFT; + this._root = this._tail = null; + this.__hash = undefined; + this.__altered = true; + return this; + } + return emptyList(); + }; + + List.prototype.push = function(/*...values*/) { + var values = arguments; + var oldSize = this.size; + return this.withMutations(function(list ) { + setListBounds(list, 0, oldSize + values.length); + for (var ii = 0; ii < values.length; ii++) { + list.set(oldSize + ii, values[ii]); + } + }); + }; + + List.prototype.pop = function() { + return setListBounds(this, 0, -1); + }; + + List.prototype.unshift = function(/*...values*/) { + var values = arguments; + return this.withMutations(function(list ) { + setListBounds(list, -values.length); + for (var ii = 0; ii < values.length; ii++) { + list.set(ii, values[ii]); + } + }); + }; + + List.prototype.shift = function() { + return setListBounds(this, 1); + }; + + // @pragma Composition + + List.prototype.merge = function(/*...iters*/) { + return mergeIntoListWith(this, undefined, arguments); + }; + + List.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1); + return mergeIntoListWith(this, merger, iters); + }; + + List.prototype.mergeDeep = function(/*...iters*/) { + return mergeIntoListWith(this, deepMerger, arguments); + }; + + List.prototype.mergeDeepWith = function(merger) {var iters = SLICE$0.call(arguments, 1); + return mergeIntoListWith(this, deepMergerWith(merger), iters); + }; + + List.prototype.setSize = function(size) { + return setListBounds(this, 0, size); + }; + + // @pragma Iteration + + List.prototype.slice = function(begin, end) { + var size = this.size; + if (wholeSlice(begin, end, size)) { + return this; + } + return setListBounds( + this, + resolveBegin(begin, size), + resolveEnd(end, size) + ); + }; + + List.prototype.__iterator = function(type, reverse) { + var index = 0; + var values = iterateList(this, reverse); + return new Iterator(function() { + var value = values(); + return value === DONE ? + iteratorDone() : + iteratorValue(type, index++, value); + }); + }; + + List.prototype.__iterate = function(fn, reverse) { + var index = 0; + var values = iterateList(this, reverse); + var value; + while ((value = values()) !== DONE) { + if (fn(value, index++, this) === false) { + break; + } + } + return index; + }; + + List.prototype.__ensureOwner = function(ownerID) { + if (ownerID === this.__ownerID) { + return this; + } + if (!ownerID) { + this.__ownerID = ownerID; + return this; + } + return makeList(this._origin, this._capacity, this._level, this._root, this._tail, ownerID, this.__hash); + }; + + + function isList(maybeList) { + return !!(maybeList && maybeList[IS_LIST_SENTINEL]); + } + + List.isList = isList; + + var IS_LIST_SENTINEL = '@@__IMMUTABLE_LIST__@@'; + + var ListPrototype = List.prototype; + ListPrototype[IS_LIST_SENTINEL] = true; + ListPrototype[DELETE] = ListPrototype.remove; + ListPrototype.setIn = MapPrototype.setIn; + ListPrototype.deleteIn = + ListPrototype.removeIn = MapPrototype.removeIn; + ListPrototype.update = MapPrototype.update; + ListPrototype.updateIn = MapPrototype.updateIn; + ListPrototype.mergeIn = MapPrototype.mergeIn; + ListPrototype.mergeDeepIn = MapPrototype.mergeDeepIn; + ListPrototype.withMutations = MapPrototype.withMutations; + ListPrototype.asMutable = MapPrototype.asMutable; + ListPrototype.asImmutable = MapPrototype.asImmutable; + ListPrototype.wasAltered = MapPrototype.wasAltered; + + + + function VNode(array, ownerID) { + this.array = array; + this.ownerID = ownerID; + } + + // TODO: seems like these methods are very similar + + VNode.prototype.removeBefore = function(ownerID, level, index) { + if (index === level ? 1 << level : 0 || this.array.length === 0) { + return this; + } + var originIndex = (index >>> level) & MASK; + if (originIndex >= this.array.length) { + return new VNode([], ownerID); + } + var removingFirst = originIndex === 0; + var newChild; + if (level > 0) { + var oldChild = this.array[originIndex]; + newChild = oldChild && oldChild.removeBefore(ownerID, level - SHIFT, index); + if (newChild === oldChild && removingFirst) { + return this; + } + } + if (removingFirst && !newChild) { + return this; + } + var editable = editableVNode(this, ownerID); + if (!removingFirst) { + for (var ii = 0; ii < originIndex; ii++) { + editable.array[ii] = undefined; + } + } + if (newChild) { + editable.array[originIndex] = newChild; + } + return editable; + }; + + VNode.prototype.removeAfter = function(ownerID, level, index) { + if (index === (level ? 1 << level : 0) || this.array.length === 0) { + return this; + } + var sizeIndex = ((index - 1) >>> level) & MASK; + if (sizeIndex >= this.array.length) { + return this; + } + + var newChild; + if (level > 0) { + var oldChild = this.array[sizeIndex]; + newChild = oldChild && oldChild.removeAfter(ownerID, level - SHIFT, index); + if (newChild === oldChild && sizeIndex === this.array.length - 1) { + return this; + } + } + + var editable = editableVNode(this, ownerID); + editable.array.splice(sizeIndex + 1); + if (newChild) { + editable.array[sizeIndex] = newChild; + } + return editable; + }; + + + + var DONE = {}; + + function iterateList(list, reverse) { + var left = list._origin; + var right = list._capacity; + var tailPos = getTailOffset(right); + var tail = list._tail; + + return iterateNodeOrLeaf(list._root, list._level, 0); + + function iterateNodeOrLeaf(node, level, offset) { + return level === 0 ? + iterateLeaf(node, offset) : + iterateNode(node, level, offset); + } + + function iterateLeaf(node, offset) { + var array = offset === tailPos ? tail && tail.array : node && node.array; + var from = offset > left ? 0 : left - offset; + var to = right - offset; + if (to > SIZE) { + to = SIZE; + } + return function() { + if (from === to) { + return DONE; + } + var idx = reverse ? --to : from++; + return array && array[idx]; + }; + } + + function iterateNode(node, level, offset) { + var values; + var array = node && node.array; + var from = offset > left ? 0 : (left - offset) >> level; + var to = ((right - offset) >> level) + 1; + if (to > SIZE) { + to = SIZE; + } + return function() { + do { + if (values) { + var value = values(); + if (value !== DONE) { + return value; + } + values = null; + } + if (from === to) { + return DONE; + } + var idx = reverse ? --to : from++; + values = iterateNodeOrLeaf( + array && array[idx], level - SHIFT, offset + (idx << level) + ); + } while (true); + }; + } + } + + function makeList(origin, capacity, level, root, tail, ownerID, hash) { + var list = Object.create(ListPrototype); + list.size = capacity - origin; + list._origin = origin; + list._capacity = capacity; + list._level = level; + list._root = root; + list._tail = tail; + list.__ownerID = ownerID; + list.__hash = hash; + list.__altered = false; + return list; + } + + var EMPTY_LIST; + function emptyList() { + return EMPTY_LIST || (EMPTY_LIST = makeList(0, 0, SHIFT)); + } + + function updateList(list, index, value) { + index = wrapIndex(list, index); + + if (index !== index) { + return list; + } + + if (index >= list.size || index < 0) { + return list.withMutations(function(list ) { + index < 0 ? + setListBounds(list, index).set(0, value) : + setListBounds(list, 0, index + 1).set(index, value) + }); + } + + index += list._origin; + + var newTail = list._tail; + var newRoot = list._root; + var didAlter = MakeRef(DID_ALTER); + if (index >= getTailOffset(list._capacity)) { + newTail = updateVNode(newTail, list.__ownerID, 0, index, value, didAlter); + } else { + newRoot = updateVNode(newRoot, list.__ownerID, list._level, index, value, didAlter); + } + + if (!didAlter.value) { + return list; + } + + if (list.__ownerID) { + list._root = newRoot; + list._tail = newTail; + list.__hash = undefined; + list.__altered = true; + return list; + } + return makeList(list._origin, list._capacity, list._level, newRoot, newTail); + } + + function updateVNode(node, ownerID, level, index, value, didAlter) { + var idx = (index >>> level) & MASK; + var nodeHas = node && idx < node.array.length; + if (!nodeHas && value === undefined) { + return node; + } + + var newNode; + + if (level > 0) { + var lowerNode = node && node.array[idx]; + var newLowerNode = updateVNode(lowerNode, ownerID, level - SHIFT, index, value, didAlter); + if (newLowerNode === lowerNode) { + return node; + } + newNode = editableVNode(node, ownerID); + newNode.array[idx] = newLowerNode; + return newNode; + } + + if (nodeHas && node.array[idx] === value) { + return node; + } + + SetRef(didAlter); + + newNode = editableVNode(node, ownerID); + if (value === undefined && idx === newNode.array.length - 1) { + newNode.array.pop(); + } else { + newNode.array[idx] = value; + } + return newNode; + } + + function editableVNode(node, ownerID) { + if (ownerID && node && ownerID === node.ownerID) { + return node; + } + return new VNode(node ? node.array.slice() : [], ownerID); + } + + function listNodeFor(list, rawIndex) { + if (rawIndex >= getTailOffset(list._capacity)) { + return list._tail; + } + if (rawIndex < 1 << (list._level + SHIFT)) { + var node = list._root; + var level = list._level; + while (node && level > 0) { + node = node.array[(rawIndex >>> level) & MASK]; + level -= SHIFT; + } + return node; + } + } + + function setListBounds(list, begin, end) { + // Sanitize begin & end using this shorthand for ToInt32(argument) + // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32 + if (begin !== undefined) { + begin = begin | 0; + } + if (end !== undefined) { + end = end | 0; + } + var owner = list.__ownerID || new OwnerID(); + var oldOrigin = list._origin; + var oldCapacity = list._capacity; + var newOrigin = oldOrigin + begin; + var newCapacity = end === undefined ? oldCapacity : end < 0 ? oldCapacity + end : oldOrigin + end; + if (newOrigin === oldOrigin && newCapacity === oldCapacity) { + return list; + } + + // If it's going to end after it starts, it's empty. + if (newOrigin >= newCapacity) { + return list.clear(); + } + + var newLevel = list._level; + var newRoot = list._root; + + // New origin might need creating a higher root. + var offsetShift = 0; + while (newOrigin + offsetShift < 0) { + newRoot = new VNode(newRoot && newRoot.array.length ? [undefined, newRoot] : [], owner); + newLevel += SHIFT; + offsetShift += 1 << newLevel; + } + if (offsetShift) { + newOrigin += offsetShift; + oldOrigin += offsetShift; + newCapacity += offsetShift; + oldCapacity += offsetShift; + } + + var oldTailOffset = getTailOffset(oldCapacity); + var newTailOffset = getTailOffset(newCapacity); + + // New size might need creating a higher root. + while (newTailOffset >= 1 << (newLevel + SHIFT)) { + newRoot = new VNode(newRoot && newRoot.array.length ? [newRoot] : [], owner); + newLevel += SHIFT; + } + + // Locate or create the new tail. + var oldTail = list._tail; + var newTail = newTailOffset < oldTailOffset ? + listNodeFor(list, newCapacity - 1) : + newTailOffset > oldTailOffset ? new VNode([], owner) : oldTail; + + // Merge Tail into tree. + if (oldTail && newTailOffset > oldTailOffset && newOrigin < oldCapacity && oldTail.array.length) { + newRoot = editableVNode(newRoot, owner); + var node = newRoot; + for (var level = newLevel; level > SHIFT; level -= SHIFT) { + var idx = (oldTailOffset >>> level) & MASK; + node = node.array[idx] = editableVNode(node.array[idx], owner); + } + node.array[(oldTailOffset >>> SHIFT) & MASK] = oldTail; + } + + // If the size has been reduced, there's a chance the tail needs to be trimmed. + if (newCapacity < oldCapacity) { + newTail = newTail && newTail.removeAfter(owner, 0, newCapacity); + } + + // If the new origin is within the tail, then we do not need a root. + if (newOrigin >= newTailOffset) { + newOrigin -= newTailOffset; + newCapacity -= newTailOffset; + newLevel = SHIFT; + newRoot = null; + newTail = newTail && newTail.removeBefore(owner, 0, newOrigin); + + // Otherwise, if the root has been trimmed, garbage collect. + } else if (newOrigin > oldOrigin || newTailOffset < oldTailOffset) { + offsetShift = 0; + + // Identify the new top root node of the subtree of the old root. + while (newRoot) { + var beginIndex = (newOrigin >>> newLevel) & MASK; + if (beginIndex !== (newTailOffset >>> newLevel) & MASK) { + break; + } + if (beginIndex) { + offsetShift += (1 << newLevel) * beginIndex; + } + newLevel -= SHIFT; + newRoot = newRoot.array[beginIndex]; + } + + // Trim the new sides of the new root. + if (newRoot && newOrigin > oldOrigin) { + newRoot = newRoot.removeBefore(owner, newLevel, newOrigin - offsetShift); + } + if (newRoot && newTailOffset < oldTailOffset) { + newRoot = newRoot.removeAfter(owner, newLevel, newTailOffset - offsetShift); + } + if (offsetShift) { + newOrigin -= offsetShift; + newCapacity -= offsetShift; + } + } + + if (list.__ownerID) { + list.size = newCapacity - newOrigin; + list._origin = newOrigin; + list._capacity = newCapacity; + list._level = newLevel; + list._root = newRoot; + list._tail = newTail; + list.__hash = undefined; + list.__altered = true; + return list; + } + return makeList(newOrigin, newCapacity, newLevel, newRoot, newTail); + } + + function mergeIntoListWith(list, merger, iterables) { + var iters = []; + var maxSize = 0; + for (var ii = 0; ii < iterables.length; ii++) { + var value = iterables[ii]; + var iter = IndexedIterable(value); + if (iter.size > maxSize) { + maxSize = iter.size; + } + if (!isIterable(value)) { + iter = iter.map(function(v ) {return fromJS(v)}); + } + iters.push(iter); + } + if (maxSize > list.size) { + list = list.setSize(maxSize); + } + return mergeIntoCollectionWith(list, merger, iters); + } + + function getTailOffset(size) { + return size < SIZE ? 0 : (((size - 1) >>> SHIFT) << SHIFT); + } + + createClass(OrderedMap, Map); + + // @pragma Construction + + function OrderedMap(value) { + return value === null || value === undefined ? emptyOrderedMap() : + isOrderedMap(value) ? value : + emptyOrderedMap().withMutations(function(map ) { + var iter = KeyedIterable(value); + assertNotInfinite(iter.size); + iter.forEach(function(v, k) {return map.set(k, v)}); + }); + } + + OrderedMap.of = function(/*...values*/) { + return this(arguments); + }; + + OrderedMap.prototype.toString = function() { + return this.__toString('OrderedMap {', '}'); + }; + + // @pragma Access + + OrderedMap.prototype.get = function(k, notSetValue) { + var index = this._map.get(k); + return index !== undefined ? this._list.get(index)[1] : notSetValue; + }; + + // @pragma Modification + + OrderedMap.prototype.clear = function() { + if (this.size === 0) { + return this; + } + if (this.__ownerID) { + this.size = 0; + this._map.clear(); + this._list.clear(); + return this; + } + return emptyOrderedMap(); + }; + + OrderedMap.prototype.set = function(k, v) { + return updateOrderedMap(this, k, v); + }; + + OrderedMap.prototype.remove = function(k) { + return updateOrderedMap(this, k, NOT_SET); + }; + + OrderedMap.prototype.wasAltered = function() { + return this._map.wasAltered() || this._list.wasAltered(); + }; + + OrderedMap.prototype.__iterate = function(fn, reverse) {var this$0 = this; + return this._list.__iterate( + function(entry ) {return entry && fn(entry[1], entry[0], this$0)}, + reverse + ); + }; + + OrderedMap.prototype.__iterator = function(type, reverse) { + return this._list.fromEntrySeq().__iterator(type, reverse); + }; + + OrderedMap.prototype.__ensureOwner = function(ownerID) { + if (ownerID === this.__ownerID) { + return this; + } + var newMap = this._map.__ensureOwner(ownerID); + var newList = this._list.__ensureOwner(ownerID); + if (!ownerID) { + this.__ownerID = ownerID; + this._map = newMap; + this._list = newList; + return this; + } + return makeOrderedMap(newMap, newList, ownerID, this.__hash); + }; + + + function isOrderedMap(maybeOrderedMap) { + return isMap(maybeOrderedMap) && isOrdered(maybeOrderedMap); + } + + OrderedMap.isOrderedMap = isOrderedMap; + + OrderedMap.prototype[IS_ORDERED_SENTINEL] = true; + OrderedMap.prototype[DELETE] = OrderedMap.prototype.remove; + + + + function makeOrderedMap(map, list, ownerID, hash) { + var omap = Object.create(OrderedMap.prototype); + omap.size = map ? map.size : 0; + omap._map = map; + omap._list = list; + omap.__ownerID = ownerID; + omap.__hash = hash; + return omap; + } + + var EMPTY_ORDERED_MAP; + function emptyOrderedMap() { + return EMPTY_ORDERED_MAP || (EMPTY_ORDERED_MAP = makeOrderedMap(emptyMap(), emptyList())); + } + + function updateOrderedMap(omap, k, v) { + var map = omap._map; + var list = omap._list; + var i = map.get(k); + var has = i !== undefined; + var newMap; + var newList; + if (v === NOT_SET) { // removed + if (!has) { + return omap; + } + if (list.size >= SIZE && list.size >= map.size * 2) { + newList = list.filter(function(entry, idx) {return entry !== undefined && i !== idx}); + newMap = newList.toKeyedSeq().map(function(entry ) {return entry[0]}).flip().toMap(); + if (omap.__ownerID) { + newMap.__ownerID = newList.__ownerID = omap.__ownerID; + } + } else { + newMap = map.remove(k); + newList = i === list.size - 1 ? list.pop() : list.set(i, undefined); + } + } else { + if (has) { + if (v === list.get(i)[1]) { + return omap; + } + newMap = map; + newList = list.set(i, [k, v]); + } else { + newMap = map.set(k, list.size); + newList = list.set(list.size, [k, v]); + } + } + if (omap.__ownerID) { + omap.size = newMap.size; + omap._map = newMap; + omap._list = newList; + omap.__hash = undefined; + return omap; + } + return makeOrderedMap(newMap, newList); + } + + createClass(ToKeyedSequence, KeyedSeq); + function ToKeyedSequence(indexed, useKeys) { + this._iter = indexed; + this._useKeys = useKeys; + this.size = indexed.size; + } + + ToKeyedSequence.prototype.get = function(key, notSetValue) { + return this._iter.get(key, notSetValue); + }; + + ToKeyedSequence.prototype.has = function(key) { + return this._iter.has(key); + }; + + ToKeyedSequence.prototype.valueSeq = function() { + return this._iter.valueSeq(); + }; + + ToKeyedSequence.prototype.reverse = function() {var this$0 = this; + var reversedSequence = reverseFactory(this, true); + if (!this._useKeys) { + reversedSequence.valueSeq = function() {return this$0._iter.toSeq().reverse()}; + } + return reversedSequence; + }; + + ToKeyedSequence.prototype.map = function(mapper, context) {var this$0 = this; + var mappedSequence = mapFactory(this, mapper, context); + if (!this._useKeys) { + mappedSequence.valueSeq = function() {return this$0._iter.toSeq().map(mapper, context)}; + } + return mappedSequence; + }; + + ToKeyedSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this; + var ii; + return this._iter.__iterate( + this._useKeys ? + function(v, k) {return fn(v, k, this$0)} : + ((ii = reverse ? resolveSize(this) : 0), + function(v ) {return fn(v, reverse ? --ii : ii++, this$0)}), + reverse + ); + }; + + ToKeyedSequence.prototype.__iterator = function(type, reverse) { + if (this._useKeys) { + return this._iter.__iterator(type, reverse); + } + var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); + var ii = reverse ? resolveSize(this) : 0; + return new Iterator(function() { + var step = iterator.next(); + return step.done ? step : + iteratorValue(type, reverse ? --ii : ii++, step.value, step); + }); + }; + + ToKeyedSequence.prototype[IS_ORDERED_SENTINEL] = true; + + + createClass(ToIndexedSequence, IndexedSeq); + function ToIndexedSequence(iter) { + this._iter = iter; + this.size = iter.size; + } + + ToIndexedSequence.prototype.includes = function(value) { + return this._iter.includes(value); + }; + + ToIndexedSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this; + var iterations = 0; + return this._iter.__iterate(function(v ) {return fn(v, iterations++, this$0)}, reverse); + }; + + ToIndexedSequence.prototype.__iterator = function(type, reverse) { + var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); + var iterations = 0; + return new Iterator(function() { + var step = iterator.next(); + return step.done ? step : + iteratorValue(type, iterations++, step.value, step) + }); + }; + + + + createClass(ToSetSequence, SetSeq); + function ToSetSequence(iter) { + this._iter = iter; + this.size = iter.size; + } + + ToSetSequence.prototype.has = function(key) { + return this._iter.includes(key); + }; + + ToSetSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this; + return this._iter.__iterate(function(v ) {return fn(v, v, this$0)}, reverse); + }; + + ToSetSequence.prototype.__iterator = function(type, reverse) { + var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); + return new Iterator(function() { + var step = iterator.next(); + return step.done ? step : + iteratorValue(type, step.value, step.value, step); + }); + }; + + + + createClass(FromEntriesSequence, KeyedSeq); + function FromEntriesSequence(entries) { + this._iter = entries; + this.size = entries.size; + } + + FromEntriesSequence.prototype.entrySeq = function() { + return this._iter.toSeq(); + }; + + FromEntriesSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this; + return this._iter.__iterate(function(entry ) { + // Check if entry exists first so array access doesn't throw for holes + // in the parent iteration. + if (entry) { + validateEntry(entry); + var indexedIterable = isIterable(entry); + return fn( + indexedIterable ? entry.get(1) : entry[1], + indexedIterable ? entry.get(0) : entry[0], + this$0 + ); + } + }, reverse); + }; + + FromEntriesSequence.prototype.__iterator = function(type, reverse) { + var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); + return new Iterator(function() { + while (true) { + var step = iterator.next(); + if (step.done) { + return step; + } + var entry = step.value; + // Check if entry exists first so array access doesn't throw for holes + // in the parent iteration. + if (entry) { + validateEntry(entry); + var indexedIterable = isIterable(entry); + return iteratorValue( + type, + indexedIterable ? entry.get(0) : entry[0], + indexedIterable ? entry.get(1) : entry[1], + step + ); + } + } + }); + }; + + + ToIndexedSequence.prototype.cacheResult = + ToKeyedSequence.prototype.cacheResult = + ToSetSequence.prototype.cacheResult = + FromEntriesSequence.prototype.cacheResult = + cacheResultThrough; + + + function flipFactory(iterable) { + var flipSequence = makeSequence(iterable); + flipSequence._iter = iterable; + flipSequence.size = iterable.size; + flipSequence.flip = function() {return iterable}; + flipSequence.reverse = function () { + var reversedSequence = iterable.reverse.apply(this); // super.reverse() + reversedSequence.flip = function() {return iterable.reverse()}; + return reversedSequence; + }; + flipSequence.has = function(key ) {return iterable.includes(key)}; + flipSequence.includes = function(key ) {return iterable.has(key)}; + flipSequence.cacheResult = cacheResultThrough; + flipSequence.__iterateUncached = function (fn, reverse) {var this$0 = this; + return iterable.__iterate(function(v, k) {return fn(k, v, this$0) !== false}, reverse); + } + flipSequence.__iteratorUncached = function(type, reverse) { + if (type === ITERATE_ENTRIES) { + var iterator = iterable.__iterator(type, reverse); + return new Iterator(function() { + var step = iterator.next(); + if (!step.done) { + var k = step.value[0]; + step.value[0] = step.value[1]; + step.value[1] = k; + } + return step; + }); + } + return iterable.__iterator( + type === ITERATE_VALUES ? ITERATE_KEYS : ITERATE_VALUES, + reverse + ); + } + return flipSequence; + } + + + function mapFactory(iterable, mapper, context) { + var mappedSequence = makeSequence(iterable); + mappedSequence.size = iterable.size; + mappedSequence.has = function(key ) {return iterable.has(key)}; + mappedSequence.get = function(key, notSetValue) { + var v = iterable.get(key, NOT_SET); + return v === NOT_SET ? + notSetValue : + mapper.call(context, v, key, iterable); + }; + mappedSequence.__iterateUncached = function (fn, reverse) {var this$0 = this; + return iterable.__iterate( + function(v, k, c) {return fn(mapper.call(context, v, k, c), k, this$0) !== false}, + reverse + ); + } + mappedSequence.__iteratorUncached = function (type, reverse) { + var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse); + return new Iterator(function() { + var step = iterator.next(); + if (step.done) { + return step; + } + var entry = step.value; + var key = entry[0]; + return iteratorValue( + type, + key, + mapper.call(context, entry[1], key, iterable), + step + ); + }); + } + return mappedSequence; + } + + + function reverseFactory(iterable, useKeys) { + var reversedSequence = makeSequence(iterable); + reversedSequence._iter = iterable; + reversedSequence.size = iterable.size; + reversedSequence.reverse = function() {return iterable}; + if (iterable.flip) { + reversedSequence.flip = function () { + var flipSequence = flipFactory(iterable); + flipSequence.reverse = function() {return iterable.flip()}; + return flipSequence; + }; + } + reversedSequence.get = function(key, notSetValue) + {return iterable.get(useKeys ? key : -1 - key, notSetValue)}; + reversedSequence.has = function(key ) + {return iterable.has(useKeys ? key : -1 - key)}; + reversedSequence.includes = function(value ) {return iterable.includes(value)}; + reversedSequence.cacheResult = cacheResultThrough; + reversedSequence.__iterate = function (fn, reverse) {var this$0 = this; + return iterable.__iterate(function(v, k) {return fn(v, k, this$0)}, !reverse); + }; + reversedSequence.__iterator = + function(type, reverse) {return iterable.__iterator(type, !reverse)}; + return reversedSequence; + } + + + function filterFactory(iterable, predicate, context, useKeys) { + var filterSequence = makeSequence(iterable); + if (useKeys) { + filterSequence.has = function(key ) { + var v = iterable.get(key, NOT_SET); + return v !== NOT_SET && !!predicate.call(context, v, key, iterable); + }; + filterSequence.get = function(key, notSetValue) { + var v = iterable.get(key, NOT_SET); + return v !== NOT_SET && predicate.call(context, v, key, iterable) ? + v : notSetValue; + }; + } + filterSequence.__iterateUncached = function (fn, reverse) {var this$0 = this; + var iterations = 0; + iterable.__iterate(function(v, k, c) { + if (predicate.call(context, v, k, c)) { + iterations++; + return fn(v, useKeys ? k : iterations - 1, this$0); + } + }, reverse); + return iterations; + }; + filterSequence.__iteratorUncached = function (type, reverse) { + var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse); + var iterations = 0; + return new Iterator(function() { + while (true) { + var step = iterator.next(); + if (step.done) { + return step; + } + var entry = step.value; + var key = entry[0]; + var value = entry[1]; + if (predicate.call(context, value, key, iterable)) { + return iteratorValue(type, useKeys ? key : iterations++, value, step); + } + } + }); + } + return filterSequence; + } + + + function countByFactory(iterable, grouper, context) { + var groups = Map().asMutable(); + iterable.__iterate(function(v, k) { + groups.update( + grouper.call(context, v, k, iterable), + 0, + function(a ) {return a + 1} + ); + }); + return groups.asImmutable(); + } + + + function groupByFactory(iterable, grouper, context) { + var isKeyedIter = isKeyed(iterable); + var groups = (isOrdered(iterable) ? OrderedMap() : Map()).asMutable(); + iterable.__iterate(function(v, k) { + groups.update( + grouper.call(context, v, k, iterable), + function(a ) {return (a = a || [], a.push(isKeyedIter ? [k, v] : v), a)} + ); + }); + var coerce = iterableClass(iterable); + return groups.map(function(arr ) {return reify(iterable, coerce(arr))}); + } + + + function sliceFactory(iterable, begin, end, useKeys) { + var originalSize = iterable.size; + + // Sanitize begin & end using this shorthand for ToInt32(argument) + // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32 + if (begin !== undefined) { + begin = begin | 0; + } + if (end !== undefined) { + end = end | 0; + } + + if (wholeSlice(begin, end, originalSize)) { + return iterable; + } + + var resolvedBegin = resolveBegin(begin, originalSize); + var resolvedEnd = resolveEnd(end, originalSize); + + // begin or end will be NaN if they were provided as negative numbers and + // this iterable's size is unknown. In that case, cache first so there is + // a known size and these do not resolve to NaN. + if (resolvedBegin !== resolvedBegin || resolvedEnd !== resolvedEnd) { + return sliceFactory(iterable.toSeq().cacheResult(), begin, end, useKeys); + } + + // Note: resolvedEnd is undefined when the original sequence's length is + // unknown and this slice did not supply an end and should contain all + // elements after resolvedBegin. + // In that case, resolvedSize will be NaN and sliceSize will remain undefined. + var resolvedSize = resolvedEnd - resolvedBegin; + var sliceSize; + if (resolvedSize === resolvedSize) { + sliceSize = resolvedSize < 0 ? 0 : resolvedSize; + } + + var sliceSeq = makeSequence(iterable); + + // If iterable.size is undefined, the size of the realized sliceSeq is + // unknown at this point unless the number of items to slice is 0 + sliceSeq.size = sliceSize === 0 ? sliceSize : iterable.size && sliceSize || undefined; + + if (!useKeys && isSeq(iterable) && sliceSize >= 0) { + sliceSeq.get = function (index, notSetValue) { + index = wrapIndex(this, index); + return index >= 0 && index < sliceSize ? + iterable.get(index + resolvedBegin, notSetValue) : + notSetValue; + } + } + + sliceSeq.__iterateUncached = function(fn, reverse) {var this$0 = this; + if (sliceSize === 0) { + return 0; + } + if (reverse) { + return this.cacheResult().__iterate(fn, reverse); + } + var skipped = 0; + var isSkipping = true; + var iterations = 0; + iterable.__iterate(function(v, k) { + if (!(isSkipping && (isSkipping = skipped++ < resolvedBegin))) { + iterations++; + return fn(v, useKeys ? k : iterations - 1, this$0) !== false && + iterations !== sliceSize; + } + }); + return iterations; + }; + + sliceSeq.__iteratorUncached = function(type, reverse) { + if (sliceSize !== 0 && reverse) { + return this.cacheResult().__iterator(type, reverse); + } + // Don't bother instantiating parent iterator if taking 0. + var iterator = sliceSize !== 0 && iterable.__iterator(type, reverse); + var skipped = 0; + var iterations = 0; + return new Iterator(function() { + while (skipped++ < resolvedBegin) { + iterator.next(); + } + if (++iterations > sliceSize) { + return iteratorDone(); + } + var step = iterator.next(); + if (useKeys || type === ITERATE_VALUES) { + return step; + } else if (type === ITERATE_KEYS) { + return iteratorValue(type, iterations - 1, undefined, step); + } else { + return iteratorValue(type, iterations - 1, step.value[1], step); + } + }); + } + + return sliceSeq; + } + + + function takeWhileFactory(iterable, predicate, context) { + var takeSequence = makeSequence(iterable); + takeSequence.__iterateUncached = function(fn, reverse) {var this$0 = this; + if (reverse) { + return this.cacheResult().__iterate(fn, reverse); + } + var iterations = 0; + iterable.__iterate(function(v, k, c) + {return predicate.call(context, v, k, c) && ++iterations && fn(v, k, this$0)} + ); + return iterations; + }; + takeSequence.__iteratorUncached = function(type, reverse) {var this$0 = this; + if (reverse) { + return this.cacheResult().__iterator(type, reverse); + } + var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse); + var iterating = true; + return new Iterator(function() { + if (!iterating) { + return iteratorDone(); + } + var step = iterator.next(); + if (step.done) { + return step; + } + var entry = step.value; + var k = entry[0]; + var v = entry[1]; + if (!predicate.call(context, v, k, this$0)) { + iterating = false; + return iteratorDone(); + } + return type === ITERATE_ENTRIES ? step : + iteratorValue(type, k, v, step); + }); + }; + return takeSequence; + } + + + function skipWhileFactory(iterable, predicate, context, useKeys) { + var skipSequence = makeSequence(iterable); + skipSequence.__iterateUncached = function (fn, reverse) {var this$0 = this; + if (reverse) { + return this.cacheResult().__iterate(fn, reverse); + } + var isSkipping = true; + var iterations = 0; + iterable.__iterate(function(v, k, c) { + if (!(isSkipping && (isSkipping = predicate.call(context, v, k, c)))) { + iterations++; + return fn(v, useKeys ? k : iterations - 1, this$0); + } + }); + return iterations; + }; + skipSequence.__iteratorUncached = function(type, reverse) {var this$0 = this; + if (reverse) { + return this.cacheResult().__iterator(type, reverse); + } + var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse); + var skipping = true; + var iterations = 0; + return new Iterator(function() { + var step, k, v; + do { + step = iterator.next(); + if (step.done) { + if (useKeys || type === ITERATE_VALUES) { + return step; + } else if (type === ITERATE_KEYS) { + return iteratorValue(type, iterations++, undefined, step); + } else { + return iteratorValue(type, iterations++, step.value[1], step); + } + } + var entry = step.value; + k = entry[0]; + v = entry[1]; + skipping && (skipping = predicate.call(context, v, k, this$0)); + } while (skipping); + return type === ITERATE_ENTRIES ? step : + iteratorValue(type, k, v, step); + }); + }; + return skipSequence; + } + + + function concatFactory(iterable, values) { + var isKeyedIterable = isKeyed(iterable); + var iters = [iterable].concat(values).map(function(v ) { + if (!isIterable(v)) { + v = isKeyedIterable ? + keyedSeqFromValue(v) : + indexedSeqFromValue(Array.isArray(v) ? v : [v]); + } else if (isKeyedIterable) { + v = KeyedIterable(v); + } + return v; + }).filter(function(v ) {return v.size !== 0}); + + if (iters.length === 0) { + return iterable; + } + + if (iters.length === 1) { + var singleton = iters[0]; + if (singleton === iterable || + isKeyedIterable && isKeyed(singleton) || + isIndexed(iterable) && isIndexed(singleton)) { + return singleton; + } + } + + var concatSeq = new ArraySeq(iters); + if (isKeyedIterable) { + concatSeq = concatSeq.toKeyedSeq(); + } else if (!isIndexed(iterable)) { + concatSeq = concatSeq.toSetSeq(); + } + concatSeq = concatSeq.flatten(true); + concatSeq.size = iters.reduce( + function(sum, seq) { + if (sum !== undefined) { + var size = seq.size; + if (size !== undefined) { + return sum + size; + } + } + }, + 0 + ); + return concatSeq; + } + + + function flattenFactory(iterable, depth, useKeys) { + var flatSequence = makeSequence(iterable); + flatSequence.__iterateUncached = function(fn, reverse) { + var iterations = 0; + var stopped = false; + function flatDeep(iter, currentDepth) {var this$0 = this; + iter.__iterate(function(v, k) { + if ((!depth || currentDepth < depth) && isIterable(v)) { + flatDeep(v, currentDepth + 1); + } else if (fn(v, useKeys ? k : iterations++, this$0) === false) { + stopped = true; + } + return !stopped; + }, reverse); + } + flatDeep(iterable, 0); + return iterations; + } + flatSequence.__iteratorUncached = function(type, reverse) { + var iterator = iterable.__iterator(type, reverse); + var stack = []; + var iterations = 0; + return new Iterator(function() { + while (iterator) { + var step = iterator.next(); + if (step.done !== false) { + iterator = stack.pop(); + continue; + } + var v = step.value; + if (type === ITERATE_ENTRIES) { + v = v[1]; + } + if ((!depth || stack.length < depth) && isIterable(v)) { + stack.push(iterator); + iterator = v.__iterator(type, reverse); + } else { + return useKeys ? step : iteratorValue(type, iterations++, v, step); + } + } + return iteratorDone(); + }); + } + return flatSequence; + } + + + function flatMapFactory(iterable, mapper, context) { + var coerce = iterableClass(iterable); + return iterable.toSeq().map( + function(v, k) {return coerce(mapper.call(context, v, k, iterable))} + ).flatten(true); + } + + + function interposeFactory(iterable, separator) { + var interposedSequence = makeSequence(iterable); + interposedSequence.size = iterable.size && iterable.size * 2 -1; + interposedSequence.__iterateUncached = function(fn, reverse) {var this$0 = this; + var iterations = 0; + iterable.__iterate(function(v, k) + {return (!iterations || fn(separator, iterations++, this$0) !== false) && + fn(v, iterations++, this$0) !== false}, + reverse + ); + return iterations; + }; + interposedSequence.__iteratorUncached = function(type, reverse) { + var iterator = iterable.__iterator(ITERATE_VALUES, reverse); + var iterations = 0; + var step; + return new Iterator(function() { + if (!step || iterations % 2) { + step = iterator.next(); + if (step.done) { + return step; + } + } + return iterations % 2 ? + iteratorValue(type, iterations++, separator) : + iteratorValue(type, iterations++, step.value, step); + }); + }; + return interposedSequence; + } + + + function sortFactory(iterable, comparator, mapper) { + if (!comparator) { + comparator = defaultComparator; + } + var isKeyedIterable = isKeyed(iterable); + var index = 0; + var entries = iterable.toSeq().map( + function(v, k) {return [k, v, index++, mapper ? mapper(v, k, iterable) : v]} + ).toArray(); + entries.sort(function(a, b) {return comparator(a[3], b[3]) || a[2] - b[2]}).forEach( + isKeyedIterable ? + function(v, i) { entries[i].length = 2; } : + function(v, i) { entries[i] = v[1]; } + ); + return isKeyedIterable ? KeyedSeq(entries) : + isIndexed(iterable) ? IndexedSeq(entries) : + SetSeq(entries); + } + + + function maxFactory(iterable, comparator, mapper) { + if (!comparator) { + comparator = defaultComparator; + } + if (mapper) { + var entry = iterable.toSeq() + .map(function(v, k) {return [v, mapper(v, k, iterable)]}) + .reduce(function(a, b) {return maxCompare(comparator, a[1], b[1]) ? b : a}); + return entry && entry[0]; + } else { + return iterable.reduce(function(a, b) {return maxCompare(comparator, a, b) ? b : a}); + } + } + + function maxCompare(comparator, a, b) { + var comp = comparator(b, a); + // b is considered the new max if the comparator declares them equal, but + // they are not equal and b is in fact a nullish value. + return (comp === 0 && b !== a && (b === undefined || b === null || b !== b)) || comp > 0; + } + + + function zipWithFactory(keyIter, zipper, iters) { + var zipSequence = makeSequence(keyIter); + zipSequence.size = new ArraySeq(iters).map(function(i ) {return i.size}).min(); + // Note: this a generic base implementation of __iterate in terms of + // __iterator which may be more generically useful in the future. + zipSequence.__iterate = function(fn, reverse) { + /* generic: + var iterator = this.__iterator(ITERATE_ENTRIES, reverse); + var step; + var iterations = 0; + while (!(step = iterator.next()).done) { + iterations++; + if (fn(step.value[1], step.value[0], this) === false) { + break; + } + } + return iterations; + */ + // indexed: + var iterator = this.__iterator(ITERATE_VALUES, reverse); + var step; + var iterations = 0; + while (!(step = iterator.next()).done) { + if (fn(step.value, iterations++, this) === false) { + break; + } + } + return iterations; + }; + zipSequence.__iteratorUncached = function(type, reverse) { + var iterators = iters.map(function(i ) + {return (i = Iterable(i), getIterator(reverse ? i.reverse() : i))} + ); + var iterations = 0; + var isDone = false; + return new Iterator(function() { + var steps; + if (!isDone) { + steps = iterators.map(function(i ) {return i.next()}); + isDone = steps.some(function(s ) {return s.done}); + } + if (isDone) { + return iteratorDone(); + } + return iteratorValue( + type, + iterations++, + zipper.apply(null, steps.map(function(s ) {return s.value})) + ); + }); + }; + return zipSequence + } + + + // #pragma Helper Functions + + function reify(iter, seq) { + return isSeq(iter) ? seq : iter.constructor(seq); + } + + function validateEntry(entry) { + if (entry !== Object(entry)) { + throw new TypeError('Expected [K, V] tuple: ' + entry); + } + } + + function resolveSize(iter) { + assertNotInfinite(iter.size); + return ensureSize(iter); + } + + function iterableClass(iterable) { + return isKeyed(iterable) ? KeyedIterable : + isIndexed(iterable) ? IndexedIterable : + SetIterable; + } + + function makeSequence(iterable) { + return Object.create( + ( + isKeyed(iterable) ? KeyedSeq : + isIndexed(iterable) ? IndexedSeq : + SetSeq + ).prototype + ); + } + + function cacheResultThrough() { + if (this._iter.cacheResult) { + this._iter.cacheResult(); + this.size = this._iter.size; + return this; + } else { + return Seq.prototype.cacheResult.call(this); + } + } + + function defaultComparator(a, b) { + return a > b ? 1 : a < b ? -1 : 0; + } + + function forceIterator(keyPath) { + var iter = getIterator(keyPath); + if (!iter) { + // Array might not be iterable in this environment, so we need a fallback + // to our wrapped type. + if (!isArrayLike(keyPath)) { + throw new TypeError('Expected iterable or array-like: ' + keyPath); + } + iter = getIterator(Iterable(keyPath)); + } + return iter; + } + + createClass(Record, KeyedCollection); + + function Record(defaultValues, name) { + var hasInitialized; + + var RecordType = function Record(values) { + if (values instanceof RecordType) { + return values; + } + if (!(this instanceof RecordType)) { + return new RecordType(values); + } + if (!hasInitialized) { + hasInitialized = true; + var keys = Object.keys(defaultValues); + setProps(RecordTypePrototype, keys); + RecordTypePrototype.size = keys.length; + RecordTypePrototype._name = name; + RecordTypePrototype._keys = keys; + RecordTypePrototype._defaultValues = defaultValues; + } + this._map = Map(values); + }; + + var RecordTypePrototype = RecordType.prototype = Object.create(RecordPrototype); + RecordTypePrototype.constructor = RecordType; + + return RecordType; + } + + Record.prototype.toString = function() { + return this.__toString(recordName(this) + ' {', '}'); + }; + + // @pragma Access + + Record.prototype.has = function(k) { + return this._defaultValues.hasOwnProperty(k); + }; + + Record.prototype.get = function(k, notSetValue) { + if (!this.has(k)) { + return notSetValue; + } + var defaultVal = this._defaultValues[k]; + return this._map ? this._map.get(k, defaultVal) : defaultVal; + }; + + // @pragma Modification + + Record.prototype.clear = function() { + if (this.__ownerID) { + this._map && this._map.clear(); + return this; + } + var RecordType = this.constructor; + return RecordType._empty || (RecordType._empty = makeRecord(this, emptyMap())); + }; + + Record.prototype.set = function(k, v) { + if (!this.has(k)) { + throw new Error('Cannot set unknown key "' + k + '" on ' + recordName(this)); + } + if (this._map && !this._map.has(k)) { + var defaultVal = this._defaultValues[k]; + if (v === defaultVal) { + return this; + } + } + var newMap = this._map && this._map.set(k, v); + if (this.__ownerID || newMap === this._map) { + return this; + } + return makeRecord(this, newMap); + }; + + Record.prototype.remove = function(k) { + if (!this.has(k)) { + return this; + } + var newMap = this._map && this._map.remove(k); + if (this.__ownerID || newMap === this._map) { + return this; + } + return makeRecord(this, newMap); + }; + + Record.prototype.wasAltered = function() { + return this._map.wasAltered(); + }; + + Record.prototype.__iterator = function(type, reverse) {var this$0 = this; + return KeyedIterable(this._defaultValues).map(function(_, k) {return this$0.get(k)}).__iterator(type, reverse); + }; + + Record.prototype.__iterate = function(fn, reverse) {var this$0 = this; + return KeyedIterable(this._defaultValues).map(function(_, k) {return this$0.get(k)}).__iterate(fn, reverse); + }; + + Record.prototype.__ensureOwner = function(ownerID) { + if (ownerID === this.__ownerID) { + return this; + } + var newMap = this._map && this._map.__ensureOwner(ownerID); + if (!ownerID) { + this.__ownerID = ownerID; + this._map = newMap; + return this; + } + return makeRecord(this, newMap, ownerID); + }; + + + var RecordPrototype = Record.prototype; + RecordPrototype[DELETE] = RecordPrototype.remove; + RecordPrototype.deleteIn = + RecordPrototype.removeIn = MapPrototype.removeIn; + RecordPrototype.merge = MapPrototype.merge; + RecordPrototype.mergeWith = MapPrototype.mergeWith; + RecordPrototype.mergeIn = MapPrototype.mergeIn; + RecordPrototype.mergeDeep = MapPrototype.mergeDeep; + RecordPrototype.mergeDeepWith = MapPrototype.mergeDeepWith; + RecordPrototype.mergeDeepIn = MapPrototype.mergeDeepIn; + RecordPrototype.setIn = MapPrototype.setIn; + RecordPrototype.update = MapPrototype.update; + RecordPrototype.updateIn = MapPrototype.updateIn; + RecordPrototype.withMutations = MapPrototype.withMutations; + RecordPrototype.asMutable = MapPrototype.asMutable; + RecordPrototype.asImmutable = MapPrototype.asImmutable; + + + function makeRecord(likeRecord, map, ownerID) { + var record = Object.create(Object.getPrototypeOf(likeRecord)); + record._map = map; + record.__ownerID = ownerID; + return record; + } + + function recordName(record) { + return record._name || record.constructor.name || 'Record'; + } + + function setProps(prototype, names) { + try { + names.forEach(setProp.bind(undefined, prototype)); + } catch (error) { + // Object.defineProperty failed. Probably IE8. + } + } + + function setProp(prototype, name) { + Object.defineProperty(prototype, name, { + get: function() { + return this.get(name); + }, + set: function(value) { + invariant(this.__ownerID, 'Cannot set on an immutable record.'); + this.set(name, value); + } + }); + } + + createClass(Set, SetCollection); + + // @pragma Construction + + function Set(value) { + return value === null || value === undefined ? emptySet() : + isSet(value) && !isOrdered(value) ? value : + emptySet().withMutations(function(set ) { + var iter = SetIterable(value); + assertNotInfinite(iter.size); + iter.forEach(function(v ) {return set.add(v)}); + }); + } + + Set.of = function(/*...values*/) { + return this(arguments); + }; + + Set.fromKeys = function(value) { + return this(KeyedIterable(value).keySeq()); + }; + + Set.prototype.toString = function() { + return this.__toString('Set {', '}'); + }; + + // @pragma Access + + Set.prototype.has = function(value) { + return this._map.has(value); + }; + + // @pragma Modification + + Set.prototype.add = function(value) { + return updateSet(this, this._map.set(value, true)); + }; + + Set.prototype.remove = function(value) { + return updateSet(this, this._map.remove(value)); + }; + + Set.prototype.clear = function() { + return updateSet(this, this._map.clear()); + }; + + // @pragma Composition + + Set.prototype.union = function() {var iters = SLICE$0.call(arguments, 0); + iters = iters.filter(function(x ) {return x.size !== 0}); + if (iters.length === 0) { + return this; + } + if (this.size === 0 && !this.__ownerID && iters.length === 1) { + return this.constructor(iters[0]); + } + return this.withMutations(function(set ) { + for (var ii = 0; ii < iters.length; ii++) { + SetIterable(iters[ii]).forEach(function(value ) {return set.add(value)}); + } + }); + }; + + Set.prototype.intersect = function() {var iters = SLICE$0.call(arguments, 0); + if (iters.length === 0) { + return this; + } + iters = iters.map(function(iter ) {return SetIterable(iter)}); + var originalSet = this; + return this.withMutations(function(set ) { + originalSet.forEach(function(value ) { + if (!iters.every(function(iter ) {return iter.includes(value)})) { + set.remove(value); + } + }); + }); + }; + + Set.prototype.subtract = function() {var iters = SLICE$0.call(arguments, 0); + if (iters.length === 0) { + return this; + } + iters = iters.map(function(iter ) {return SetIterable(iter)}); + var originalSet = this; + return this.withMutations(function(set ) { + originalSet.forEach(function(value ) { + if (iters.some(function(iter ) {return iter.includes(value)})) { + set.remove(value); + } + }); + }); + }; + + Set.prototype.merge = function() { + return this.union.apply(this, arguments); + }; + + Set.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1); + return this.union.apply(this, iters); + }; + + Set.prototype.sort = function(comparator) { + // Late binding + return OrderedSet(sortFactory(this, comparator)); + }; + + Set.prototype.sortBy = function(mapper, comparator) { + // Late binding + return OrderedSet(sortFactory(this, comparator, mapper)); + }; + + Set.prototype.wasAltered = function() { + return this._map.wasAltered(); + }; + + Set.prototype.__iterate = function(fn, reverse) {var this$0 = this; + return this._map.__iterate(function(_, k) {return fn(k, k, this$0)}, reverse); + }; + + Set.prototype.__iterator = function(type, reverse) { + return this._map.map(function(_, k) {return k}).__iterator(type, reverse); + }; + + Set.prototype.__ensureOwner = function(ownerID) { + if (ownerID === this.__ownerID) { + return this; + } + var newMap = this._map.__ensureOwner(ownerID); + if (!ownerID) { + this.__ownerID = ownerID; + this._map = newMap; + return this; + } + return this.__make(newMap, ownerID); + }; + + + function isSet(maybeSet) { + return !!(maybeSet && maybeSet[IS_SET_SENTINEL]); + } + + Set.isSet = isSet; + + var IS_SET_SENTINEL = '@@__IMMUTABLE_SET__@@'; + + var SetPrototype = Set.prototype; + SetPrototype[IS_SET_SENTINEL] = true; + SetPrototype[DELETE] = SetPrototype.remove; + SetPrototype.mergeDeep = SetPrototype.merge; + SetPrototype.mergeDeepWith = SetPrototype.mergeWith; + SetPrototype.withMutations = MapPrototype.withMutations; + SetPrototype.asMutable = MapPrototype.asMutable; + SetPrototype.asImmutable = MapPrototype.asImmutable; + + SetPrototype.__empty = emptySet; + SetPrototype.__make = makeSet; + + function updateSet(set, newMap) { + if (set.__ownerID) { + set.size = newMap.size; + set._map = newMap; + return set; + } + return newMap === set._map ? set : + newMap.size === 0 ? set.__empty() : + set.__make(newMap); + } + + function makeSet(map, ownerID) { + var set = Object.create(SetPrototype); + set.size = map ? map.size : 0; + set._map = map; + set.__ownerID = ownerID; + return set; + } + + var EMPTY_SET; + function emptySet() { + return EMPTY_SET || (EMPTY_SET = makeSet(emptyMap())); + } + + createClass(OrderedSet, Set); + + // @pragma Construction + + function OrderedSet(value) { + return value === null || value === undefined ? emptyOrderedSet() : + isOrderedSet(value) ? value : + emptyOrderedSet().withMutations(function(set ) { + var iter = SetIterable(value); + assertNotInfinite(iter.size); + iter.forEach(function(v ) {return set.add(v)}); + }); + } + + OrderedSet.of = function(/*...values*/) { + return this(arguments); + }; + + OrderedSet.fromKeys = function(value) { + return this(KeyedIterable(value).keySeq()); + }; + + OrderedSet.prototype.toString = function() { + return this.__toString('OrderedSet {', '}'); + }; + + + function isOrderedSet(maybeOrderedSet) { + return isSet(maybeOrderedSet) && isOrdered(maybeOrderedSet); + } + + OrderedSet.isOrderedSet = isOrderedSet; + + var OrderedSetPrototype = OrderedSet.prototype; + OrderedSetPrototype[IS_ORDERED_SENTINEL] = true; + + OrderedSetPrototype.__empty = emptyOrderedSet; + OrderedSetPrototype.__make = makeOrderedSet; + + function makeOrderedSet(map, ownerID) { + var set = Object.create(OrderedSetPrototype); + set.size = map ? map.size : 0; + set._map = map; + set.__ownerID = ownerID; + return set; + } + + var EMPTY_ORDERED_SET; + function emptyOrderedSet() { + return EMPTY_ORDERED_SET || (EMPTY_ORDERED_SET = makeOrderedSet(emptyOrderedMap())); + } + + createClass(Stack, IndexedCollection); + + // @pragma Construction + + function Stack(value) { + return value === null || value === undefined ? emptyStack() : + isStack(value) ? value : + emptyStack().unshiftAll(value); + } + + Stack.of = function(/*...values*/) { + return this(arguments); + }; + + Stack.prototype.toString = function() { + return this.__toString('Stack [', ']'); + }; + + // @pragma Access + + Stack.prototype.get = function(index, notSetValue) { + var head = this._head; + index = wrapIndex(this, index); + while (head && index--) { + head = head.next; + } + return head ? head.value : notSetValue; + }; + + Stack.prototype.peek = function() { + return this._head && this._head.value; + }; + + // @pragma Modification + + Stack.prototype.push = function(/*...values*/) { + if (arguments.length === 0) { + return this; + } + var newSize = this.size + arguments.length; + var head = this._head; + for (var ii = arguments.length - 1; ii >= 0; ii--) { + head = { + value: arguments[ii], + next: head + }; + } + if (this.__ownerID) { + this.size = newSize; + this._head = head; + this.__hash = undefined; + this.__altered = true; + return this; + } + return makeStack(newSize, head); + }; + + Stack.prototype.pushAll = function(iter) { + iter = IndexedIterable(iter); + if (iter.size === 0) { + return this; + } + assertNotInfinite(iter.size); + var newSize = this.size; + var head = this._head; + iter.reverse().forEach(function(value ) { + newSize++; + head = { + value: value, + next: head + }; + }); + if (this.__ownerID) { + this.size = newSize; + this._head = head; + this.__hash = undefined; + this.__altered = true; + return this; + } + return makeStack(newSize, head); + }; + + Stack.prototype.pop = function() { + return this.slice(1); + }; + + Stack.prototype.unshift = function(/*...values*/) { + return this.push.apply(this, arguments); + }; + + Stack.prototype.unshiftAll = function(iter) { + return this.pushAll(iter); + }; + + Stack.prototype.shift = function() { + return this.pop.apply(this, arguments); + }; + + Stack.prototype.clear = function() { + if (this.size === 0) { + return this; + } + if (this.__ownerID) { + this.size = 0; + this._head = undefined; + this.__hash = undefined; + this.__altered = true; + return this; + } + return emptyStack(); + }; + + Stack.prototype.slice = function(begin, end) { + if (wholeSlice(begin, end, this.size)) { + return this; + } + var resolvedBegin = resolveBegin(begin, this.size); + var resolvedEnd = resolveEnd(end, this.size); + if (resolvedEnd !== this.size) { + // super.slice(begin, end); + return IndexedCollection.prototype.slice.call(this, begin, end); + } + var newSize = this.size - resolvedBegin; + var head = this._head; + while (resolvedBegin--) { + head = head.next; + } + if (this.__ownerID) { + this.size = newSize; + this._head = head; + this.__hash = undefined; + this.__altered = true; + return this; + } + return makeStack(newSize, head); + }; + + // @pragma Mutability + + Stack.prototype.__ensureOwner = function(ownerID) { + if (ownerID === this.__ownerID) { + return this; + } + if (!ownerID) { + this.__ownerID = ownerID; + this.__altered = false; + return this; + } + return makeStack(this.size, this._head, ownerID, this.__hash); + }; + + // @pragma Iteration + + Stack.prototype.__iterate = function(fn, reverse) { + if (reverse) { + return this.reverse().__iterate(fn); + } + var iterations = 0; + var node = this._head; + while (node) { + if (fn(node.value, iterations++, this) === false) { + break; + } + node = node.next; + } + return iterations; + }; + + Stack.prototype.__iterator = function(type, reverse) { + if (reverse) { + return this.reverse().__iterator(type); + } + var iterations = 0; + var node = this._head; + return new Iterator(function() { + if (node) { + var value = node.value; + node = node.next; + return iteratorValue(type, iterations++, value); + } + return iteratorDone(); + }); + }; + + + function isStack(maybeStack) { + return !!(maybeStack && maybeStack[IS_STACK_SENTINEL]); + } + + Stack.isStack = isStack; + + var IS_STACK_SENTINEL = '@@__IMMUTABLE_STACK__@@'; + + var StackPrototype = Stack.prototype; + StackPrototype[IS_STACK_SENTINEL] = true; + StackPrototype.withMutations = MapPrototype.withMutations; + StackPrototype.asMutable = MapPrototype.asMutable; + StackPrototype.asImmutable = MapPrototype.asImmutable; + StackPrototype.wasAltered = MapPrototype.wasAltered; + + + function makeStack(size, head, ownerID, hash) { + var map = Object.create(StackPrototype); + map.size = size; + map._head = head; + map.__ownerID = ownerID; + map.__hash = hash; + map.__altered = false; + return map; + } + + var EMPTY_STACK; + function emptyStack() { + return EMPTY_STACK || (EMPTY_STACK = makeStack(0)); + } + + /** + * Contributes additional methods to a constructor + */ + function mixin(ctor, methods) { + var keyCopier = function(key ) { ctor.prototype[key] = methods[key]; }; + Object.keys(methods).forEach(keyCopier); + Object.getOwnPropertySymbols && + Object.getOwnPropertySymbols(methods).forEach(keyCopier); + return ctor; + } + + Iterable.Iterator = Iterator; + + mixin(Iterable, { + + // ### Conversion to other types + + toArray: function() { + assertNotInfinite(this.size); + var array = new Array(this.size || 0); + this.valueSeq().__iterate(function(v, i) { array[i] = v; }); + return array; + }, + + toIndexedSeq: function() { + return new ToIndexedSequence(this); + }, + + toJS: function() { + return this.toSeq().map( + function(value ) {return value && typeof value.toJS === 'function' ? value.toJS() : value} + ).__toJS(); + }, + + toJSON: function() { + return this.toSeq().map( + function(value ) {return value && typeof value.toJSON === 'function' ? value.toJSON() : value} + ).__toJS(); + }, + + toKeyedSeq: function() { + return new ToKeyedSequence(this, true); + }, + + toMap: function() { + // Use Late Binding here to solve the circular dependency. + return Map(this.toKeyedSeq()); + }, + + toObject: function() { + assertNotInfinite(this.size); + var object = {}; + this.__iterate(function(v, k) { object[k] = v; }); + return object; + }, + + toOrderedMap: function() { + // Use Late Binding here to solve the circular dependency. + return OrderedMap(this.toKeyedSeq()); + }, + + toOrderedSet: function() { + // Use Late Binding here to solve the circular dependency. + return OrderedSet(isKeyed(this) ? this.valueSeq() : this); + }, + + toSet: function() { + // Use Late Binding here to solve the circular dependency. + return Set(isKeyed(this) ? this.valueSeq() : this); + }, + + toSetSeq: function() { + return new ToSetSequence(this); + }, + + toSeq: function() { + return isIndexed(this) ? this.toIndexedSeq() : + isKeyed(this) ? this.toKeyedSeq() : + this.toSetSeq(); + }, + + toStack: function() { + // Use Late Binding here to solve the circular dependency. + return Stack(isKeyed(this) ? this.valueSeq() : this); + }, + + toList: function() { + // Use Late Binding here to solve the circular dependency. + return List(isKeyed(this) ? this.valueSeq() : this); + }, + + + // ### Common JavaScript methods and properties + + toString: function() { + return '[Iterable]'; + }, + + __toString: function(head, tail) { + if (this.size === 0) { + return head + tail; + } + return head + ' ' + this.toSeq().map(this.__toStringMapper).join(', ') + ' ' + tail; + }, + + + // ### ES6 Collection methods (ES6 Array and Map) + + concat: function() {var values = SLICE$0.call(arguments, 0); + return reify(this, concatFactory(this, values)); + }, + + includes: function(searchValue) { + return this.some(function(value ) {return is(value, searchValue)}); + }, + + entries: function() { + return this.__iterator(ITERATE_ENTRIES); + }, + + every: function(predicate, context) { + assertNotInfinite(this.size); + var returnValue = true; + this.__iterate(function(v, k, c) { + if (!predicate.call(context, v, k, c)) { + returnValue = false; + return false; + } + }); + return returnValue; + }, + + filter: function(predicate, context) { + return reify(this, filterFactory(this, predicate, context, true)); + }, + + find: function(predicate, context, notSetValue) { + var entry = this.findEntry(predicate, context); + return entry ? entry[1] : notSetValue; + }, + + findEntry: function(predicate, context) { + var found; + this.__iterate(function(v, k, c) { + if (predicate.call(context, v, k, c)) { + found = [k, v]; + return false; + } + }); + return found; + }, + + findLastEntry: function(predicate, context) { + return this.toSeq().reverse().findEntry(predicate, context); + }, + + forEach: function(sideEffect, context) { + assertNotInfinite(this.size); + return this.__iterate(context ? sideEffect.bind(context) : sideEffect); + }, + + join: function(separator) { + assertNotInfinite(this.size); + separator = separator !== undefined ? '' + separator : ','; + var joined = ''; + var isFirst = true; + this.__iterate(function(v ) { + isFirst ? (isFirst = false) : (joined += separator); + joined += v !== null && v !== undefined ? v.toString() : ''; + }); + return joined; + }, + + keys: function() { + return this.__iterator(ITERATE_KEYS); + }, + + map: function(mapper, context) { + return reify(this, mapFactory(this, mapper, context)); + }, + + reduce: function(reducer, initialReduction, context) { + assertNotInfinite(this.size); + var reduction; + var useFirst; + if (arguments.length < 2) { + useFirst = true; + } else { + reduction = initialReduction; + } + this.__iterate(function(v, k, c) { + if (useFirst) { + useFirst = false; + reduction = v; + } else { + reduction = reducer.call(context, reduction, v, k, c); + } + }); + return reduction; + }, + + reduceRight: function(reducer, initialReduction, context) { + var reversed = this.toKeyedSeq().reverse(); + return reversed.reduce.apply(reversed, arguments); + }, + + reverse: function() { + return reify(this, reverseFactory(this, true)); + }, + + slice: function(begin, end) { + return reify(this, sliceFactory(this, begin, end, true)); + }, + + some: function(predicate, context) { + return !this.every(not(predicate), context); + }, + + sort: function(comparator) { + return reify(this, sortFactory(this, comparator)); + }, + + values: function() { + return this.__iterator(ITERATE_VALUES); + }, + + + // ### More sequential methods + + butLast: function() { + return this.slice(0, -1); + }, + + isEmpty: function() { + return this.size !== undefined ? this.size === 0 : !this.some(function() {return true}); + }, + + count: function(predicate, context) { + return ensureSize( + predicate ? this.toSeq().filter(predicate, context) : this + ); + }, + + countBy: function(grouper, context) { + return countByFactory(this, grouper, context); + }, + + equals: function(other) { + return deepEqual(this, other); + }, + + entrySeq: function() { + var iterable = this; + if (iterable._cache) { + // We cache as an entries array, so we can just return the cache! + return new ArraySeq(iterable._cache); + } + var entriesSequence = iterable.toSeq().map(entryMapper).toIndexedSeq(); + entriesSequence.fromEntrySeq = function() {return iterable.toSeq()}; + return entriesSequence; + }, + + filterNot: function(predicate, context) { + return this.filter(not(predicate), context); + }, + + findLast: function(predicate, context, notSetValue) { + return this.toKeyedSeq().reverse().find(predicate, context, notSetValue); + }, + + first: function() { + return this.find(returnTrue); + }, + + flatMap: function(mapper, context) { + return reify(this, flatMapFactory(this, mapper, context)); + }, + + flatten: function(depth) { + return reify(this, flattenFactory(this, depth, true)); + }, + + fromEntrySeq: function() { + return new FromEntriesSequence(this); + }, + + get: function(searchKey, notSetValue) { + return this.find(function(_, key) {return is(key, searchKey)}, undefined, notSetValue); + }, + + getIn: function(searchKeyPath, notSetValue) { + var nested = this; + // Note: in an ES6 environment, we would prefer: + // for (var key of searchKeyPath) { + var iter = forceIterator(searchKeyPath); + var step; + while (!(step = iter.next()).done) { + var key = step.value; + nested = nested && nested.get ? nested.get(key, NOT_SET) : NOT_SET; + if (nested === NOT_SET) { + return notSetValue; + } + } + return nested; + }, + + groupBy: function(grouper, context) { + return groupByFactory(this, grouper, context); + }, + + has: function(searchKey) { + return this.get(searchKey, NOT_SET) !== NOT_SET; + }, + + hasIn: function(searchKeyPath) { + return this.getIn(searchKeyPath, NOT_SET) !== NOT_SET; + }, + + isSubset: function(iter) { + iter = typeof iter.includes === 'function' ? iter : Iterable(iter); + return this.every(function(value ) {return iter.includes(value)}); + }, + + isSuperset: function(iter) { + iter = typeof iter.isSubset === 'function' ? iter : Iterable(iter); + return iter.isSubset(this); + }, + + keySeq: function() { + return this.toSeq().map(keyMapper).toIndexedSeq(); + }, + + last: function() { + return this.toSeq().reverse().first(); + }, + + max: function(comparator) { + return maxFactory(this, comparator); + }, + + maxBy: function(mapper, comparator) { + return maxFactory(this, comparator, mapper); + }, + + min: function(comparator) { + return maxFactory(this, comparator ? neg(comparator) : defaultNegComparator); + }, + + minBy: function(mapper, comparator) { + return maxFactory(this, comparator ? neg(comparator) : defaultNegComparator, mapper); + }, + + rest: function() { + return this.slice(1); + }, + + skip: function(amount) { + return this.slice(Math.max(0, amount)); + }, + + skipLast: function(amount) { + return reify(this, this.toSeq().reverse().skip(amount).reverse()); + }, + + skipWhile: function(predicate, context) { + return reify(this, skipWhileFactory(this, predicate, context, true)); + }, + + skipUntil: function(predicate, context) { + return this.skipWhile(not(predicate), context); + }, + + sortBy: function(mapper, comparator) { + return reify(this, sortFactory(this, comparator, mapper)); + }, + + take: function(amount) { + return this.slice(0, Math.max(0, amount)); + }, + + takeLast: function(amount) { + return reify(this, this.toSeq().reverse().take(amount).reverse()); + }, + + takeWhile: function(predicate, context) { + return reify(this, takeWhileFactory(this, predicate, context)); + }, + + takeUntil: function(predicate, context) { + return this.takeWhile(not(predicate), context); + }, + + valueSeq: function() { + return this.toIndexedSeq(); + }, + + + // ### Hashable Object + + hashCode: function() { + return this.__hash || (this.__hash = hashIterable(this)); + } + + + // ### Internal + + // abstract __iterate(fn, reverse) + + // abstract __iterator(type, reverse) + }); + + // var IS_ITERABLE_SENTINEL = '@@__IMMUTABLE_ITERABLE__@@'; + // var IS_KEYED_SENTINEL = '@@__IMMUTABLE_KEYED__@@'; + // var IS_INDEXED_SENTINEL = '@@__IMMUTABLE_INDEXED__@@'; + // var IS_ORDERED_SENTINEL = '@@__IMMUTABLE_ORDERED__@@'; + + var IterablePrototype = Iterable.prototype; + IterablePrototype[IS_ITERABLE_SENTINEL] = true; + IterablePrototype[ITERATOR_SYMBOL] = IterablePrototype.values; + IterablePrototype.__toJS = IterablePrototype.toArray; + IterablePrototype.__toStringMapper = quoteString; + IterablePrototype.inspect = + IterablePrototype.toSource = function() { return this.toString(); }; + IterablePrototype.chain = IterablePrototype.flatMap; + IterablePrototype.contains = IterablePrototype.includes; + + // Temporary warning about using length + (function () { + try { + Object.defineProperty(IterablePrototype, 'length', { + get: function () { + if (!Iterable.noLengthWarning) { + var stack; + try { + throw new Error(); + } catch (error) { + stack = error.stack; + } + if (stack.indexOf('_wrapObject') === -1) { + console && console.warn && console.warn( + 'iterable.length has been deprecated, '+ + 'use iterable.size or iterable.count(). '+ + 'This warning will become a silent error in a future version. ' + + stack + ); + return this.size; + } + } + } + }); + } catch (e) {} + })(); + + + + mixin(KeyedIterable, { + + // ### More sequential methods + + flip: function() { + return reify(this, flipFactory(this)); + }, + + findKey: function(predicate, context) { + var entry = this.findEntry(predicate, context); + return entry && entry[0]; + }, + + findLastKey: function(predicate, context) { + return this.toSeq().reverse().findKey(predicate, context); + }, + + keyOf: function(searchValue) { + return this.findKey(function(value ) {return is(value, searchValue)}); + }, + + lastKeyOf: function(searchValue) { + return this.findLastKey(function(value ) {return is(value, searchValue)}); + }, + + mapEntries: function(mapper, context) {var this$0 = this; + var iterations = 0; + return reify(this, + this.toSeq().map( + function(v, k) {return mapper.call(context, [k, v], iterations++, this$0)} + ).fromEntrySeq() + ); + }, + + mapKeys: function(mapper, context) {var this$0 = this; + return reify(this, + this.toSeq().flip().map( + function(k, v) {return mapper.call(context, k, v, this$0)} + ).flip() + ); + } + + }); + + var KeyedIterablePrototype = KeyedIterable.prototype; + KeyedIterablePrototype[IS_KEYED_SENTINEL] = true; + KeyedIterablePrototype[ITERATOR_SYMBOL] = IterablePrototype.entries; + KeyedIterablePrototype.__toJS = IterablePrototype.toObject; + KeyedIterablePrototype.__toStringMapper = function(v, k) {return JSON.stringify(k) + ': ' + quoteString(v)}; + + + + mixin(IndexedIterable, { + + // ### Conversion to other types + + toKeyedSeq: function() { + return new ToKeyedSequence(this, false); + }, + + + // ### ES6 Collection methods (ES6 Array and Map) + + filter: function(predicate, context) { + return reify(this, filterFactory(this, predicate, context, false)); + }, + + findIndex: function(predicate, context) { + var entry = this.findEntry(predicate, context); + return entry ? entry[0] : -1; + }, + + indexOf: function(searchValue) { + var key = this.toKeyedSeq().keyOf(searchValue); + return key === undefined ? -1 : key; + }, + + lastIndexOf: function(searchValue) { + var key = this.toKeyedSeq().reverse().keyOf(searchValue); + return key === undefined ? -1 : key; + }, + + reverse: function() { + return reify(this, reverseFactory(this, false)); + }, + + slice: function(begin, end) { + return reify(this, sliceFactory(this, begin, end, false)); + }, + + splice: function(index, removeNum /*, ...values*/) { + var numArgs = arguments.length; + removeNum = Math.max(removeNum | 0, 0); + if (numArgs === 0 || (numArgs === 2 && !removeNum)) { + return this; + } + // If index is negative, it should resolve relative to the size of the + // collection. However size may be expensive to compute if not cached, so + // only call count() if the number is in fact negative. + index = resolveBegin(index, index < 0 ? this.count() : this.size); + var spliced = this.slice(0, index); + return reify( + this, + numArgs === 1 ? + spliced : + spliced.concat(arrCopy(arguments, 2), this.slice(index + removeNum)) + ); + }, + + + // ### More collection methods + + findLastIndex: function(predicate, context) { + var key = this.toKeyedSeq().findLastKey(predicate, context); + return key === undefined ? -1 : key; + }, + + first: function() { + return this.get(0); + }, + + flatten: function(depth) { + return reify(this, flattenFactory(this, depth, false)); + }, + + get: function(index, notSetValue) { + index = wrapIndex(this, index); + return (index < 0 || (this.size === Infinity || + (this.size !== undefined && index > this.size))) ? + notSetValue : + this.find(function(_, key) {return key === index}, undefined, notSetValue); + }, + + has: function(index) { + index = wrapIndex(this, index); + return index >= 0 && (this.size !== undefined ? + this.size === Infinity || index < this.size : + this.indexOf(index) !== -1 + ); + }, + + interpose: function(separator) { + return reify(this, interposeFactory(this, separator)); + }, + + interleave: function(/*...iterables*/) { + var iterables = [this].concat(arrCopy(arguments)); + var zipped = zipWithFactory(this.toSeq(), IndexedSeq.of, iterables); + var interleaved = zipped.flatten(true); + if (zipped.size) { + interleaved.size = zipped.size * iterables.length; + } + return reify(this, interleaved); + }, + + last: function() { + return this.get(-1); + }, + + skipWhile: function(predicate, context) { + return reify(this, skipWhileFactory(this, predicate, context, false)); + }, + + zip: function(/*, ...iterables */) { + var iterables = [this].concat(arrCopy(arguments)); + return reify(this, zipWithFactory(this, defaultZipper, iterables)); + }, + + zipWith: function(zipper/*, ...iterables */) { + var iterables = arrCopy(arguments); + iterables[0] = this; + return reify(this, zipWithFactory(this, zipper, iterables)); + } + + }); + + IndexedIterable.prototype[IS_INDEXED_SENTINEL] = true; + IndexedIterable.prototype[IS_ORDERED_SENTINEL] = true; + + + + mixin(SetIterable, { + + // ### ES6 Collection methods (ES6 Array and Map) + + get: function(value, notSetValue) { + return this.has(value) ? value : notSetValue; + }, + + includes: function(value) { + return this.has(value); + }, + + + // ### More sequential methods + + keySeq: function() { + return this.valueSeq(); + } + + }); + + SetIterable.prototype.has = IterablePrototype.includes; + SetIterable.prototype.contains = SetIterable.prototype.includes; + + + // Mixin subclasses + + mixin(KeyedSeq, KeyedIterable.prototype); + mixin(IndexedSeq, IndexedIterable.prototype); + mixin(SetSeq, SetIterable.prototype); + + mixin(KeyedCollection, KeyedIterable.prototype); + mixin(IndexedCollection, IndexedIterable.prototype); + mixin(SetCollection, SetIterable.prototype); + + + // #pragma Helper functions + + function keyMapper(v, k) { + return k; + } + + function entryMapper(v, k) { + return [k, v]; + } + + function not(predicate) { + return function() { + return !predicate.apply(this, arguments); + } + } + + function neg(predicate) { + return function() { + return -predicate.apply(this, arguments); + } + } + + function quoteString(value) { + return typeof value === 'string' ? JSON.stringify(value) : value; + } + + function defaultZipper() { + return arrCopy(arguments); + } + + function defaultNegComparator(a, b) { + return a < b ? 1 : a > b ? -1 : 0; + } + + function hashIterable(iterable) { + if (iterable.size === Infinity) { + return 0; + } + var ordered = isOrdered(iterable); + var keyed = isKeyed(iterable); + var h = ordered ? 1 : 0; + var size = iterable.__iterate( + keyed ? + ordered ? + function(v, k) { h = 31 * h + hashMerge(hash(v), hash(k)) | 0; } : + function(v, k) { h = h + hashMerge(hash(v), hash(k)) | 0; } : + ordered ? + function(v ) { h = 31 * h + hash(v) | 0; } : + function(v ) { h = h + hash(v) | 0; } + ); + return murmurHashOfSize(size, h); + } + + function murmurHashOfSize(size, h) { + h = imul(h, 0xCC9E2D51); + h = imul(h << 15 | h >>> -15, 0x1B873593); + h = imul(h << 13 | h >>> -13, 5); + h = (h + 0xE6546B64 | 0) ^ size; + h = imul(h ^ h >>> 16, 0x85EBCA6B); + h = imul(h ^ h >>> 13, 0xC2B2AE35); + h = smi(h ^ h >>> 16); + return h; + } + + function hashMerge(a, b) { + return a ^ b + 0x9E3779B9 + (a << 6) + (a >> 2) | 0; // int + } + + var Immutable = { + + Iterable: Iterable, + + Seq: Seq, + Collection: Collection, + Map: Map, + OrderedMap: OrderedMap, + List: List, + Stack: Stack, + Set: Set, + OrderedSet: OrderedSet, + + Record: Record, + Range: Range, + Repeat: Repeat, + + is: is, + fromJS: fromJS + + }; + + return Immutable; + +}));
\ No newline at end of file diff --git a/devtools/client/shared/vendor/jsol.js b/devtools/client/shared/vendor/jsol.js new file mode 100755 index 000000000..a87948c43 --- /dev/null +++ b/devtools/client/shared/vendor/jsol.js @@ -0,0 +1,97 @@ +/* + * Copyright 2010, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +(function () { + /** + JSOL stands for JavaScript Object Literal which is a string representing + an object in JavaScript syntax. + + For example: + + {foo:"bar"} is equivalent to {"foo":"bar"} in JavaScript. Both are valid JSOL. + + Note that {"foo":"bar"} is proper JSON[1] therefore you can use one of the many + JSON parsers out there like json2.js[2] or even the native browser's JSON parser, + if available. + + However, {foo:"bar"} is NOT proper JSON but valid Javascript syntax for + representing an object with one key, "foo" and its value, "bar". + Using a JSON parser is not an option since this is NOT proper JSON. + + You can use JSOL.parse to safely parse any string that reprsents a JavaScript Object Literal. + JSOL.parse will throw an Invalid JSOL exception on function calls, function declarations and variable references. + + Examples: + + JSOL.parse('{foo:"bar"}'); // valid + + JSOL.parse('{evil:(function(){alert("I\'m evil");})()}'); // invalid function calls + + JSOL.parse('{fn:function() { }}'); // invalid function declarations + + var bar = "bar"; + JSOL.parse('{foo:bar}'); // invalid variable references + + [1] http://www.json.org + [2] http://www.json.org/json2.js + */ + var trim = /^(\s|\u00A0)+|(\s|\u00A0)+$/g; // Used for trimming whitespace + var JSOL = { + parse: function(text) { + // make sure text is a "string" + if (typeof text !== "string" || !text) { + return null; + } + // Make sure leading/trailing whitespace is removed + text = text.replace(trim, ""); + // Make sure the incoming text is actual JSOL (or Javascript Object Literal) + // Logic borrowed from http://json.org/json2.js + if ( /^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@") + .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]") + .replace(/(?:^|:|,)(?:\s*\[)+/g, ":") + /** everything up to this point is json2.js **/ + /** this is the 5th stage where it accepts unquoted keys **/ + .replace(/\w*\s*\:/g, ":")) ) { + return (new Function("return " + text))(); + } + else { + throw("Invalid JSOL: " + text); + } + } + }; + + if (typeof define === "function" && define.amd) { + define(JSOL); + } else if (typeof module === "object" && module.exports) { + module.exports = JSOL; + } else { + this.JSOL = JSOL; + } +})(); diff --git a/devtools/client/shared/vendor/moz.build b/devtools/client/shared/vendor/moz.build new file mode 100644 index 000000000..e04221293 --- /dev/null +++ b/devtools/client/shared/vendor/moz.build @@ -0,0 +1,29 @@ +# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*- +# vim: set filetype=python: +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. +modules = [] +modules += [ + 'immutable.js', + 'jsol.js', + 'react-addons-shallow-compare.js', +] + +# react-dev is used if either debug mode is enabled, +# so include it for both +if CONFIG['DEBUG_JS_MODULES'] or CONFIG['MOZ_DEBUG']: + modules += ['react-dev.js'] + +modules += [ + 'react-dom.js', + 'react-proxy.js', + 'react-redux.js', + 'react-virtualized.js', + 'react.js', + 'redux.js', + 'reselect.js', + 'seamless-immutable.js', +] + +DevToolsModules(*modules) diff --git a/devtools/client/shared/vendor/react-addons-shallow-compare.js b/devtools/client/shared/vendor/react-addons-shallow-compare.js new file mode 100644 index 000000000..6a1c723cc --- /dev/null +++ b/devtools/client/shared/vendor/react-addons-shallow-compare.js @@ -0,0 +1,9 @@ +/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set ft=javascript ts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +module.exports = require("devtools/client/shared/vendor/react").addons.shallowCompare; diff --git a/devtools/client/shared/vendor/react-dev.js b/devtools/client/shared/vendor/react-dev.js new file mode 100644 index 000000000..90e5e177a --- /dev/null +++ b/devtools/client/shared/vendor/react-dev.js @@ -0,0 +1,20763 @@ + /** + * React (with addons) v0.14.6 + */ +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.React = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactWithAddons + */ + +/** + * This module exists purely in the open source project, and is meant as a way + * to create a separate standalone build of React. This build has "addons", or + * functionality we've built and think might be useful but doesn't have a good + * place to live inside React core. + */ + +'use strict'; + +var LinkedStateMixin = _dereq_(22); +var React = _dereq_(26); +var ReactComponentWithPureRenderMixin = _dereq_(37); +var ReactCSSTransitionGroup = _dereq_(29); +var ReactFragment = _dereq_(64); +var ReactTransitionGroup = _dereq_(94); +var ReactUpdates = _dereq_(96); + +var cloneWithProps = _dereq_(118); +var shallowCompare = _dereq_(140); +var update = _dereq_(143); +var warning = _dereq_(173); + +var warnedAboutBatchedUpdates = false; + +React.addons = { + CSSTransitionGroup: ReactCSSTransitionGroup, + LinkedStateMixin: LinkedStateMixin, + PureRenderMixin: ReactComponentWithPureRenderMixin, + TransitionGroup: ReactTransitionGroup, + + batchedUpdates: function () { + if ("development" !== 'production') { + "development" !== 'production' ? warning(warnedAboutBatchedUpdates, 'React.addons.batchedUpdates is deprecated. Use ' + 'ReactDOM.unstable_batchedUpdates instead.') : undefined; + warnedAboutBatchedUpdates = true; + } + return ReactUpdates.batchedUpdates.apply(this, arguments); + }, + cloneWithProps: cloneWithProps, + createFragment: ReactFragment.create, + shallowCompare: shallowCompare, + update: update +}; + +React.addons.TestUtils = _dereq_(91); + +if ("development" !== 'production') { + React.addons.Perf = _dereq_(55); +} + +module.exports = React; +},{"118":118,"140":140,"143":143,"173":173,"22":22,"26":26,"29":29,"37":37,"55":55,"64":64,"91":91,"94":94,"96":96}],2:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule AutoFocusUtils + * @typechecks static-only + */ + +'use strict'; + +var ReactMount = _dereq_(72); + +var findDOMNode = _dereq_(122); +var focusNode = _dereq_(155); + +var Mixin = { + componentDidMount: function () { + if (this.props.autoFocus) { + focusNode(findDOMNode(this)); + } + } +}; + +var AutoFocusUtils = { + Mixin: Mixin, + + focusDOMComponent: function () { + focusNode(ReactMount.getNode(this._rootNodeID)); + } +}; + +module.exports = AutoFocusUtils; +},{"122":122,"155":155,"72":72}],3:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015 Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule BeforeInputEventPlugin + * @typechecks static-only + */ + +'use strict'; + +var EventConstants = _dereq_(15); +var EventPropagators = _dereq_(19); +var ExecutionEnvironment = _dereq_(147); +var FallbackCompositionState = _dereq_(20); +var SyntheticCompositionEvent = _dereq_(103); +var SyntheticInputEvent = _dereq_(107); + +var keyOf = _dereq_(166); + +var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space +var START_KEYCODE = 229; + +var canUseCompositionEvent = ExecutionEnvironment.canUseDOM && 'CompositionEvent' in window; + +var documentMode = null; +if (ExecutionEnvironment.canUseDOM && 'documentMode' in document) { + documentMode = document.documentMode; +} + +// Webkit offers a very useful `textInput` event that can be used to +// directly represent `beforeInput`. The IE `textinput` event is not as +// useful, so we don't use it. +var canUseTextInputEvent = ExecutionEnvironment.canUseDOM && 'TextEvent' in window && !documentMode && !isPresto(); + +// In IE9+, we have access to composition events, but the data supplied +// by the native compositionend event may be incorrect. Japanese ideographic +// spaces, for instance (\u3000) are not recorded correctly. +var useFallbackCompositionData = ExecutionEnvironment.canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11); + +/** + * Opera <= 12 includes TextEvent in window, but does not fire + * text input events. Rely on keypress instead. + */ +function isPresto() { + var opera = window.opera; + return typeof opera === 'object' && typeof opera.version === 'function' && parseInt(opera.version(), 10) <= 12; +} + +var SPACEBAR_CODE = 32; +var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE); + +var topLevelTypes = EventConstants.topLevelTypes; + +// Events and their corresponding property names. +var eventTypes = { + beforeInput: { + phasedRegistrationNames: { + bubbled: keyOf({ onBeforeInput: null }), + captured: keyOf({ onBeforeInputCapture: null }) + }, + dependencies: [topLevelTypes.topCompositionEnd, topLevelTypes.topKeyPress, topLevelTypes.topTextInput, topLevelTypes.topPaste] + }, + compositionEnd: { + phasedRegistrationNames: { + bubbled: keyOf({ onCompositionEnd: null }), + captured: keyOf({ onCompositionEndCapture: null }) + }, + dependencies: [topLevelTypes.topBlur, topLevelTypes.topCompositionEnd, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown] + }, + compositionStart: { + phasedRegistrationNames: { + bubbled: keyOf({ onCompositionStart: null }), + captured: keyOf({ onCompositionStartCapture: null }) + }, + dependencies: [topLevelTypes.topBlur, topLevelTypes.topCompositionStart, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown] + }, + compositionUpdate: { + phasedRegistrationNames: { + bubbled: keyOf({ onCompositionUpdate: null }), + captured: keyOf({ onCompositionUpdateCapture: null }) + }, + dependencies: [topLevelTypes.topBlur, topLevelTypes.topCompositionUpdate, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown] + } +}; + +// Track whether we've ever handled a keypress on the space key. +var hasSpaceKeypress = false; + +/** + * Return whether a native keypress event is assumed to be a command. + * This is required because Firefox fires `keypress` events for key commands + * (cut, copy, select-all, etc.) even though no character is inserted. + */ +function isKeypressCommand(nativeEvent) { + return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) && + // ctrlKey && altKey is equivalent to AltGr, and is not a command. + !(nativeEvent.ctrlKey && nativeEvent.altKey); +} + +/** + * Translate native top level events into event types. + * + * @param {string} topLevelType + * @return {object} + */ +function getCompositionEventType(topLevelType) { + switch (topLevelType) { + case topLevelTypes.topCompositionStart: + return eventTypes.compositionStart; + case topLevelTypes.topCompositionEnd: + return eventTypes.compositionEnd; + case topLevelTypes.topCompositionUpdate: + return eventTypes.compositionUpdate; + } +} + +/** + * Does our fallback best-guess model think this event signifies that + * composition has begun? + * + * @param {string} topLevelType + * @param {object} nativeEvent + * @return {boolean} + */ +function isFallbackCompositionStart(topLevelType, nativeEvent) { + return topLevelType === topLevelTypes.topKeyDown && nativeEvent.keyCode === START_KEYCODE; +} + +/** + * Does our fallback mode think that this event is the end of composition? + * + * @param {string} topLevelType + * @param {object} nativeEvent + * @return {boolean} + */ +function isFallbackCompositionEnd(topLevelType, nativeEvent) { + switch (topLevelType) { + case topLevelTypes.topKeyUp: + // Command keys insert or clear IME input. + return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1; + case topLevelTypes.topKeyDown: + // Expect IME keyCode on each keydown. If we get any other + // code we must have exited earlier. + return nativeEvent.keyCode !== START_KEYCODE; + case topLevelTypes.topKeyPress: + case topLevelTypes.topMouseDown: + case topLevelTypes.topBlur: + // Events are not possible without cancelling IME. + return true; + default: + return false; + } +} + +/** + * Google Input Tools provides composition data via a CustomEvent, + * with the `data` property populated in the `detail` object. If this + * is available on the event object, use it. If not, this is a plain + * composition event and we have nothing special to extract. + * + * @param {object} nativeEvent + * @return {?string} + */ +function getDataFromCustomEvent(nativeEvent) { + var detail = nativeEvent.detail; + if (typeof detail === 'object' && 'data' in detail) { + return detail.data; + } + return null; +} + +// Track the current IME composition fallback object, if any. +var currentComposition = null; + +/** + * @param {string} topLevelType Record from `EventConstants`. + * @param {DOMEventTarget} topLevelTarget The listening component root node. + * @param {string} topLevelTargetID ID of `topLevelTarget`. + * @param {object} nativeEvent Native browser event. + * @return {?object} A SyntheticCompositionEvent. + */ +function extractCompositionEvent(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) { + var eventType; + var fallbackData; + + if (canUseCompositionEvent) { + eventType = getCompositionEventType(topLevelType); + } else if (!currentComposition) { + if (isFallbackCompositionStart(topLevelType, nativeEvent)) { + eventType = eventTypes.compositionStart; + } + } else if (isFallbackCompositionEnd(topLevelType, nativeEvent)) { + eventType = eventTypes.compositionEnd; + } + + if (!eventType) { + return null; + } + + if (useFallbackCompositionData) { + // The current composition is stored statically and must not be + // overwritten while composition continues. + if (!currentComposition && eventType === eventTypes.compositionStart) { + currentComposition = FallbackCompositionState.getPooled(topLevelTarget); + } else if (eventType === eventTypes.compositionEnd) { + if (currentComposition) { + fallbackData = currentComposition.getData(); + } + } + } + + var event = SyntheticCompositionEvent.getPooled(eventType, topLevelTargetID, nativeEvent, nativeEventTarget); + + if (fallbackData) { + // Inject data generated from fallback path into the synthetic event. + // This matches the property of native CompositionEventInterface. + event.data = fallbackData; + } else { + var customData = getDataFromCustomEvent(nativeEvent); + if (customData !== null) { + event.data = customData; + } + } + + EventPropagators.accumulateTwoPhaseDispatches(event); + return event; +} + +/** + * @param {string} topLevelType Record from `EventConstants`. + * @param {object} nativeEvent Native browser event. + * @return {?string} The string corresponding to this `beforeInput` event. + */ +function getNativeBeforeInputChars(topLevelType, nativeEvent) { + switch (topLevelType) { + case topLevelTypes.topCompositionEnd: + return getDataFromCustomEvent(nativeEvent); + case topLevelTypes.topKeyPress: + /** + * If native `textInput` events are available, our goal is to make + * use of them. However, there is a special case: the spacebar key. + * In Webkit, preventing default on a spacebar `textInput` event + * cancels character insertion, but it *also* causes the browser + * to fall back to its default spacebar behavior of scrolling the + * page. + * + * Tracking at: + * https://code.google.com/p/chromium/issues/detail?id=355103 + * + * To avoid this issue, use the keypress event as if no `textInput` + * event is available. + */ + var which = nativeEvent.which; + if (which !== SPACEBAR_CODE) { + return null; + } + + hasSpaceKeypress = true; + return SPACEBAR_CHAR; + + case topLevelTypes.topTextInput: + // Record the characters to be added to the DOM. + var chars = nativeEvent.data; + + // If it's a spacebar character, assume that we have already handled + // it at the keypress level and bail immediately. Android Chrome + // doesn't give us keycodes, so we need to blacklist it. + if (chars === SPACEBAR_CHAR && hasSpaceKeypress) { + return null; + } + + return chars; + + default: + // For other native event types, do nothing. + return null; + } +} + +/** + * For browsers that do not provide the `textInput` event, extract the + * appropriate string to use for SyntheticInputEvent. + * + * @param {string} topLevelType Record from `EventConstants`. + * @param {object} nativeEvent Native browser event. + * @return {?string} The fallback string for this `beforeInput` event. + */ +function getFallbackBeforeInputChars(topLevelType, nativeEvent) { + // If we are currently composing (IME) and using a fallback to do so, + // try to extract the composed characters from the fallback object. + if (currentComposition) { + if (topLevelType === topLevelTypes.topCompositionEnd || isFallbackCompositionEnd(topLevelType, nativeEvent)) { + var chars = currentComposition.getData(); + FallbackCompositionState.release(currentComposition); + currentComposition = null; + return chars; + } + return null; + } + + switch (topLevelType) { + case topLevelTypes.topPaste: + // If a paste event occurs after a keypress, throw out the input + // chars. Paste events should not lead to BeforeInput events. + return null; + case topLevelTypes.topKeyPress: + /** + * As of v27, Firefox may fire keypress events even when no character + * will be inserted. A few possibilities: + * + * - `which` is `0`. Arrow keys, Esc key, etc. + * + * - `which` is the pressed key code, but no char is available. + * Ex: 'AltGr + d` in Polish. There is no modified character for + * this key combination and no character is inserted into the + * document, but FF fires the keypress for char code `100` anyway. + * No `input` event will occur. + * + * - `which` is the pressed key code, but a command combination is + * being used. Ex: `Cmd+C`. No character is inserted, and no + * `input` event will occur. + */ + if (nativeEvent.which && !isKeypressCommand(nativeEvent)) { + return String.fromCharCode(nativeEvent.which); + } + return null; + case topLevelTypes.topCompositionEnd: + return useFallbackCompositionData ? null : nativeEvent.data; + default: + return null; + } +} + +/** + * Extract a SyntheticInputEvent for `beforeInput`, based on either native + * `textInput` or fallback behavior. + * + * @param {string} topLevelType Record from `EventConstants`. + * @param {DOMEventTarget} topLevelTarget The listening component root node. + * @param {string} topLevelTargetID ID of `topLevelTarget`. + * @param {object} nativeEvent Native browser event. + * @return {?object} A SyntheticInputEvent. + */ +function extractBeforeInputEvent(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) { + var chars; + + if (canUseTextInputEvent) { + chars = getNativeBeforeInputChars(topLevelType, nativeEvent); + } else { + chars = getFallbackBeforeInputChars(topLevelType, nativeEvent); + } + + // If no characters are being inserted, no BeforeInput event should + // be fired. + if (!chars) { + return null; + } + + var event = SyntheticInputEvent.getPooled(eventTypes.beforeInput, topLevelTargetID, nativeEvent, nativeEventTarget); + + event.data = chars; + EventPropagators.accumulateTwoPhaseDispatches(event); + return event; +} + +/** + * Create an `onBeforeInput` event to match + * http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents. + * + * This event plugin is based on the native `textInput` event + * available in Chrome, Safari, Opera, and IE. This event fires after + * `onKeyPress` and `onCompositionEnd`, but before `onInput`. + * + * `beforeInput` is spec'd but not implemented in any browsers, and + * the `input` event does not provide any useful information about what has + * actually been added, contrary to the spec. Thus, `textInput` is the best + * available event to identify the characters that have actually been inserted + * into the target node. + * + * This plugin is also responsible for emitting `composition` events, thus + * allowing us to share composition fallback code for both `beforeInput` and + * `composition` event types. + */ +var BeforeInputEventPlugin = { + + eventTypes: eventTypes, + + /** + * @param {string} topLevelType Record from `EventConstants`. + * @param {DOMEventTarget} topLevelTarget The listening component root node. + * @param {string} topLevelTargetID ID of `topLevelTarget`. + * @param {object} nativeEvent Native browser event. + * @return {*} An accumulation of synthetic events. + * @see {EventPluginHub.extractEvents} + */ + extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) { + return [extractCompositionEvent(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget), extractBeforeInputEvent(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget)]; + } +}; + +module.exports = BeforeInputEventPlugin; +},{"103":103,"107":107,"147":147,"15":15,"166":166,"19":19,"20":20}],4:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule CSSProperty + */ + +'use strict'; + +/** + * CSS properties which accept numbers but are not in units of "px". + */ +var isUnitlessNumber = { + animationIterationCount: true, + boxFlex: true, + boxFlexGroup: true, + boxOrdinalGroup: true, + columnCount: true, + flex: true, + flexGrow: true, + flexPositive: true, + flexShrink: true, + flexNegative: true, + flexOrder: true, + fontWeight: true, + lineClamp: true, + lineHeight: true, + opacity: true, + order: true, + orphans: true, + tabSize: true, + widows: true, + zIndex: true, + zoom: true, + + // SVG-related properties + fillOpacity: true, + stopOpacity: true, + strokeDashoffset: true, + strokeOpacity: true, + strokeWidth: true +}; + +/** + * @param {string} prefix vendor-specific prefix, eg: Webkit + * @param {string} key style name, eg: transitionDuration + * @return {string} style name prefixed with `prefix`, properly camelCased, eg: + * WebkitTransitionDuration + */ +function prefixKey(prefix, key) { + return prefix + key.charAt(0).toUpperCase() + key.substring(1); +} + +/** + * Support style names that may come passed in prefixed by adding permutations + * of vendor prefixes. + */ +var prefixes = ['Webkit', 'ms', 'Moz', 'O']; + +// Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an +// infinite loop, because it iterates over the newly added props too. +Object.keys(isUnitlessNumber).forEach(function (prop) { + prefixes.forEach(function (prefix) { + isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop]; + }); +}); + +/** + * Most style properties can be unset by doing .style[prop] = '' but IE8 + * doesn't like doing that with shorthand properties so for the properties that + * IE8 breaks on, which are listed here, we instead unset each of the + * individual properties. See http://bugs.jquery.com/ticket/12385. + * The 4-value 'clock' properties like margin, padding, border-width seem to + * behave without any problems. Curiously, list-style works too without any + * special prodding. + */ +var shorthandPropertyExpansions = { + background: { + backgroundAttachment: true, + backgroundColor: true, + backgroundImage: true, + backgroundPositionX: true, + backgroundPositionY: true, + backgroundRepeat: true + }, + backgroundPosition: { + backgroundPositionX: true, + backgroundPositionY: true + }, + border: { + borderWidth: true, + borderStyle: true, + borderColor: true + }, + borderBottom: { + borderBottomWidth: true, + borderBottomStyle: true, + borderBottomColor: true + }, + borderLeft: { + borderLeftWidth: true, + borderLeftStyle: true, + borderLeftColor: true + }, + borderRight: { + borderRightWidth: true, + borderRightStyle: true, + borderRightColor: true + }, + borderTop: { + borderTopWidth: true, + borderTopStyle: true, + borderTopColor: true + }, + font: { + fontStyle: true, + fontVariant: true, + fontWeight: true, + fontSize: true, + lineHeight: true, + fontFamily: true + }, + outline: { + outlineWidth: true, + outlineStyle: true, + outlineColor: true + } +}; + +var CSSProperty = { + isUnitlessNumber: isUnitlessNumber, + shorthandPropertyExpansions: shorthandPropertyExpansions +}; + +module.exports = CSSProperty; +},{}],5:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule CSSPropertyOperations + * @typechecks static-only + */ + +'use strict'; + +var CSSProperty = _dereq_(4); +var ExecutionEnvironment = _dereq_(147); +var ReactPerf = _dereq_(78); + +var camelizeStyleName = _dereq_(149); +var dangerousStyleValue = _dereq_(119); +var hyphenateStyleName = _dereq_(160); +var memoizeStringOnly = _dereq_(168); +var warning = _dereq_(173); + +var processStyleName = memoizeStringOnly(function (styleName) { + return hyphenateStyleName(styleName); +}); + +var hasShorthandPropertyBug = false; +var styleFloatAccessor = 'cssFloat'; +if (ExecutionEnvironment.canUseDOM) { + var tempStyle = document.createElementNS('http://www.w3.org/1999/xhtml', 'div').style; + try { + // IE8 throws "Invalid argument." if resetting shorthand style properties. + tempStyle.font = ''; + } catch (e) { + hasShorthandPropertyBug = true; + } + // IE8 only supports accessing cssFloat (standard) as styleFloat + if (document.documentElement.style.cssFloat === undefined) { + styleFloatAccessor = 'styleFloat'; + } +} + +if ("development" !== 'production') { + // 'msTransform' is correct, but the other prefixes should be capitalized + var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/; + + // style values shouldn't contain a semicolon + var badStyleValueWithSemicolonPattern = /;\s*$/; + + var warnedStyleNames = {}; + var warnedStyleValues = {}; + + var warnHyphenatedStyleName = function (name) { + if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { + return; + } + + warnedStyleNames[name] = true; + "development" !== 'production' ? warning(false, 'Unsupported style property %s. Did you mean %s?', name, camelizeStyleName(name)) : undefined; + }; + + var warnBadVendoredStyleName = function (name) { + if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { + return; + } + + warnedStyleNames[name] = true; + "development" !== 'production' ? warning(false, 'Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1)) : undefined; + }; + + var warnStyleValueWithSemicolon = function (name, value) { + if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) { + return; + } + + warnedStyleValues[value] = true; + "development" !== 'production' ? warning(false, 'Style property values shouldn\'t contain a semicolon. ' + 'Try "%s: %s" instead.', name, value.replace(badStyleValueWithSemicolonPattern, '')) : undefined; + }; + + /** + * @param {string} name + * @param {*} value + */ + var warnValidStyle = function (name, value) { + if (name.indexOf('-') > -1) { + warnHyphenatedStyleName(name); + } else if (badVendoredStyleNamePattern.test(name)) { + warnBadVendoredStyleName(name); + } else if (badStyleValueWithSemicolonPattern.test(value)) { + warnStyleValueWithSemicolon(name, value); + } + }; +} + +/** + * Operations for dealing with CSS properties. + */ +var CSSPropertyOperations = { + + /** + * Serializes a mapping of style properties for use as inline styles: + * + * > createMarkupForStyles({width: '200px', height: 0}) + * "width:200px;height:0;" + * + * Undefined values are ignored so that declarative programming is easier. + * The result should be HTML-escaped before insertion into the DOM. + * + * @param {object} styles + * @return {?string} + */ + createMarkupForStyles: function (styles) { + var serialized = ''; + for (var styleName in styles) { + if (!styles.hasOwnProperty(styleName)) { + continue; + } + var styleValue = styles[styleName]; + if ("development" !== 'production') { + warnValidStyle(styleName, styleValue); + } + if (styleValue != null) { + serialized += processStyleName(styleName) + ':'; + serialized += dangerousStyleValue(styleName, styleValue) + ';'; + } + } + return serialized || null; + }, + + /** + * Sets the value for multiple styles on a node. If a value is specified as + * '' (empty string), the corresponding style property will be unset. + * + * @param {DOMElement} node + * @param {object} styles + */ + setValueForStyles: function (node, styles) { + var style = node.style; + for (var styleName in styles) { + if (!styles.hasOwnProperty(styleName)) { + continue; + } + if ("development" !== 'production') { + warnValidStyle(styleName, styles[styleName]); + } + var styleValue = dangerousStyleValue(styleName, styles[styleName]); + if (styleName === 'float') { + styleName = styleFloatAccessor; + } + if (styleValue) { + style[styleName] = styleValue; + } else { + var expansion = hasShorthandPropertyBug && CSSProperty.shorthandPropertyExpansions[styleName]; + if (expansion) { + // Shorthand property that IE8 won't like unsetting, so unset each + // component to placate it + for (var individualStyleName in expansion) { + style[individualStyleName] = ''; + } + } else { + style[styleName] = ''; + } + } + } + } + +}; + +ReactPerf.measureMethods(CSSPropertyOperations, 'CSSPropertyOperations', { + setValueForStyles: 'setValueForStyles' +}); + +module.exports = CSSPropertyOperations; +},{"119":119,"147":147,"149":149,"160":160,"168":168,"173":173,"4":4,"78":78}],6:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule CallbackQueue + */ + +'use strict'; + +var PooledClass = _dereq_(25); + +var assign = _dereq_(24); +var invariant = _dereq_(161); + +/** + * A specialized pseudo-event module to help keep track of components waiting to + * be notified when their DOM representations are available for use. + * + * This implements `PooledClass`, so you should never need to instantiate this. + * Instead, use `CallbackQueue.getPooled()`. + * + * @class ReactMountReady + * @implements PooledClass + * @internal + */ +function CallbackQueue() { + this._callbacks = null; + this._contexts = null; +} + +assign(CallbackQueue.prototype, { + + /** + * Enqueues a callback to be invoked when `notifyAll` is invoked. + * + * @param {function} callback Invoked when `notifyAll` is invoked. + * @param {?object} context Context to call `callback` with. + * @internal + */ + enqueue: function (callback, context) { + this._callbacks = this._callbacks || []; + this._contexts = this._contexts || []; + this._callbacks.push(callback); + this._contexts.push(context); + }, + + /** + * Invokes all enqueued callbacks and clears the queue. This is invoked after + * the DOM representation of a component has been created or updated. + * + * @internal + */ + notifyAll: function () { + var callbacks = this._callbacks; + var contexts = this._contexts; + if (callbacks) { + !(callbacks.length === contexts.length) ? "development" !== 'production' ? invariant(false, 'Mismatched list of contexts in callback queue') : invariant(false) : undefined; + this._callbacks = null; + this._contexts = null; + for (var i = 0; i < callbacks.length; i++) { + callbacks[i].call(contexts[i]); + } + callbacks.length = 0; + contexts.length = 0; + } + }, + + /** + * Resets the internal queue. + * + * @internal + */ + reset: function () { + this._callbacks = null; + this._contexts = null; + }, + + /** + * `PooledClass` looks for this. + */ + destructor: function () { + this.reset(); + } + +}); + +PooledClass.addPoolingTo(CallbackQueue); + +module.exports = CallbackQueue; +},{"161":161,"24":24,"25":25}],7:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ChangeEventPlugin + */ + +'use strict'; + +var EventConstants = _dereq_(15); +var EventPluginHub = _dereq_(16); +var EventPropagators = _dereq_(19); +var ExecutionEnvironment = _dereq_(147); +var ReactUpdates = _dereq_(96); +var SyntheticEvent = _dereq_(105); + +var getEventTarget = _dereq_(128); +var isEventSupported = _dereq_(133); +var isTextInputElement = _dereq_(134); +var keyOf = _dereq_(166); + +var topLevelTypes = EventConstants.topLevelTypes; + +var eventTypes = { + change: { + phasedRegistrationNames: { + bubbled: keyOf({ onChange: null }), + captured: keyOf({ onChangeCapture: null }) + }, + dependencies: [topLevelTypes.topBlur, topLevelTypes.topChange, topLevelTypes.topClick, topLevelTypes.topFocus, topLevelTypes.topInput, topLevelTypes.topKeyDown, topLevelTypes.topKeyUp, topLevelTypes.topSelectionChange] + } +}; + +/** + * For IE shims + */ +var activeElement = null; +var activeElementID = null; +var activeElementValue = null; +var activeElementValueProp = null; + +/** + * SECTION: handle `change` event + */ +function shouldUseChangeEvent(elem) { + var nodeName = elem.nodeName && elem.nodeName.toLowerCase(); + return nodeName === 'select' || nodeName === 'input' && elem.type === 'file'; +} + +var doesChangeEventBubble = false; +if (ExecutionEnvironment.canUseDOM) { + // See `handleChange` comment below + doesChangeEventBubble = isEventSupported('change') && (!('documentMode' in document) || document.documentMode > 8); +} + +function manualDispatchChangeEvent(nativeEvent) { + var event = SyntheticEvent.getPooled(eventTypes.change, activeElementID, nativeEvent, getEventTarget(nativeEvent)); + EventPropagators.accumulateTwoPhaseDispatches(event); + + // If change and propertychange bubbled, we'd just bind to it like all the + // other events and have it go through ReactBrowserEventEmitter. Since it + // doesn't, we manually listen for the events and so we have to enqueue and + // process the abstract event manually. + // + // Batching is necessary here in order to ensure that all event handlers run + // before the next rerender (including event handlers attached to ancestor + // elements instead of directly on the input). Without this, controlled + // components don't work properly in conjunction with event bubbling because + // the component is rerendered and the value reverted before all the event + // handlers can run. See https://github.com/facebook/react/issues/708. + ReactUpdates.batchedUpdates(runEventInBatch, event); +} + +function runEventInBatch(event) { + EventPluginHub.enqueueEvents(event); + EventPluginHub.processEventQueue(false); +} + +function startWatchingForChangeEventIE8(target, targetID) { + activeElement = target; + activeElementID = targetID; + activeElement.attachEvent('onchange', manualDispatchChangeEvent); +} + +function stopWatchingForChangeEventIE8() { + if (!activeElement) { + return; + } + activeElement.detachEvent('onchange', manualDispatchChangeEvent); + activeElement = null; + activeElementID = null; +} + +function getTargetIDForChangeEvent(topLevelType, topLevelTarget, topLevelTargetID) { + if (topLevelType === topLevelTypes.topChange) { + return topLevelTargetID; + } +} +function handleEventsForChangeEventIE8(topLevelType, topLevelTarget, topLevelTargetID) { + if (topLevelType === topLevelTypes.topFocus) { + // stopWatching() should be a noop here but we call it just in case we + // missed a blur event somehow. + stopWatchingForChangeEventIE8(); + startWatchingForChangeEventIE8(topLevelTarget, topLevelTargetID); + } else if (topLevelType === topLevelTypes.topBlur) { + stopWatchingForChangeEventIE8(); + } +} + +/** + * SECTION: handle `input` event + */ +var isInputEventSupported = false; +if (ExecutionEnvironment.canUseDOM) { + // IE9 claims to support the input event but fails to trigger it when + // deleting text, so we ignore its input events + isInputEventSupported = isEventSupported('input') && (!('documentMode' in document) || document.documentMode > 9); +} + +/** + * (For old IE.) Replacement getter/setter for the `value` property that gets + * set on the active element. + */ +var newValueProp = { + get: function () { + return activeElementValueProp.get.call(this); + }, + set: function (val) { + // Cast to a string so we can do equality checks. + activeElementValue = '' + val; + activeElementValueProp.set.call(this, val); + } +}; + +/** + * (For old IE.) Starts tracking propertychange events on the passed-in element + * and override the value property so that we can distinguish user events from + * value changes in JS. + */ +function startWatchingForValueChange(target, targetID) { + activeElement = target; + activeElementID = targetID; + activeElementValue = target.value; + activeElementValueProp = Object.getOwnPropertyDescriptor(target.constructor.prototype, 'value'); + + // Not guarded in a canDefineProperty check: IE8 supports defineProperty only + // on DOM elements + Object.defineProperty(activeElement, 'value', newValueProp); + activeElement.attachEvent('onpropertychange', handlePropertyChange); +} + +/** + * (For old IE.) Removes the event listeners from the currently-tracked element, + * if any exists. + */ +function stopWatchingForValueChange() { + if (!activeElement) { + return; + } + + // delete restores the original property definition + delete activeElement.value; + activeElement.detachEvent('onpropertychange', handlePropertyChange); + + activeElement = null; + activeElementID = null; + activeElementValue = null; + activeElementValueProp = null; +} + +/** + * (For old IE.) Handles a propertychange event, sending a `change` event if + * the value of the active element has changed. + */ +function handlePropertyChange(nativeEvent) { + if (nativeEvent.propertyName !== 'value') { + return; + } + var value = nativeEvent.srcElement.value; + if (value === activeElementValue) { + return; + } + activeElementValue = value; + + manualDispatchChangeEvent(nativeEvent); +} + +/** + * If a `change` event should be fired, returns the target's ID. + */ +function getTargetIDForInputEvent(topLevelType, topLevelTarget, topLevelTargetID) { + if (topLevelType === topLevelTypes.topInput) { + // In modern browsers (i.e., not IE8 or IE9), the input event is exactly + // what we want so fall through here and trigger an abstract event + return topLevelTargetID; + } +} + +// For IE8 and IE9. +function handleEventsForInputEventIE(topLevelType, topLevelTarget, topLevelTargetID) { + if (topLevelType === topLevelTypes.topFocus) { + // In IE8, we can capture almost all .value changes by adding a + // propertychange handler and looking for events with propertyName + // equal to 'value' + // In IE9, propertychange fires for most input events but is buggy and + // doesn't fire when text is deleted, but conveniently, selectionchange + // appears to fire in all of the remaining cases so we catch those and + // forward the event if the value has changed + // In either case, we don't want to call the event handler if the value + // is changed from JS so we redefine a setter for `.value` that updates + // our activeElementValue variable, allowing us to ignore those changes + // + // stopWatching() should be a noop here but we call it just in case we + // missed a blur event somehow. + stopWatchingForValueChange(); + startWatchingForValueChange(topLevelTarget, topLevelTargetID); + } else if (topLevelType === topLevelTypes.topBlur) { + stopWatchingForValueChange(); + } +} + +// For IE8 and IE9. +function getTargetIDForInputEventIE(topLevelType, topLevelTarget, topLevelTargetID) { + if (topLevelType === topLevelTypes.topSelectionChange || topLevelType === topLevelTypes.topKeyUp || topLevelType === topLevelTypes.topKeyDown) { + // On the selectionchange event, the target is just document which isn't + // helpful for us so just check activeElement instead. + // + // 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire + // propertychange on the first input event after setting `value` from a + // script and fires only keydown, keypress, keyup. Catching keyup usually + // gets it and catching keydown lets us fire an event for the first + // keystroke if user does a key repeat (it'll be a little delayed: right + // before the second keystroke). Other input methods (e.g., paste) seem to + // fire selectionchange normally. + if (activeElement && activeElement.value !== activeElementValue) { + activeElementValue = activeElement.value; + return activeElementID; + } + } +} + +/** + * SECTION: handle `click` event + */ +function shouldUseClickEvent(elem) { + // Use the `click` event to detect changes to checkbox and radio inputs. + // This approach works across all browsers, whereas `change` does not fire + // until `blur` in IE8. + return elem.nodeName && elem.nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio'); +} + +function getTargetIDForClickEvent(topLevelType, topLevelTarget, topLevelTargetID) { + if (topLevelType === topLevelTypes.topClick) { + return topLevelTargetID; + } +} + +/** + * This plugin creates an `onChange` event that normalizes change events + * across form elements. This event fires at a time when it's possible to + * change the element's value without seeing a flicker. + * + * Supported elements are: + * - input (see `isTextInputElement`) + * - textarea + * - select + */ +var ChangeEventPlugin = { + + eventTypes: eventTypes, + + /** + * @param {string} topLevelType Record from `EventConstants`. + * @param {DOMEventTarget} topLevelTarget The listening component root node. + * @param {string} topLevelTargetID ID of `topLevelTarget`. + * @param {object} nativeEvent Native browser event. + * @return {*} An accumulation of synthetic events. + * @see {EventPluginHub.extractEvents} + */ + extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) { + + var getTargetIDFunc, handleEventFunc; + if (shouldUseChangeEvent(topLevelTarget)) { + if (doesChangeEventBubble) { + getTargetIDFunc = getTargetIDForChangeEvent; + } else { + handleEventFunc = handleEventsForChangeEventIE8; + } + } else if (isTextInputElement(topLevelTarget)) { + if (isInputEventSupported) { + getTargetIDFunc = getTargetIDForInputEvent; + } else { + getTargetIDFunc = getTargetIDForInputEventIE; + handleEventFunc = handleEventsForInputEventIE; + } + } else if (shouldUseClickEvent(topLevelTarget)) { + getTargetIDFunc = getTargetIDForClickEvent; + } + + if (getTargetIDFunc) { + var targetID = getTargetIDFunc(topLevelType, topLevelTarget, topLevelTargetID); + if (targetID) { + var event = SyntheticEvent.getPooled(eventTypes.change, targetID, nativeEvent, nativeEventTarget); + event.type = 'change'; + EventPropagators.accumulateTwoPhaseDispatches(event); + return event; + } + } + + if (handleEventFunc) { + handleEventFunc(topLevelType, topLevelTarget, topLevelTargetID); + } + } + +}; + +module.exports = ChangeEventPlugin; +},{"105":105,"128":128,"133":133,"134":134,"147":147,"15":15,"16":16,"166":166,"19":19,"96":96}],8:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ClientReactRootIndex + * @typechecks + */ + +'use strict'; + +var nextReactRootIndex = 0; + +var ClientReactRootIndex = { + createReactRootIndex: function () { + return nextReactRootIndex++; + } +}; + +module.exports = ClientReactRootIndex; +},{}],9:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule DOMChildrenOperations + * @typechecks static-only + */ + +'use strict'; + +var Danger = _dereq_(12); +var ReactMultiChildUpdateTypes = _dereq_(74); +var ReactPerf = _dereq_(78); + +var setInnerHTML = _dereq_(138); +var setTextContent = _dereq_(139); +var invariant = _dereq_(161); + +/** + * Inserts `childNode` as a child of `parentNode` at the `index`. + * + * @param {DOMElement} parentNode Parent node in which to insert. + * @param {DOMElement} childNode Child node to insert. + * @param {number} index Index at which to insert the child. + * @internal + */ +function insertChildAt(parentNode, childNode, index) { + // By exploiting arrays returning `undefined` for an undefined index, we can + // rely exclusively on `insertBefore(node, null)` instead of also using + // `appendChild(node)`. However, using `undefined` is not allowed by all + // browsers so we must replace it with `null`. + + // fix render order error in safari + // IE8 will throw error when index out of list size. + var beforeChild = index >= parentNode.childNodes.length ? null : parentNode.childNodes.item(index); + + parentNode.insertBefore(childNode, beforeChild); +} + +/** + * Operations for updating with DOM children. + */ +var DOMChildrenOperations = { + + dangerouslyReplaceNodeWithMarkup: Danger.dangerouslyReplaceNodeWithMarkup, + + updateTextContent: setTextContent, + + /** + * Updates a component's children by processing a series of updates. The + * update configurations are each expected to have a `parentNode` property. + * + * @param {array<object>} updates List of update configurations. + * @param {array<string>} markupList List of markup strings. + * @internal + */ + processUpdates: function (updates, markupList) { + var update; + // Mapping from parent IDs to initial child orderings. + var initialChildren = null; + // List of children that will be moved or removed. + var updatedChildren = null; + + for (var i = 0; i < updates.length; i++) { + update = updates[i]; + if (update.type === ReactMultiChildUpdateTypes.MOVE_EXISTING || update.type === ReactMultiChildUpdateTypes.REMOVE_NODE) { + var updatedIndex = update.fromIndex; + var updatedChild = update.parentNode.childNodes[updatedIndex]; + var parentID = update.parentID; + + !updatedChild ? "development" !== 'production' ? invariant(false, 'processUpdates(): Unable to find child %s of element. This ' + 'probably means the DOM was unexpectedly mutated (e.g., by the ' + 'browser), usually due to forgetting a <tbody> when using tables, ' + 'nesting tags like <form>, <p>, or <a>, or using non-SVG elements ' + 'in an <svg> parent. Try inspecting the child nodes of the element ' + 'with React ID `%s`.', updatedIndex, parentID) : invariant(false) : undefined; + + initialChildren = initialChildren || {}; + initialChildren[parentID] = initialChildren[parentID] || []; + initialChildren[parentID][updatedIndex] = updatedChild; + + updatedChildren = updatedChildren || []; + updatedChildren.push(updatedChild); + } + } + + var renderedMarkup; + // markupList is either a list of markup or just a list of elements + if (markupList.length && typeof markupList[0] === 'string') { + renderedMarkup = Danger.dangerouslyRenderMarkup(markupList); + } else { + renderedMarkup = markupList; + } + + // Remove updated children first so that `toIndex` is consistent. + if (updatedChildren) { + for (var j = 0; j < updatedChildren.length; j++) { + updatedChildren[j].parentNode.removeChild(updatedChildren[j]); + } + } + + for (var k = 0; k < updates.length; k++) { + update = updates[k]; + switch (update.type) { + case ReactMultiChildUpdateTypes.INSERT_MARKUP: + insertChildAt(update.parentNode, renderedMarkup[update.markupIndex], update.toIndex); + break; + case ReactMultiChildUpdateTypes.MOVE_EXISTING: + insertChildAt(update.parentNode, initialChildren[update.parentID][update.fromIndex], update.toIndex); + break; + case ReactMultiChildUpdateTypes.SET_MARKUP: + setInnerHTML(update.parentNode, update.content); + break; + case ReactMultiChildUpdateTypes.TEXT_CONTENT: + setTextContent(update.parentNode, update.content); + break; + case ReactMultiChildUpdateTypes.REMOVE_NODE: + // Already removed by the for-loop above. + break; + } + } + } + +}; + +ReactPerf.measureMethods(DOMChildrenOperations, 'DOMChildrenOperations', { + updateTextContent: 'updateTextContent' +}); + +module.exports = DOMChildrenOperations; +},{"12":12,"138":138,"139":139,"161":161,"74":74,"78":78}],10:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule DOMProperty + * @typechecks static-only + */ + +'use strict'; + +var invariant = _dereq_(161); + +function checkMask(value, bitmask) { + return (value & bitmask) === bitmask; +} + +var DOMPropertyInjection = { + /** + * Mapping from normalized, camelcased property names to a configuration that + * specifies how the associated DOM property should be accessed or rendered. + */ + MUST_USE_ATTRIBUTE: 0x1, + MUST_USE_PROPERTY: 0x2, + HAS_SIDE_EFFECTS: 0x4, + HAS_BOOLEAN_VALUE: 0x8, + HAS_NUMERIC_VALUE: 0x10, + HAS_POSITIVE_NUMERIC_VALUE: 0x20 | 0x10, + HAS_OVERLOADED_BOOLEAN_VALUE: 0x40, + + /** + * Inject some specialized knowledge about the DOM. This takes a config object + * with the following properties: + * + * isCustomAttribute: function that given an attribute name will return true + * if it can be inserted into the DOM verbatim. Useful for data-* or aria-* + * attributes where it's impossible to enumerate all of the possible + * attribute names, + * + * Properties: object mapping DOM property name to one of the + * DOMPropertyInjection constants or null. If your attribute isn't in here, + * it won't get written to the DOM. + * + * DOMAttributeNames: object mapping React attribute name to the DOM + * attribute name. Attribute names not specified use the **lowercase** + * normalized name. + * + * DOMAttributeNamespaces: object mapping React attribute name to the DOM + * attribute namespace URL. (Attribute names not specified use no namespace.) + * + * DOMPropertyNames: similar to DOMAttributeNames but for DOM properties. + * Property names not specified use the normalized name. + * + * DOMMutationMethods: Properties that require special mutation methods. If + * `value` is undefined, the mutation method should unset the property. + * + * @param {object} domPropertyConfig the config as described above. + */ + injectDOMPropertyConfig: function (domPropertyConfig) { + var Injection = DOMPropertyInjection; + var Properties = domPropertyConfig.Properties || {}; + var DOMAttributeNamespaces = domPropertyConfig.DOMAttributeNamespaces || {}; + var DOMAttributeNames = domPropertyConfig.DOMAttributeNames || {}; + var DOMPropertyNames = domPropertyConfig.DOMPropertyNames || {}; + var DOMMutationMethods = domPropertyConfig.DOMMutationMethods || {}; + + if (domPropertyConfig.isCustomAttribute) { + DOMProperty._isCustomAttributeFunctions.push(domPropertyConfig.isCustomAttribute); + } + + for (var propName in Properties) { + !!DOMProperty.properties.hasOwnProperty(propName) ? "development" !== 'production' ? invariant(false, 'injectDOMPropertyConfig(...): You\'re trying to inject DOM property ' + '\'%s\' which has already been injected. You may be accidentally ' + 'injecting the same DOM property config twice, or you may be ' + 'injecting two configs that have conflicting property names.', propName) : invariant(false) : undefined; + + var lowerCased = propName.toLowerCase(); + var propConfig = Properties[propName]; + + var propertyInfo = { + attributeName: lowerCased, + attributeNamespace: null, + propertyName: propName, + mutationMethod: null, + + mustUseAttribute: checkMask(propConfig, Injection.MUST_USE_ATTRIBUTE), + mustUseProperty: checkMask(propConfig, Injection.MUST_USE_PROPERTY), + hasSideEffects: checkMask(propConfig, Injection.HAS_SIDE_EFFECTS), + hasBooleanValue: checkMask(propConfig, Injection.HAS_BOOLEAN_VALUE), + hasNumericValue: checkMask(propConfig, Injection.HAS_NUMERIC_VALUE), + hasPositiveNumericValue: checkMask(propConfig, Injection.HAS_POSITIVE_NUMERIC_VALUE), + hasOverloadedBooleanValue: checkMask(propConfig, Injection.HAS_OVERLOADED_BOOLEAN_VALUE) + }; + + !(!propertyInfo.mustUseAttribute || !propertyInfo.mustUseProperty) ? "development" !== 'production' ? invariant(false, 'DOMProperty: Cannot require using both attribute and property: %s', propName) : invariant(false) : undefined; + !(propertyInfo.mustUseProperty || !propertyInfo.hasSideEffects) ? "development" !== 'production' ? invariant(false, 'DOMProperty: Properties that have side effects must use property: %s', propName) : invariant(false) : undefined; + !(propertyInfo.hasBooleanValue + propertyInfo.hasNumericValue + propertyInfo.hasOverloadedBooleanValue <= 1) ? "development" !== 'production' ? invariant(false, 'DOMProperty: Value can be one of boolean, overloaded boolean, or ' + 'numeric value, but not a combination: %s', propName) : invariant(false) : undefined; + + if ("development" !== 'production') { + DOMProperty.getPossibleStandardName[lowerCased] = propName; + } + + if (DOMAttributeNames.hasOwnProperty(propName)) { + var attributeName = DOMAttributeNames[propName]; + propertyInfo.attributeName = attributeName; + if ("development" !== 'production') { + DOMProperty.getPossibleStandardName[attributeName] = propName; + } + } + + if (DOMAttributeNamespaces.hasOwnProperty(propName)) { + propertyInfo.attributeNamespace = DOMAttributeNamespaces[propName]; + } + + if (DOMPropertyNames.hasOwnProperty(propName)) { + propertyInfo.propertyName = DOMPropertyNames[propName]; + } + + if (DOMMutationMethods.hasOwnProperty(propName)) { + propertyInfo.mutationMethod = DOMMutationMethods[propName]; + } + + DOMProperty.properties[propName] = propertyInfo; + } + } +}; +var defaultValueCache = {}; + +/** + * DOMProperty exports lookup objects that can be used like functions: + * + * > DOMProperty.isValid['id'] + * true + * > DOMProperty.isValid['foobar'] + * undefined + * + * Although this may be confusing, it performs better in general. + * + * @see http://jsperf.com/key-exists + * @see http://jsperf.com/key-missing + */ +var DOMProperty = { + + ID_ATTRIBUTE_NAME: 'data-reactid', + + /** + * Map from property "standard name" to an object with info about how to set + * the property in the DOM. Each object contains: + * + * attributeName: + * Used when rendering markup or with `*Attribute()`. + * attributeNamespace + * propertyName: + * Used on DOM node instances. (This includes properties that mutate due to + * external factors.) + * mutationMethod: + * If non-null, used instead of the property or `setAttribute()` after + * initial render. + * mustUseAttribute: + * Whether the property must be accessed and mutated using `*Attribute()`. + * (This includes anything that fails `<propName> in <element>`.) + * mustUseProperty: + * Whether the property must be accessed and mutated as an object property. + * hasSideEffects: + * Whether or not setting a value causes side effects such as triggering + * resources to be loaded or text selection changes. If true, we read from + * the DOM before updating to ensure that the value is only set if it has + * changed. + * hasBooleanValue: + * Whether the property should be removed when set to a falsey value. + * hasNumericValue: + * Whether the property must be numeric or parse as a numeric and should be + * removed when set to a falsey value. + * hasPositiveNumericValue: + * Whether the property must be positive numeric or parse as a positive + * numeric and should be removed when set to a falsey value. + * hasOverloadedBooleanValue: + * Whether the property can be used as a flag as well as with a value. + * Removed when strictly equal to false; present without a value when + * strictly equal to true; present with a value otherwise. + */ + properties: {}, + + /** + * Mapping from lowercase property names to the properly cased version, used + * to warn in the case of missing properties. Available only in __DEV__. + * @type {Object} + */ + getPossibleStandardName: "development" !== 'production' ? {} : null, + + /** + * All of the isCustomAttribute() functions that have been injected. + */ + _isCustomAttributeFunctions: [], + + /** + * Checks whether a property name is a custom attribute. + * @method + */ + isCustomAttribute: function (attributeName) { + for (var i = 0; i < DOMProperty._isCustomAttributeFunctions.length; i++) { + var isCustomAttributeFn = DOMProperty._isCustomAttributeFunctions[i]; + if (isCustomAttributeFn(attributeName)) { + return true; + } + } + return false; + }, + + /** + * Returns the default property value for a DOM property (i.e., not an + * attribute). Most default values are '' or false, but not all. Worse yet, + * some (in particular, `type`) vary depending on the type of element. + * + * TODO: Is it better to grab all the possible properties when creating an + * element to avoid having to create the same element twice? + */ + getDefaultValueForProperty: function (nodeName, prop) { + var nodeDefaults = defaultValueCache[nodeName]; + var testElement; + if (!nodeDefaults) { + defaultValueCache[nodeName] = nodeDefaults = {}; + } + if (!(prop in nodeDefaults)) { + testElement = document.createElementNS('http://www.w3.org/1999/xhtml', nodeName); + nodeDefaults[prop] = testElement[prop]; + } + return nodeDefaults[prop]; + }, + + injection: DOMPropertyInjection +}; + +module.exports = DOMProperty; +},{"161":161}],11:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule DOMPropertyOperations + * @typechecks static-only + */ + +'use strict'; + +var DOMProperty = _dereq_(10); +var ReactPerf = _dereq_(78); + +var quoteAttributeValueForBrowser = _dereq_(136); +var warning = _dereq_(173); + +// Simplified subset +var VALID_ATTRIBUTE_NAME_REGEX = /^[a-zA-Z_][\w\.\-]*$/; +var illegalAttributeNameCache = {}; +var validatedAttributeNameCache = {}; + +function isAttributeNameSafe(attributeName) { + if (validatedAttributeNameCache.hasOwnProperty(attributeName)) { + return true; + } + if (illegalAttributeNameCache.hasOwnProperty(attributeName)) { + return false; + } + if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) { + validatedAttributeNameCache[attributeName] = true; + return true; + } + illegalAttributeNameCache[attributeName] = true; + "development" !== 'production' ? warning(false, 'Invalid attribute name: `%s`', attributeName) : undefined; + return false; +} + +function shouldIgnoreValue(propertyInfo, value) { + return value == null || propertyInfo.hasBooleanValue && !value || propertyInfo.hasNumericValue && isNaN(value) || propertyInfo.hasPositiveNumericValue && value < 1 || propertyInfo.hasOverloadedBooleanValue && value === false; +} + +if ("development" !== 'production') { + var reactProps = { + children: true, + dangerouslySetInnerHTML: true, + key: true, + ref: true + }; + var warnedProperties = {}; + + var warnUnknownProperty = function (name) { + if (reactProps.hasOwnProperty(name) && reactProps[name] || warnedProperties.hasOwnProperty(name) && warnedProperties[name]) { + return; + } + + warnedProperties[name] = true; + var lowerCasedName = name.toLowerCase(); + + // data-* attributes should be lowercase; suggest the lowercase version + var standardName = DOMProperty.isCustomAttribute(lowerCasedName) ? lowerCasedName : DOMProperty.getPossibleStandardName.hasOwnProperty(lowerCasedName) ? DOMProperty.getPossibleStandardName[lowerCasedName] : null; + + // For now, only warn when we have a suggested correction. This prevents + // logging too much when using transferPropsTo. + "development" !== 'production' ? warning(standardName == null, 'Unknown DOM property %s. Did you mean %s?', name, standardName) : undefined; + }; +} + +/** + * Operations for dealing with DOM properties. + */ +var DOMPropertyOperations = { + + /** + * Creates markup for the ID property. + * + * @param {string} id Unescaped ID. + * @return {string} Markup string. + */ + createMarkupForID: function (id) { + return DOMProperty.ID_ATTRIBUTE_NAME + '=' + quoteAttributeValueForBrowser(id); + }, + + setAttributeForID: function (node, id) { + node.setAttribute(DOMProperty.ID_ATTRIBUTE_NAME, id); + }, + + /** + * Creates markup for a property. + * + * @param {string} name + * @param {*} value + * @return {?string} Markup string, or null if the property was invalid. + */ + createMarkupForProperty: function (name, value) { + var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null; + if (propertyInfo) { + if (shouldIgnoreValue(propertyInfo, value)) { + return ''; + } + var attributeName = propertyInfo.attributeName; + if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) { + return attributeName + '=""'; + } + return attributeName + '=' + quoteAttributeValueForBrowser(value); + } else if (DOMProperty.isCustomAttribute(name)) { + if (value == null) { + return ''; + } + return name + '=' + quoteAttributeValueForBrowser(value); + } else if ("development" !== 'production') { + warnUnknownProperty(name); + } + return null; + }, + + /** + * Creates markup for a custom property. + * + * @param {string} name + * @param {*} value + * @return {string} Markup string, or empty string if the property was invalid. + */ + createMarkupForCustomAttribute: function (name, value) { + if (!isAttributeNameSafe(name) || value == null) { + return ''; + } + return name + '=' + quoteAttributeValueForBrowser(value); + }, + + /** + * Sets the value for a property on a node. + * + * @param {DOMElement} node + * @param {string} name + * @param {*} value + */ + setValueForProperty: function (node, name, value) { + var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null; + if (propertyInfo) { + var mutationMethod = propertyInfo.mutationMethod; + if (mutationMethod) { + mutationMethod(node, value); + } else if (shouldIgnoreValue(propertyInfo, value)) { + this.deleteValueForProperty(node, name); + } else if (propertyInfo.mustUseAttribute) { + var attributeName = propertyInfo.attributeName; + var namespace = propertyInfo.attributeNamespace; + // `setAttribute` with objects becomes only `[object]` in IE8/9, + // ('' + value) makes it output the correct toString()-value. + if (namespace) { + node.setAttributeNS(namespace, attributeName, '' + value); + } else if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) { + node.setAttribute(attributeName, ''); + } else { + node.setAttribute(attributeName, '' + value); + } + } else { + var propName = propertyInfo.propertyName; + // Must explicitly cast values for HAS_SIDE_EFFECTS-properties to the + // property type before comparing; only `value` does and is string. + if (!propertyInfo.hasSideEffects || '' + node[propName] !== '' + value) { + // Contrary to `setAttribute`, object properties are properly + // `toString`ed by IE8/9. + node[propName] = value; + } + } + } else if (DOMProperty.isCustomAttribute(name)) { + DOMPropertyOperations.setValueForAttribute(node, name, value); + } else if ("development" !== 'production') { + warnUnknownProperty(name); + } + }, + + setValueForAttribute: function (node, name, value) { + if (!isAttributeNameSafe(name)) { + return; + } + if (value == null) { + node.removeAttribute(name); + } else { + node.setAttribute(name, '' + value); + } + }, + + /** + * Deletes the value for a property on a node. + * + * @param {DOMElement} node + * @param {string} name + */ + deleteValueForProperty: function (node, name) { + var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null; + if (propertyInfo) { + var mutationMethod = propertyInfo.mutationMethod; + if (mutationMethod) { + mutationMethod(node, undefined); + } else if (propertyInfo.mustUseAttribute) { + node.removeAttribute(propertyInfo.attributeName); + } else { + var propName = propertyInfo.propertyName; + var defaultValue = DOMProperty.getDefaultValueForProperty(node.nodeName, propName); + if (!propertyInfo.hasSideEffects || '' + node[propName] !== defaultValue) { + node[propName] = defaultValue; + } + } + } else if (DOMProperty.isCustomAttribute(name)) { + node.removeAttribute(name); + } else if ("development" !== 'production') { + warnUnknownProperty(name); + } + } + +}; + +ReactPerf.measureMethods(DOMPropertyOperations, 'DOMPropertyOperations', { + setValueForProperty: 'setValueForProperty', + setValueForAttribute: 'setValueForAttribute', + deleteValueForProperty: 'deleteValueForProperty' +}); + +module.exports = DOMPropertyOperations; +},{"10":10,"136":136,"173":173,"78":78}],12:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule Danger + * @typechecks static-only + */ + +'use strict'; + +var ExecutionEnvironment = _dereq_(147); + +var createNodesFromMarkup = _dereq_(152); +var emptyFunction = _dereq_(153); +var getMarkupWrap = _dereq_(157); +var invariant = _dereq_(161); + +var OPEN_TAG_NAME_EXP = /^(<[^ \/>]+)/; +var RESULT_INDEX_ATTR = 'data-danger-index'; + +/** + * Extracts the `nodeName` from a string of markup. + * + * NOTE: Extracting the `nodeName` does not require a regular expression match + * because we make assumptions about React-generated markup (i.e. there are no + * spaces surrounding the opening tag and there is at least one attribute). + * + * @param {string} markup String of markup. + * @return {string} Node name of the supplied markup. + * @see http://jsperf.com/extract-nodename + */ +function getNodeName(markup) { + return markup.substring(1, markup.indexOf(' ')); +} + +var Danger = { + + /** + * Renders markup into an array of nodes. The markup is expected to render + * into a list of root nodes. Also, the length of `resultList` and + * `markupList` should be the same. + * + * @param {array<string>} markupList List of markup strings to render. + * @return {array<DOMElement>} List of rendered nodes. + * @internal + */ + dangerouslyRenderMarkup: function (markupList) { + !ExecutionEnvironment.canUseDOM ? "development" !== 'production' ? invariant(false, 'dangerouslyRenderMarkup(...): Cannot render markup in a worker ' + 'thread. Make sure `window` and `document` are available globally ' + 'before requiring React when unit testing or use ' + 'ReactDOMServer.renderToString for server rendering.') : invariant(false) : undefined; + var nodeName; + var markupByNodeName = {}; + // Group markup by `nodeName` if a wrap is necessary, else by '*'. + for (var i = 0; i < markupList.length; i++) { + !markupList[i] ? "development" !== 'production' ? invariant(false, 'dangerouslyRenderMarkup(...): Missing markup.') : invariant(false) : undefined; + nodeName = getNodeName(markupList[i]); + nodeName = getMarkupWrap(nodeName) ? nodeName : '*'; + markupByNodeName[nodeName] = markupByNodeName[nodeName] || []; + markupByNodeName[nodeName][i] = markupList[i]; + } + var resultList = []; + var resultListAssignmentCount = 0; + for (nodeName in markupByNodeName) { + if (!markupByNodeName.hasOwnProperty(nodeName)) { + continue; + } + var markupListByNodeName = markupByNodeName[nodeName]; + + // This for-in loop skips the holes of the sparse array. The order of + // iteration should follow the order of assignment, which happens to match + // numerical index order, but we don't rely on that. + var resultIndex; + for (resultIndex in markupListByNodeName) { + if (markupListByNodeName.hasOwnProperty(resultIndex)) { + var markup = markupListByNodeName[resultIndex]; + + // Push the requested markup with an additional RESULT_INDEX_ATTR + // attribute. If the markup does not start with a < character, it + // will be discarded below (with an appropriate console.error). + markupListByNodeName[resultIndex] = markup.replace(OPEN_TAG_NAME_EXP, + // This index will be parsed back out below. + '$1 ' + RESULT_INDEX_ATTR + '="' + resultIndex + '" '); + } + } + + // Render each group of markup with similar wrapping `nodeName`. + var renderNodes = createNodesFromMarkup(markupListByNodeName.join(''), emptyFunction // Do nothing special with <script> tags. + ); + + for (var j = 0; j < renderNodes.length; ++j) { + var renderNode = renderNodes[j]; + if (renderNode.hasAttribute && renderNode.hasAttribute(RESULT_INDEX_ATTR)) { + + resultIndex = +renderNode.getAttribute(RESULT_INDEX_ATTR); + renderNode.removeAttribute(RESULT_INDEX_ATTR); + + !!resultList.hasOwnProperty(resultIndex) ? "development" !== 'production' ? invariant(false, 'Danger: Assigning to an already-occupied result index.') : invariant(false) : undefined; + + resultList[resultIndex] = renderNode; + + // This should match resultList.length and markupList.length when + // we're done. + resultListAssignmentCount += 1; + } else if ("development" !== 'production') { + console.error('Danger: Discarding unexpected node:', renderNode); + } + } + } + + // Although resultList was populated out of order, it should now be a dense + // array. + !(resultListAssignmentCount === resultList.length) ? "development" !== 'production' ? invariant(false, 'Danger: Did not assign to every index of resultList.') : invariant(false) : undefined; + + !(resultList.length === markupList.length) ? "development" !== 'production' ? invariant(false, 'Danger: Expected markup to render %s nodes, but rendered %s.', markupList.length, resultList.length) : invariant(false) : undefined; + + return resultList; + }, + + /** + * Replaces a node with a string of markup at its current position within its + * parent. The markup must render into a single root node. + * + * @param {DOMElement} oldChild Child node to replace. + * @param {string} markup Markup to render in place of the child node. + * @internal + */ + dangerouslyReplaceNodeWithMarkup: function (oldChild, markup) { + !ExecutionEnvironment.canUseDOM ? "development" !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Cannot render markup in a ' + 'worker thread. Make sure `window` and `document` are available ' + 'globally before requiring React when unit testing or use ' + 'ReactDOMServer.renderToString() for server rendering.') : invariant(false) : undefined; + !markup ? "development" !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Missing markup.') : invariant(false) : undefined; + !(oldChild.tagName.toLowerCase() !== 'html') ? "development" !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Cannot replace markup of the ' + '<html> node. This is because browser quirks make this unreliable ' + 'and/or slow. If you want to render to the root you must use ' + 'server rendering. See ReactDOMServer.renderToString().') : invariant(false) : undefined; + + var newChild; + if (typeof markup === 'string') { + newChild = createNodesFromMarkup(markup, emptyFunction)[0]; + } else { + newChild = markup; + } + oldChild.parentNode.replaceChild(newChild, oldChild); + } + +}; + +module.exports = Danger; +},{"147":147,"152":152,"153":153,"157":157,"161":161}],13:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule DefaultEventPluginOrder + */ + +'use strict'; + +var keyOf = _dereq_(166); + +/** + * Module that is injectable into `EventPluginHub`, that specifies a + * deterministic ordering of `EventPlugin`s. A convenient way to reason about + * plugins, without having to package every one of them. This is better than + * having plugins be ordered in the same order that they are injected because + * that ordering would be influenced by the packaging order. + * `ResponderEventPlugin` must occur before `SimpleEventPlugin` so that + * preventing default on events is convenient in `SimpleEventPlugin` handlers. + */ +var DefaultEventPluginOrder = [keyOf({ ResponderEventPlugin: null }), keyOf({ SimpleEventPlugin: null }), keyOf({ TapEventPlugin: null }), keyOf({ EnterLeaveEventPlugin: null }), keyOf({ ChangeEventPlugin: null }), keyOf({ SelectEventPlugin: null }), keyOf({ BeforeInputEventPlugin: null })]; + +module.exports = DefaultEventPluginOrder; +},{"166":166}],14:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule EnterLeaveEventPlugin + * @typechecks static-only + */ + +'use strict'; + +var EventConstants = _dereq_(15); +var EventPropagators = _dereq_(19); +var SyntheticMouseEvent = _dereq_(109); + +var ReactMount = _dereq_(72); +var keyOf = _dereq_(166); + +var topLevelTypes = EventConstants.topLevelTypes; +var getFirstReactDOM = ReactMount.getFirstReactDOM; + +var eventTypes = { + mouseEnter: { + registrationName: keyOf({ onMouseEnter: null }), + dependencies: [topLevelTypes.topMouseOut, topLevelTypes.topMouseOver] + }, + mouseLeave: { + registrationName: keyOf({ onMouseLeave: null }), + dependencies: [topLevelTypes.topMouseOut, topLevelTypes.topMouseOver] + } +}; + +var extractedEvents = [null, null]; + +var EnterLeaveEventPlugin = { + + eventTypes: eventTypes, + + /** + * For almost every interaction we care about, there will be both a top-level + * `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that + * we do not extract duplicate events. However, moving the mouse into the + * browser from outside will not fire a `mouseout` event. In this case, we use + * the `mouseover` top-level event. + * + * @param {string} topLevelType Record from `EventConstants`. + * @param {DOMEventTarget} topLevelTarget The listening component root node. + * @param {string} topLevelTargetID ID of `topLevelTarget`. + * @param {object} nativeEvent Native browser event. + * @return {*} An accumulation of synthetic events. + * @see {EventPluginHub.extractEvents} + */ + extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) { + if (topLevelType === topLevelTypes.topMouseOver && (nativeEvent.relatedTarget || nativeEvent.fromElement)) { + return null; + } + if (topLevelType !== topLevelTypes.topMouseOut && topLevelType !== topLevelTypes.topMouseOver) { + // Must not be a mouse in or mouse out - ignoring. + return null; + } + + var win; + if (topLevelTarget.window === topLevelTarget) { + // `topLevelTarget` is probably a window object. + win = topLevelTarget; + } else { + // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. + var doc = topLevelTarget.ownerDocument; + if (doc) { + win = doc.defaultView || doc.parentWindow; + } else { + win = window; + } + } + + var from; + var to; + var fromID = ''; + var toID = ''; + if (topLevelType === topLevelTypes.topMouseOut) { + from = topLevelTarget; + fromID = topLevelTargetID; + to = getFirstReactDOM(nativeEvent.relatedTarget || nativeEvent.toElement); + if (to) { + toID = ReactMount.getID(to); + } else { + to = win; + } + to = to || win; + } else { + from = win; + to = topLevelTarget; + toID = topLevelTargetID; + } + + if (from === to) { + // Nothing pertains to our managed components. + return null; + } + + var leave = SyntheticMouseEvent.getPooled(eventTypes.mouseLeave, fromID, nativeEvent, nativeEventTarget); + leave.type = 'mouseleave'; + leave.target = from; + leave.relatedTarget = to; + + var enter = SyntheticMouseEvent.getPooled(eventTypes.mouseEnter, toID, nativeEvent, nativeEventTarget); + enter.type = 'mouseenter'; + enter.target = to; + enter.relatedTarget = from; + + EventPropagators.accumulateEnterLeaveDispatches(leave, enter, fromID, toID); + + extractedEvents[0] = leave; + extractedEvents[1] = enter; + + return extractedEvents; + } + +}; + +module.exports = EnterLeaveEventPlugin; +},{"109":109,"15":15,"166":166,"19":19,"72":72}],15:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule EventConstants + */ + +'use strict'; + +var keyMirror = _dereq_(165); + +var PropagationPhases = keyMirror({ bubbled: null, captured: null }); + +/** + * Types of raw signals from the browser caught at the top level. + */ +var topLevelTypes = keyMirror({ + topAbort: null, + topBlur: null, + topCanPlay: null, + topCanPlayThrough: null, + topChange: null, + topClick: null, + topCompositionEnd: null, + topCompositionStart: null, + topCompositionUpdate: null, + topContextMenu: null, + topCopy: null, + topCut: null, + topDoubleClick: null, + topDrag: null, + topDragEnd: null, + topDragEnter: null, + topDragExit: null, + topDragLeave: null, + topDragOver: null, + topDragStart: null, + topDrop: null, + topDurationChange: null, + topEmptied: null, + topEncrypted: null, + topEnded: null, + topError: null, + topFocus: null, + topInput: null, + topKeyDown: null, + topKeyPress: null, + topKeyUp: null, + topLoad: null, + topLoadedData: null, + topLoadedMetadata: null, + topLoadStart: null, + topMouseDown: null, + topMouseMove: null, + topMouseOut: null, + topMouseOver: null, + topMouseUp: null, + topPaste: null, + topPause: null, + topPlay: null, + topPlaying: null, + topProgress: null, + topRateChange: null, + topReset: null, + topScroll: null, + topSeeked: null, + topSeeking: null, + topSelectionChange: null, + topStalled: null, + topSubmit: null, + topSuspend: null, + topTextInput: null, + topTimeUpdate: null, + topTouchCancel: null, + topTouchEnd: null, + topTouchMove: null, + topTouchStart: null, + topVolumeChange: null, + topWaiting: null, + topWheel: null +}); + +var EventConstants = { + topLevelTypes: topLevelTypes, + PropagationPhases: PropagationPhases +}; + +module.exports = EventConstants; +},{"165":165}],16:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule EventPluginHub + */ + +'use strict'; + +var EventPluginRegistry = _dereq_(17); +var EventPluginUtils = _dereq_(18); +var ReactErrorUtils = _dereq_(61); + +var accumulateInto = _dereq_(115); +var forEachAccumulated = _dereq_(124); +var invariant = _dereq_(161); +var warning = _dereq_(173); + +/** + * Internal store for event listeners + */ +var listenerBank = {}; + +/** + * Internal queue of events that have accumulated their dispatches and are + * waiting to have their dispatches executed. + */ +var eventQueue = null; + +/** + * Dispatches an event and releases it back into the pool, unless persistent. + * + * @param {?object} event Synthetic event to be dispatched. + * @param {boolean} simulated If the event is simulated (changes exn behavior) + * @private + */ +var executeDispatchesAndRelease = function (event, simulated) { + if (event) { + EventPluginUtils.executeDispatchesInOrder(event, simulated); + + if (!event.isPersistent()) { + event.constructor.release(event); + } + } +}; +var executeDispatchesAndReleaseSimulated = function (e) { + return executeDispatchesAndRelease(e, true); +}; +var executeDispatchesAndReleaseTopLevel = function (e) { + return executeDispatchesAndRelease(e, false); +}; + +/** + * - `InstanceHandle`: [required] Module that performs logical traversals of DOM + * hierarchy given ids of the logical DOM elements involved. + */ +var InstanceHandle = null; + +function validateInstanceHandle() { + var valid = InstanceHandle && InstanceHandle.traverseTwoPhase && InstanceHandle.traverseEnterLeave; + "development" !== 'production' ? warning(valid, 'InstanceHandle not injected before use!') : undefined; +} + +/** + * This is a unified interface for event plugins to be installed and configured. + * + * Event plugins can implement the following properties: + * + * `extractEvents` {function(string, DOMEventTarget, string, object): *} + * Required. When a top-level event is fired, this method is expected to + * extract synthetic events that will in turn be queued and dispatched. + * + * `eventTypes` {object} + * Optional, plugins that fire events must publish a mapping of registration + * names that are used to register listeners. Values of this mapping must + * be objects that contain `registrationName` or `phasedRegistrationNames`. + * + * `executeDispatch` {function(object, function, string)} + * Optional, allows plugins to override how an event gets dispatched. By + * default, the listener is simply invoked. + * + * Each plugin that is injected into `EventsPluginHub` is immediately operable. + * + * @public + */ +var EventPluginHub = { + + /** + * Methods for injecting dependencies. + */ + injection: { + + /** + * @param {object} InjectedMount + * @public + */ + injectMount: EventPluginUtils.injection.injectMount, + + /** + * @param {object} InjectedInstanceHandle + * @public + */ + injectInstanceHandle: function (InjectedInstanceHandle) { + InstanceHandle = InjectedInstanceHandle; + if ("development" !== 'production') { + validateInstanceHandle(); + } + }, + + getInstanceHandle: function () { + if ("development" !== 'production') { + validateInstanceHandle(); + } + return InstanceHandle; + }, + + /** + * @param {array} InjectedEventPluginOrder + * @public + */ + injectEventPluginOrder: EventPluginRegistry.injectEventPluginOrder, + + /** + * @param {object} injectedNamesToPlugins Map from names to plugin modules. + */ + injectEventPluginsByName: EventPluginRegistry.injectEventPluginsByName + + }, + + eventNameDispatchConfigs: EventPluginRegistry.eventNameDispatchConfigs, + + registrationNameModules: EventPluginRegistry.registrationNameModules, + + /** + * Stores `listener` at `listenerBank[registrationName][id]`. Is idempotent. + * + * @param {string} id ID of the DOM element. + * @param {string} registrationName Name of listener (e.g. `onClick`). + * @param {?function} listener The callback to store. + */ + putListener: function (id, registrationName, listener) { + !(typeof listener === 'function') ? "development" !== 'production' ? invariant(false, 'Expected %s listener to be a function, instead got type %s', registrationName, typeof listener) : invariant(false) : undefined; + + var bankForRegistrationName = listenerBank[registrationName] || (listenerBank[registrationName] = {}); + bankForRegistrationName[id] = listener; + + var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; + if (PluginModule && PluginModule.didPutListener) { + PluginModule.didPutListener(id, registrationName, listener); + } + }, + + /** + * @param {string} id ID of the DOM element. + * @param {string} registrationName Name of listener (e.g. `onClick`). + * @return {?function} The stored callback. + */ + getListener: function (id, registrationName) { + var bankForRegistrationName = listenerBank[registrationName]; + return bankForRegistrationName && bankForRegistrationName[id]; + }, + + /** + * Deletes a listener from the registration bank. + * + * @param {string} id ID of the DOM element. + * @param {string} registrationName Name of listener (e.g. `onClick`). + */ + deleteListener: function (id, registrationName) { + var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; + if (PluginModule && PluginModule.willDeleteListener) { + PluginModule.willDeleteListener(id, registrationName); + } + + var bankForRegistrationName = listenerBank[registrationName]; + // TODO: This should never be null -- when is it? + if (bankForRegistrationName) { + delete bankForRegistrationName[id]; + } + }, + + /** + * Deletes all listeners for the DOM element with the supplied ID. + * + * @param {string} id ID of the DOM element. + */ + deleteAllListeners: function (id) { + for (var registrationName in listenerBank) { + if (!listenerBank[registrationName][id]) { + continue; + } + + var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; + if (PluginModule && PluginModule.willDeleteListener) { + PluginModule.willDeleteListener(id, registrationName); + } + + delete listenerBank[registrationName][id]; + } + }, + + /** + * Allows registered plugins an opportunity to extract events from top-level + * native browser events. + * + * @param {string} topLevelType Record from `EventConstants`. + * @param {DOMEventTarget} topLevelTarget The listening component root node. + * @param {string} topLevelTargetID ID of `topLevelTarget`. + * @param {object} nativeEvent Native browser event. + * @return {*} An accumulation of synthetic events. + * @internal + */ + extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) { + var events; + var plugins = EventPluginRegistry.plugins; + for (var i = 0; i < plugins.length; i++) { + // Not every plugin in the ordering may be loaded at runtime. + var possiblePlugin = plugins[i]; + if (possiblePlugin) { + var extractedEvents = possiblePlugin.extractEvents(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget); + if (extractedEvents) { + events = accumulateInto(events, extractedEvents); + } + } + } + return events; + }, + + /** + * Enqueues a synthetic event that should be dispatched when + * `processEventQueue` is invoked. + * + * @param {*} events An accumulation of synthetic events. + * @internal + */ + enqueueEvents: function (events) { + if (events) { + eventQueue = accumulateInto(eventQueue, events); + } + }, + + /** + * Dispatches all synthetic events on the event queue. + * + * @internal + */ + processEventQueue: function (simulated) { + // Set `eventQueue` to null before processing it so that we can tell if more + // events get enqueued while processing. + var processingEventQueue = eventQueue; + eventQueue = null; + if (simulated) { + forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseSimulated); + } else { + forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel); + } + !!eventQueue ? "development" !== 'production' ? invariant(false, 'processEventQueue(): Additional events were enqueued while processing ' + 'an event queue. Support for this has not yet been implemented.') : invariant(false) : undefined; + // This would be a good time to rethrow if any of the event handlers threw. + ReactErrorUtils.rethrowCaughtError(); + }, + + /** + * These are needed for tests only. Do not use! + */ + __purge: function () { + listenerBank = {}; + }, + + __getListenerBank: function () { + return listenerBank; + } + +}; + +module.exports = EventPluginHub; +},{"115":115,"124":124,"161":161,"17":17,"173":173,"18":18,"61":61}],17:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule EventPluginRegistry + * @typechecks static-only + */ + +'use strict'; + +var invariant = _dereq_(161); + +/** + * Injectable ordering of event plugins. + */ +var EventPluginOrder = null; + +/** + * Injectable mapping from names to event plugin modules. + */ +var namesToPlugins = {}; + +/** + * Recomputes the plugin list using the injected plugins and plugin ordering. + * + * @private + */ +function recomputePluginOrdering() { + if (!EventPluginOrder) { + // Wait until an `EventPluginOrder` is injected. + return; + } + for (var pluginName in namesToPlugins) { + var PluginModule = namesToPlugins[pluginName]; + var pluginIndex = EventPluginOrder.indexOf(pluginName); + !(pluginIndex > -1) ? "development" !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject event plugins that do not exist in ' + 'the plugin ordering, `%s`.', pluginName) : invariant(false) : undefined; + if (EventPluginRegistry.plugins[pluginIndex]) { + continue; + } + !PluginModule.extractEvents ? "development" !== 'production' ? invariant(false, 'EventPluginRegistry: Event plugins must implement an `extractEvents` ' + 'method, but `%s` does not.', pluginName) : invariant(false) : undefined; + EventPluginRegistry.plugins[pluginIndex] = PluginModule; + var publishedEvents = PluginModule.eventTypes; + for (var eventName in publishedEvents) { + !publishEventForPlugin(publishedEvents[eventName], PluginModule, eventName) ? "development" !== 'production' ? invariant(false, 'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.', eventName, pluginName) : invariant(false) : undefined; + } + } +} + +/** + * Publishes an event so that it can be dispatched by the supplied plugin. + * + * @param {object} dispatchConfig Dispatch configuration for the event. + * @param {object} PluginModule Plugin publishing the event. + * @return {boolean} True if the event was successfully published. + * @private + */ +function publishEventForPlugin(dispatchConfig, PluginModule, eventName) { + !!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName) ? "development" !== 'production' ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same ' + 'event name, `%s`.', eventName) : invariant(false) : undefined; + EventPluginRegistry.eventNameDispatchConfigs[eventName] = dispatchConfig; + + var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; + if (phasedRegistrationNames) { + for (var phaseName in phasedRegistrationNames) { + if (phasedRegistrationNames.hasOwnProperty(phaseName)) { + var phasedRegistrationName = phasedRegistrationNames[phaseName]; + publishRegistrationName(phasedRegistrationName, PluginModule, eventName); + } + } + return true; + } else if (dispatchConfig.registrationName) { + publishRegistrationName(dispatchConfig.registrationName, PluginModule, eventName); + return true; + } + return false; +} + +/** + * Publishes a registration name that is used to identify dispatched events and + * can be used with `EventPluginHub.putListener` to register listeners. + * + * @param {string} registrationName Registration name to add. + * @param {object} PluginModule Plugin publishing the event. + * @private + */ +function publishRegistrationName(registrationName, PluginModule, eventName) { + !!EventPluginRegistry.registrationNameModules[registrationName] ? "development" !== 'production' ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same ' + 'registration name, `%s`.', registrationName) : invariant(false) : undefined; + EventPluginRegistry.registrationNameModules[registrationName] = PluginModule; + EventPluginRegistry.registrationNameDependencies[registrationName] = PluginModule.eventTypes[eventName].dependencies; +} + +/** + * Registers plugins so that they can extract and dispatch events. + * + * @see {EventPluginHub} + */ +var EventPluginRegistry = { + + /** + * Ordered list of injected plugins. + */ + plugins: [], + + /** + * Mapping from event name to dispatch config + */ + eventNameDispatchConfigs: {}, + + /** + * Mapping from registration name to plugin module + */ + registrationNameModules: {}, + + /** + * Mapping from registration name to event name + */ + registrationNameDependencies: {}, + + /** + * Injects an ordering of plugins (by plugin name). This allows the ordering + * to be decoupled from injection of the actual plugins so that ordering is + * always deterministic regardless of packaging, on-the-fly injection, etc. + * + * @param {array} InjectedEventPluginOrder + * @internal + * @see {EventPluginHub.injection.injectEventPluginOrder} + */ + injectEventPluginOrder: function (InjectedEventPluginOrder) { + !!EventPluginOrder ? "development" !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject event plugin ordering more than ' + 'once. You are likely trying to load more than one copy of React.') : invariant(false) : undefined; + // Clone the ordering so it cannot be dynamically mutated. + EventPluginOrder = Array.prototype.slice.call(InjectedEventPluginOrder); + recomputePluginOrdering(); + }, + + /** + * Injects plugins to be used by `EventPluginHub`. The plugin names must be + * in the ordering injected by `injectEventPluginOrder`. + * + * Plugins can be injected as part of page initialization or on-the-fly. + * + * @param {object} injectedNamesToPlugins Map from names to plugin modules. + * @internal + * @see {EventPluginHub.injection.injectEventPluginsByName} + */ + injectEventPluginsByName: function (injectedNamesToPlugins) { + var isOrderingDirty = false; + for (var pluginName in injectedNamesToPlugins) { + if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) { + continue; + } + var PluginModule = injectedNamesToPlugins[pluginName]; + if (!namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== PluginModule) { + !!namesToPlugins[pluginName] ? "development" !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject two different event plugins ' + 'using the same name, `%s`.', pluginName) : invariant(false) : undefined; + namesToPlugins[pluginName] = PluginModule; + isOrderingDirty = true; + } + } + if (isOrderingDirty) { + recomputePluginOrdering(); + } + }, + + /** + * Looks up the plugin for the supplied event. + * + * @param {object} event A synthetic event. + * @return {?object} The plugin that created the supplied event. + * @internal + */ + getPluginModuleForEvent: function (event) { + var dispatchConfig = event.dispatchConfig; + if (dispatchConfig.registrationName) { + return EventPluginRegistry.registrationNameModules[dispatchConfig.registrationName] || null; + } + for (var phase in dispatchConfig.phasedRegistrationNames) { + if (!dispatchConfig.phasedRegistrationNames.hasOwnProperty(phase)) { + continue; + } + var PluginModule = EventPluginRegistry.registrationNameModules[dispatchConfig.phasedRegistrationNames[phase]]; + if (PluginModule) { + return PluginModule; + } + } + return null; + }, + + /** + * Exposed for unit testing. + * @private + */ + _resetEventPlugins: function () { + EventPluginOrder = null; + for (var pluginName in namesToPlugins) { + if (namesToPlugins.hasOwnProperty(pluginName)) { + delete namesToPlugins[pluginName]; + } + } + EventPluginRegistry.plugins.length = 0; + + var eventNameDispatchConfigs = EventPluginRegistry.eventNameDispatchConfigs; + for (var eventName in eventNameDispatchConfigs) { + if (eventNameDispatchConfigs.hasOwnProperty(eventName)) { + delete eventNameDispatchConfigs[eventName]; + } + } + + var registrationNameModules = EventPluginRegistry.registrationNameModules; + for (var registrationName in registrationNameModules) { + if (registrationNameModules.hasOwnProperty(registrationName)) { + delete registrationNameModules[registrationName]; + } + } + } + +}; + +module.exports = EventPluginRegistry; +},{"161":161}],18:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule EventPluginUtils + */ + +'use strict'; + +var EventConstants = _dereq_(15); +var ReactErrorUtils = _dereq_(61); + +var invariant = _dereq_(161); +var warning = _dereq_(173); + +/** + * Injected dependencies: + */ + +/** + * - `Mount`: [required] Module that can convert between React dom IDs and + * actual node references. + */ +var injection = { + Mount: null, + injectMount: function (InjectedMount) { + injection.Mount = InjectedMount; + if ("development" !== 'production') { + "development" !== 'production' ? warning(InjectedMount && InjectedMount.getNode && InjectedMount.getID, 'EventPluginUtils.injection.injectMount(...): Injected Mount ' + 'module is missing getNode or getID.') : undefined; + } + } +}; + +var topLevelTypes = EventConstants.topLevelTypes; + +function isEndish(topLevelType) { + return topLevelType === topLevelTypes.topMouseUp || topLevelType === topLevelTypes.topTouchEnd || topLevelType === topLevelTypes.topTouchCancel; +} + +function isMoveish(topLevelType) { + return topLevelType === topLevelTypes.topMouseMove || topLevelType === topLevelTypes.topTouchMove; +} +function isStartish(topLevelType) { + return topLevelType === topLevelTypes.topMouseDown || topLevelType === topLevelTypes.topTouchStart; +} + +var validateEventDispatches; +if ("development" !== 'production') { + validateEventDispatches = function (event) { + var dispatchListeners = event._dispatchListeners; + var dispatchIDs = event._dispatchIDs; + + var listenersIsArr = Array.isArray(dispatchListeners); + var idsIsArr = Array.isArray(dispatchIDs); + var IDsLen = idsIsArr ? dispatchIDs.length : dispatchIDs ? 1 : 0; + var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0; + + "development" !== 'production' ? warning(idsIsArr === listenersIsArr && IDsLen === listenersLen, 'EventPluginUtils: Invalid `event`.') : undefined; + }; +} + +/** + * Dispatch the event to the listener. + * @param {SyntheticEvent} event SyntheticEvent to handle + * @param {boolean} simulated If the event is simulated (changes exn behavior) + * @param {function} listener Application-level callback + * @param {string} domID DOM id to pass to the callback. + */ +function executeDispatch(event, simulated, listener, domID) { + var type = event.type || 'unknown-event'; + event.currentTarget = injection.Mount.getNode(domID); + if (simulated) { + ReactErrorUtils.invokeGuardedCallbackWithCatch(type, listener, event, domID); + } else { + ReactErrorUtils.invokeGuardedCallback(type, listener, event, domID); + } + event.currentTarget = null; +} + +/** + * Standard/simple iteration through an event's collected dispatches. + */ +function executeDispatchesInOrder(event, simulated) { + var dispatchListeners = event._dispatchListeners; + var dispatchIDs = event._dispatchIDs; + if ("development" !== 'production') { + validateEventDispatches(event); + } + if (Array.isArray(dispatchListeners)) { + for (var i = 0; i < dispatchListeners.length; i++) { + if (event.isPropagationStopped()) { + break; + } + // Listeners and IDs are two parallel arrays that are always in sync. + executeDispatch(event, simulated, dispatchListeners[i], dispatchIDs[i]); + } + } else if (dispatchListeners) { + executeDispatch(event, simulated, dispatchListeners, dispatchIDs); + } + event._dispatchListeners = null; + event._dispatchIDs = null; +} + +/** + * Standard/simple iteration through an event's collected dispatches, but stops + * at the first dispatch execution returning true, and returns that id. + * + * @return {?string} id of the first dispatch execution who's listener returns + * true, or null if no listener returned true. + */ +function executeDispatchesInOrderStopAtTrueImpl(event) { + var dispatchListeners = event._dispatchListeners; + var dispatchIDs = event._dispatchIDs; + if ("development" !== 'production') { + validateEventDispatches(event); + } + if (Array.isArray(dispatchListeners)) { + for (var i = 0; i < dispatchListeners.length; i++) { + if (event.isPropagationStopped()) { + break; + } + // Listeners and IDs are two parallel arrays that are always in sync. + if (dispatchListeners[i](event, dispatchIDs[i])) { + return dispatchIDs[i]; + } + } + } else if (dispatchListeners) { + if (dispatchListeners(event, dispatchIDs)) { + return dispatchIDs; + } + } + return null; +} + +/** + * @see executeDispatchesInOrderStopAtTrueImpl + */ +function executeDispatchesInOrderStopAtTrue(event) { + var ret = executeDispatchesInOrderStopAtTrueImpl(event); + event._dispatchIDs = null; + event._dispatchListeners = null; + return ret; +} + +/** + * Execution of a "direct" dispatch - there must be at most one dispatch + * accumulated on the event or it is considered an error. It doesn't really make + * sense for an event with multiple dispatches (bubbled) to keep track of the + * return values at each dispatch execution, but it does tend to make sense when + * dealing with "direct" dispatches. + * + * @return {*} The return value of executing the single dispatch. + */ +function executeDirectDispatch(event) { + if ("development" !== 'production') { + validateEventDispatches(event); + } + var dispatchListener = event._dispatchListeners; + var dispatchID = event._dispatchIDs; + !!Array.isArray(dispatchListener) ? "development" !== 'production' ? invariant(false, 'executeDirectDispatch(...): Invalid `event`.') : invariant(false) : undefined; + var res = dispatchListener ? dispatchListener(event, dispatchID) : null; + event._dispatchListeners = null; + event._dispatchIDs = null; + return res; +} + +/** + * @param {SyntheticEvent} event + * @return {boolean} True iff number of dispatches accumulated is greater than 0. + */ +function hasDispatches(event) { + return !!event._dispatchListeners; +} + +/** + * General utilities that are useful in creating custom Event Plugins. + */ +var EventPluginUtils = { + isEndish: isEndish, + isMoveish: isMoveish, + isStartish: isStartish, + + executeDirectDispatch: executeDirectDispatch, + executeDispatchesInOrder: executeDispatchesInOrder, + executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue, + hasDispatches: hasDispatches, + + getNode: function (id) { + return injection.Mount.getNode(id); + }, + getID: function (node) { + return injection.Mount.getID(node); + }, + + injection: injection +}; + +module.exports = EventPluginUtils; +},{"15":15,"161":161,"173":173,"61":61}],19:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule EventPropagators + */ + +'use strict'; + +var EventConstants = _dereq_(15); +var EventPluginHub = _dereq_(16); + +var warning = _dereq_(173); + +var accumulateInto = _dereq_(115); +var forEachAccumulated = _dereq_(124); + +var PropagationPhases = EventConstants.PropagationPhases; +var getListener = EventPluginHub.getListener; + +/** + * Some event types have a notion of different registration names for different + * "phases" of propagation. This finds listeners by a given phase. + */ +function listenerAtPhase(id, event, propagationPhase) { + var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase]; + return getListener(id, registrationName); +} + +/** + * Tags a `SyntheticEvent` with dispatched listeners. Creating this function + * here, allows us to not have to bind or create functions for each event. + * Mutating the event's members allows us to not have to create a wrapping + * "dispatch" object that pairs the event with the listener. + */ +function accumulateDirectionalDispatches(domID, upwards, event) { + if ("development" !== 'production') { + "development" !== 'production' ? warning(domID, 'Dispatching id must not be null') : undefined; + } + var phase = upwards ? PropagationPhases.bubbled : PropagationPhases.captured; + var listener = listenerAtPhase(domID, event, phase); + if (listener) { + event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); + event._dispatchIDs = accumulateInto(event._dispatchIDs, domID); + } +} + +/** + * Collect dispatches (must be entirely collected before dispatching - see unit + * tests). Lazily allocate the array to conserve memory. We must loop through + * each event and perform the traversal for each one. We cannot perform a + * single traversal for the entire collection of events because each event may + * have a different target. + */ +function accumulateTwoPhaseDispatchesSingle(event) { + if (event && event.dispatchConfig.phasedRegistrationNames) { + EventPluginHub.injection.getInstanceHandle().traverseTwoPhase(event.dispatchMarker, accumulateDirectionalDispatches, event); + } +} + +/** + * Same as `accumulateTwoPhaseDispatchesSingle`, but skips over the targetID. + */ +function accumulateTwoPhaseDispatchesSingleSkipTarget(event) { + if (event && event.dispatchConfig.phasedRegistrationNames) { + EventPluginHub.injection.getInstanceHandle().traverseTwoPhaseSkipTarget(event.dispatchMarker, accumulateDirectionalDispatches, event); + } +} + +/** + * Accumulates without regard to direction, does not look for phased + * registration names. Same as `accumulateDirectDispatchesSingle` but without + * requiring that the `dispatchMarker` be the same as the dispatched ID. + */ +function accumulateDispatches(id, ignoredDirection, event) { + if (event && event.dispatchConfig.registrationName) { + var registrationName = event.dispatchConfig.registrationName; + var listener = getListener(id, registrationName); + if (listener) { + event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); + event._dispatchIDs = accumulateInto(event._dispatchIDs, id); + } + } +} + +/** + * Accumulates dispatches on an `SyntheticEvent`, but only for the + * `dispatchMarker`. + * @param {SyntheticEvent} event + */ +function accumulateDirectDispatchesSingle(event) { + if (event && event.dispatchConfig.registrationName) { + accumulateDispatches(event.dispatchMarker, null, event); + } +} + +function accumulateTwoPhaseDispatches(events) { + forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle); +} + +function accumulateTwoPhaseDispatchesSkipTarget(events) { + forEachAccumulated(events, accumulateTwoPhaseDispatchesSingleSkipTarget); +} + +function accumulateEnterLeaveDispatches(leave, enter, fromID, toID) { + EventPluginHub.injection.getInstanceHandle().traverseEnterLeave(fromID, toID, accumulateDispatches, leave, enter); +} + +function accumulateDirectDispatches(events) { + forEachAccumulated(events, accumulateDirectDispatchesSingle); +} + +/** + * A small set of propagation patterns, each of which will accept a small amount + * of information, and generate a set of "dispatch ready event objects" - which + * are sets of events that have already been annotated with a set of dispatched + * listener functions/ids. The API is designed this way to discourage these + * propagation strategies from actually executing the dispatches, since we + * always want to collect the entire set of dispatches before executing event a + * single one. + * + * @constructor EventPropagators + */ +var EventPropagators = { + accumulateTwoPhaseDispatches: accumulateTwoPhaseDispatches, + accumulateTwoPhaseDispatchesSkipTarget: accumulateTwoPhaseDispatchesSkipTarget, + accumulateDirectDispatches: accumulateDirectDispatches, + accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches +}; + +module.exports = EventPropagators; +},{"115":115,"124":124,"15":15,"16":16,"173":173}],20:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule FallbackCompositionState + * @typechecks static-only + */ + +'use strict'; + +var PooledClass = _dereq_(25); + +var assign = _dereq_(24); +var getTextContentAccessor = _dereq_(131); + +/** + * This helper class stores information about text content of a target node, + * allowing comparison of content before and after a given event. + * + * Identify the node where selection currently begins, then observe + * both its text content and its current position in the DOM. Since the + * browser may natively replace the target node during composition, we can + * use its position to find its replacement. + * + * @param {DOMEventTarget} root + */ +function FallbackCompositionState(root) { + this._root = root; + this._startText = this.getText(); + this._fallbackText = null; +} + +assign(FallbackCompositionState.prototype, { + destructor: function () { + this._root = null; + this._startText = null; + this._fallbackText = null; + }, + + /** + * Get current text of input. + * + * @return {string} + */ + getText: function () { + if ('value' in this._root) { + return this._root.value; + } + return this._root[getTextContentAccessor()]; + }, + + /** + * Determine the differing substring between the initially stored + * text content and the current content. + * + * @return {string} + */ + getData: function () { + if (this._fallbackText) { + return this._fallbackText; + } + + var start; + var startValue = this._startText; + var startLength = startValue.length; + var end; + var endValue = this.getText(); + var endLength = endValue.length; + + for (start = 0; start < startLength; start++) { + if (startValue[start] !== endValue[start]) { + break; + } + } + + var minEnd = startLength - start; + for (end = 1; end <= minEnd; end++) { + if (startValue[startLength - end] !== endValue[endLength - end]) { + break; + } + } + + var sliceTail = end > 1 ? 1 - end : undefined; + this._fallbackText = endValue.slice(start, sliceTail); + return this._fallbackText; + } +}); + +PooledClass.addPoolingTo(FallbackCompositionState); + +module.exports = FallbackCompositionState; +},{"131":131,"24":24,"25":25}],21:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule HTMLDOMPropertyConfig + */ + +'use strict'; + +var DOMProperty = _dereq_(10); +var ExecutionEnvironment = _dereq_(147); + +var MUST_USE_ATTRIBUTE = DOMProperty.injection.MUST_USE_ATTRIBUTE; +var MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY; +var HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE; +var HAS_SIDE_EFFECTS = DOMProperty.injection.HAS_SIDE_EFFECTS; +var HAS_NUMERIC_VALUE = DOMProperty.injection.HAS_NUMERIC_VALUE; +var HAS_POSITIVE_NUMERIC_VALUE = DOMProperty.injection.HAS_POSITIVE_NUMERIC_VALUE; +var HAS_OVERLOADED_BOOLEAN_VALUE = DOMProperty.injection.HAS_OVERLOADED_BOOLEAN_VALUE; + +var hasSVG; +if (ExecutionEnvironment.canUseDOM) { + var implementation = document.implementation; + hasSVG = implementation && implementation.hasFeature && implementation.hasFeature('http://www.w3.org/TR/SVG11/feature#BasicStructure', '1.1'); +} + +var HTMLDOMPropertyConfig = { + isCustomAttribute: RegExp.prototype.test.bind(/^(data|aria)-[a-z_][a-z\d_.\-]*$/), + Properties: { + /** + * Standard Properties + */ + accept: null, + acceptCharset: null, + accessKey: null, + action: null, + allowFullScreen: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, + allowTransparency: MUST_USE_ATTRIBUTE, + alt: null, + async: HAS_BOOLEAN_VALUE, + autoComplete: null, + // autoFocus is polyfilled/normalized by AutoFocusUtils + // autoFocus: HAS_BOOLEAN_VALUE, + autoPlay: HAS_BOOLEAN_VALUE, + capture: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, + cellPadding: null, + cellSpacing: null, + charSet: MUST_USE_ATTRIBUTE, + challenge: MUST_USE_ATTRIBUTE, + checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, + classID: MUST_USE_ATTRIBUTE, + // To set className on SVG elements, it's necessary to use .setAttribute; + // this works on HTML elements too in all browsers except IE8. Conveniently, + // IE8 doesn't support SVG and so we can simply use the attribute in + // browsers that support SVG and the property in browsers that don't, + // regardless of whether the element is HTML or SVG. + className: hasSVG ? MUST_USE_ATTRIBUTE : MUST_USE_PROPERTY, + cols: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE, + colSpan: null, + content: null, + contentEditable: null, + contextMenu: MUST_USE_ATTRIBUTE, + controls: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, + coords: null, + crossOrigin: null, + data: null, // For `<object />` acts as `src`. + dateTime: MUST_USE_ATTRIBUTE, + 'default': HAS_BOOLEAN_VALUE, + defer: HAS_BOOLEAN_VALUE, + dir: null, + disabled: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, + download: HAS_OVERLOADED_BOOLEAN_VALUE, + draggable: null, + encType: null, + form: MUST_USE_ATTRIBUTE, + formAction: MUST_USE_ATTRIBUTE, + formEncType: MUST_USE_ATTRIBUTE, + formMethod: MUST_USE_ATTRIBUTE, + formNoValidate: HAS_BOOLEAN_VALUE, + formTarget: MUST_USE_ATTRIBUTE, + frameBorder: MUST_USE_ATTRIBUTE, + headers: null, + height: MUST_USE_ATTRIBUTE, + hidden: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, + high: null, + href: null, + hrefLang: null, + htmlFor: null, + httpEquiv: null, + icon: null, + id: MUST_USE_PROPERTY, + inputMode: MUST_USE_ATTRIBUTE, + integrity: null, + is: MUST_USE_ATTRIBUTE, + keyParams: MUST_USE_ATTRIBUTE, + keyType: MUST_USE_ATTRIBUTE, + kind: null, + label: null, + lang: null, + list: MUST_USE_ATTRIBUTE, + loop: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, + low: null, + manifest: MUST_USE_ATTRIBUTE, + marginHeight: null, + marginWidth: null, + max: null, + maxLength: MUST_USE_ATTRIBUTE, + media: MUST_USE_ATTRIBUTE, + mediaGroup: null, + method: null, + min: null, + minLength: MUST_USE_ATTRIBUTE, + multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, + muted: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, + name: null, + nonce: MUST_USE_ATTRIBUTE, + noValidate: HAS_BOOLEAN_VALUE, + open: HAS_BOOLEAN_VALUE, + optimum: null, + pattern: null, + placeholder: null, + poster: null, + preload: null, + radioGroup: null, + readOnly: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, + rel: null, + required: HAS_BOOLEAN_VALUE, + reversed: HAS_BOOLEAN_VALUE, + role: MUST_USE_ATTRIBUTE, + rows: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE, + rowSpan: null, + sandbox: null, + scope: null, + scoped: HAS_BOOLEAN_VALUE, + scrolling: null, + seamless: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, + selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, + shape: null, + size: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE, + sizes: MUST_USE_ATTRIBUTE, + span: HAS_POSITIVE_NUMERIC_VALUE, + spellCheck: null, + src: null, + srcDoc: MUST_USE_PROPERTY, + srcLang: null, + srcSet: MUST_USE_ATTRIBUTE, + start: HAS_NUMERIC_VALUE, + step: null, + style: null, + summary: null, + tabIndex: null, + target: null, + title: null, + type: null, + useMap: null, + value: MUST_USE_PROPERTY | HAS_SIDE_EFFECTS, + width: MUST_USE_ATTRIBUTE, + wmode: MUST_USE_ATTRIBUTE, + wrap: null, + + /** + * RDFa Properties + */ + about: MUST_USE_ATTRIBUTE, + datatype: MUST_USE_ATTRIBUTE, + inlist: MUST_USE_ATTRIBUTE, + prefix: MUST_USE_ATTRIBUTE, + // property is also supported for OpenGraph in meta tags. + property: MUST_USE_ATTRIBUTE, + resource: MUST_USE_ATTRIBUTE, + 'typeof': MUST_USE_ATTRIBUTE, + vocab: MUST_USE_ATTRIBUTE, + + /** + * Non-standard Properties + */ + // autoCapitalize and autoCorrect are supported in Mobile Safari for + // keyboard hints. + autoCapitalize: MUST_USE_ATTRIBUTE, + autoCorrect: MUST_USE_ATTRIBUTE, + // autoSave allows WebKit/Blink to persist values of input fields on page reloads + autoSave: null, + // color is for Safari mask-icon link + color: null, + // itemProp, itemScope, itemType are for + // Microdata support. See http://schema.org/docs/gs.html + itemProp: MUST_USE_ATTRIBUTE, + itemScope: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, + itemType: MUST_USE_ATTRIBUTE, + // itemID and itemRef are for Microdata support as well but + // only specified in the the WHATWG spec document. See + // https://html.spec.whatwg.org/multipage/microdata.html#microdata-dom-api + itemID: MUST_USE_ATTRIBUTE, + itemRef: MUST_USE_ATTRIBUTE, + // results show looking glass icon and recent searches on input + // search fields in WebKit/Blink + results: null, + // IE-only attribute that specifies security restrictions on an iframe + // as an alternative to the sandbox attribute on IE<10 + security: MUST_USE_ATTRIBUTE, + // IE-only attribute that controls focus behavior + unselectable: MUST_USE_ATTRIBUTE + }, + DOMAttributeNames: { + acceptCharset: 'accept-charset', + className: 'class', + htmlFor: 'for', + httpEquiv: 'http-equiv' + }, + DOMPropertyNames: { + autoComplete: 'autocomplete', + autoFocus: 'autofocus', + autoPlay: 'autoplay', + autoSave: 'autosave', + // `encoding` is equivalent to `enctype`, IE8 lacks an `enctype` setter. + // http://www.w3.org/TR/html5/forms.html#dom-fs-encoding + encType: 'encoding', + hrefLang: 'hreflang', + radioGroup: 'radiogroup', + spellCheck: 'spellcheck', + srcDoc: 'srcdoc', + srcSet: 'srcset' + } +}; + +module.exports = HTMLDOMPropertyConfig; +},{"10":10,"147":147}],22:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule LinkedStateMixin + * @typechecks static-only + */ + +'use strict'; + +var ReactLink = _dereq_(70); +var ReactStateSetters = _dereq_(90); + +/** + * A simple mixin around ReactLink.forState(). + */ +var LinkedStateMixin = { + /** + * Create a ReactLink that's linked to part of this component's state. The + * ReactLink will have the current value of this.state[key] and will call + * setState() when a change is requested. + * + * @param {string} key state key to update. Note: you may want to use keyOf() + * if you're using Google Closure Compiler advanced mode. + * @return {ReactLink} ReactLink instance linking to the state. + */ + linkState: function (key) { + return new ReactLink(this.state[key], ReactStateSetters.createStateKeySetter(this, key)); + } +}; + +module.exports = LinkedStateMixin; +},{"70":70,"90":90}],23:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule LinkedValueUtils + * @typechecks static-only + */ + +'use strict'; + +var ReactPropTypes = _dereq_(82); +var ReactPropTypeLocations = _dereq_(81); + +var invariant = _dereq_(161); +var warning = _dereq_(173); + +var hasReadOnlyValue = { + 'button': true, + 'checkbox': true, + 'image': true, + 'hidden': true, + 'radio': true, + 'reset': true, + 'submit': true +}; + +function _assertSingleLink(inputProps) { + !(inputProps.checkedLink == null || inputProps.valueLink == null) ? "development" !== 'production' ? invariant(false, 'Cannot provide a checkedLink and a valueLink. If you want to use ' + 'checkedLink, you probably don\'t want to use valueLink and vice versa.') : invariant(false) : undefined; +} +function _assertValueLink(inputProps) { + _assertSingleLink(inputProps); + !(inputProps.value == null && inputProps.onChange == null) ? "development" !== 'production' ? invariant(false, 'Cannot provide a valueLink and a value or onChange event. If you want ' + 'to use value or onChange, you probably don\'t want to use valueLink.') : invariant(false) : undefined; +} + +function _assertCheckedLink(inputProps) { + _assertSingleLink(inputProps); + !(inputProps.checked == null && inputProps.onChange == null) ? "development" !== 'production' ? invariant(false, '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') : invariant(false) : undefined; +} + +var propTypes = { + value: function (props, propName, componentName) { + if (!props[propName] || hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled) { + return null; + } + return new Error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); + }, + checked: function (props, propName, componentName) { + if (!props[propName] || props.onChange || props.readOnly || props.disabled) { + return null; + } + return new Error('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`.'); + }, + onChange: ReactPropTypes.func +}; + +var loggedTypeFailures = {}; +function getDeclarationErrorAddendum(owner) { + if (owner) { + var name = owner.getName(); + if (name) { + return ' Check the render method of `' + name + '`.'; + } + } + return ''; +} + +/** + * Provide a linked `value` attribute for controlled forms. You should not use + * this outside of the ReactDOM controlled form components. + */ +var LinkedValueUtils = { + checkPropTypes: function (tagName, props, owner) { + for (var propName in propTypes) { + if (propTypes.hasOwnProperty(propName)) { + var error = propTypes[propName](props, propName, tagName, ReactPropTypeLocations.prop); + } + if (error instanceof Error && !(error.message in loggedTypeFailures)) { + // Only monitor this failure once because there tends to be a lot of the + // same error. + loggedTypeFailures[error.message] = true; + + var addendum = getDeclarationErrorAddendum(owner); + "development" !== 'production' ? warning(false, 'Failed form propType: %s%s', error.message, addendum) : undefined; + } + } + }, + + /** + * @param {object} inputProps Props for form component + * @return {*} current value of the input either from value prop or link. + */ + getValue: function (inputProps) { + if (inputProps.valueLink) { + _assertValueLink(inputProps); + return inputProps.valueLink.value; + } + return inputProps.value; + }, + + /** + * @param {object} inputProps Props for form component + * @return {*} current checked status of the input either from checked prop + * or link. + */ + getChecked: function (inputProps) { + if (inputProps.checkedLink) { + _assertCheckedLink(inputProps); + return inputProps.checkedLink.value; + } + return inputProps.checked; + }, + + /** + * @param {object} inputProps Props for form component + * @param {SyntheticEvent} event change event to handle + */ + executeOnChange: function (inputProps, event) { + if (inputProps.valueLink) { + _assertValueLink(inputProps); + return inputProps.valueLink.requestChange(event.target.value); + } else if (inputProps.checkedLink) { + _assertCheckedLink(inputProps); + return inputProps.checkedLink.requestChange(event.target.checked); + } else if (inputProps.onChange) { + return inputProps.onChange.call(undefined, event); + } + } +}; + +module.exports = LinkedValueUtils; +},{"161":161,"173":173,"81":81,"82":82}],24:[function(_dereq_,module,exports){ +/** + * Copyright 2014-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule Object.assign + */ + +// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign + +'use strict'; + +function assign(target, sources) { + if (target == null) { + throw new TypeError('Object.assign target cannot be null or undefined'); + } + + var to = Object(target); + var hasOwnProperty = Object.prototype.hasOwnProperty; + + for (var nextIndex = 1; nextIndex < arguments.length; nextIndex++) { + var nextSource = arguments[nextIndex]; + if (nextSource == null) { + continue; + } + + var from = Object(nextSource); + + // We don't currently support accessors nor proxies. Therefore this + // copy cannot throw. If we ever supported this then we must handle + // exceptions and side-effects. We don't support symbols so they won't + // be transferred. + + for (var key in from) { + if (hasOwnProperty.call(from, key)) { + to[key] = from[key]; + } + } + } + + return to; +} + +module.exports = assign; +},{}],25:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule PooledClass + */ + +'use strict'; + +var invariant = _dereq_(161); + +/** + * Static poolers. Several custom versions for each potential number of + * arguments. A completely generic pooler is easy to implement, but would + * require accessing the `arguments` object. In each of these, `this` refers to + * the Class itself, not an instance. If any others are needed, simply add them + * here, or in their own files. + */ +var oneArgumentPooler = function (copyFieldsFrom) { + var Klass = this; + if (Klass.instancePool.length) { + var instance = Klass.instancePool.pop(); + Klass.call(instance, copyFieldsFrom); + return instance; + } else { + return new Klass(copyFieldsFrom); + } +}; + +var twoArgumentPooler = function (a1, a2) { + var Klass = this; + if (Klass.instancePool.length) { + var instance = Klass.instancePool.pop(); + Klass.call(instance, a1, a2); + return instance; + } else { + return new Klass(a1, a2); + } +}; + +var threeArgumentPooler = function (a1, a2, a3) { + var Klass = this; + if (Klass.instancePool.length) { + var instance = Klass.instancePool.pop(); + Klass.call(instance, a1, a2, a3); + return instance; + } else { + return new Klass(a1, a2, a3); + } +}; + +var fourArgumentPooler = function (a1, a2, a3, a4) { + var Klass = this; + if (Klass.instancePool.length) { + var instance = Klass.instancePool.pop(); + Klass.call(instance, a1, a2, a3, a4); + return instance; + } else { + return new Klass(a1, a2, a3, a4); + } +}; + +var fiveArgumentPooler = function (a1, a2, a3, a4, a5) { + var Klass = this; + if (Klass.instancePool.length) { + var instance = Klass.instancePool.pop(); + Klass.call(instance, a1, a2, a3, a4, a5); + return instance; + } else { + return new Klass(a1, a2, a3, a4, a5); + } +}; + +var standardReleaser = function (instance) { + var Klass = this; + !(instance instanceof Klass) ? "development" !== 'production' ? invariant(false, 'Trying to release an instance into a pool of a different type.') : invariant(false) : undefined; + instance.destructor(); + if (Klass.instancePool.length < Klass.poolSize) { + Klass.instancePool.push(instance); + } +}; + +var DEFAULT_POOL_SIZE = 10; +var DEFAULT_POOLER = oneArgumentPooler; + +/** + * Augments `CopyConstructor` to be a poolable class, augmenting only the class + * itself (statically) not adding any prototypical fields. Any CopyConstructor + * you give this may have a `poolSize` property, and will look for a + * prototypical `destructor` on instances (optional). + * + * @param {Function} CopyConstructor Constructor that can be used to reset. + * @param {Function} pooler Customizable pooler. + */ +var addPoolingTo = function (CopyConstructor, pooler) { + var NewKlass = CopyConstructor; + NewKlass.instancePool = []; + NewKlass.getPooled = pooler || DEFAULT_POOLER; + if (!NewKlass.poolSize) { + NewKlass.poolSize = DEFAULT_POOL_SIZE; + } + NewKlass.release = standardReleaser; + return NewKlass; +}; + +var PooledClass = { + addPoolingTo: addPoolingTo, + oneArgumentPooler: oneArgumentPooler, + twoArgumentPooler: twoArgumentPooler, + threeArgumentPooler: threeArgumentPooler, + fourArgumentPooler: fourArgumentPooler, + fiveArgumentPooler: fiveArgumentPooler +}; + +module.exports = PooledClass; +},{"161":161}],26:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule React + */ + +'use strict'; + +var ReactDOM = _dereq_(40); +var ReactDOMServer = _dereq_(50); +var ReactIsomorphic = _dereq_(69); + +var assign = _dereq_(24); +var deprecated = _dereq_(120); + +// `version` will be added here by ReactIsomorphic. +var React = {}; + +assign(React, ReactIsomorphic); + +assign(React, { + // ReactDOM + findDOMNode: deprecated('findDOMNode', 'ReactDOM', 'react-dom', ReactDOM, ReactDOM.findDOMNode), + render: deprecated('render', 'ReactDOM', 'react-dom', ReactDOM, ReactDOM.render), + unmountComponentAtNode: deprecated('unmountComponentAtNode', 'ReactDOM', 'react-dom', ReactDOM, ReactDOM.unmountComponentAtNode), + + // ReactDOMServer + renderToString: deprecated('renderToString', 'ReactDOMServer', 'react-dom/server', ReactDOMServer, ReactDOMServer.renderToString), + renderToStaticMarkup: deprecated('renderToStaticMarkup', 'ReactDOMServer', 'react-dom/server', ReactDOMServer, ReactDOMServer.renderToStaticMarkup) +}); + +React.__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactDOM; +React.__SECRET_DOM_SERVER_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactDOMServer; + +module.exports = React; +},{"120":120,"24":24,"40":40,"50":50,"69":69}],27:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactBrowserComponentMixin + */ + +'use strict'; + +var ReactInstanceMap = _dereq_(68); + +var findDOMNode = _dereq_(122); +var warning = _dereq_(173); + +var didWarnKey = '_getDOMNodeDidWarn'; + +var ReactBrowserComponentMixin = { + /** + * Returns the DOM node rendered by this component. + * + * @return {DOMElement} The root node of this component. + * @final + * @protected + */ + getDOMNode: function () { + "development" !== 'production' ? warning(this.constructor[didWarnKey], '%s.getDOMNode(...) is deprecated. Please use ' + 'ReactDOM.findDOMNode(instance) instead.', ReactInstanceMap.get(this).getName() || this.tagName || 'Unknown') : undefined; + this.constructor[didWarnKey] = true; + return findDOMNode(this); + } +}; + +module.exports = ReactBrowserComponentMixin; +},{"122":122,"173":173,"68":68}],28:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactBrowserEventEmitter + * @typechecks static-only + */ + +'use strict'; + +var EventConstants = _dereq_(15); +var EventPluginHub = _dereq_(16); +var EventPluginRegistry = _dereq_(17); +var ReactEventEmitterMixin = _dereq_(62); +var ReactPerf = _dereq_(78); +var ViewportMetrics = _dereq_(114); + +var assign = _dereq_(24); +var isEventSupported = _dereq_(133); + +/** + * Summary of `ReactBrowserEventEmitter` event handling: + * + * - Top-level delegation is used to trap most native browser events. This + * may only occur in the main thread and is the responsibility of + * ReactEventListener, which is injected and can therefore support pluggable + * event sources. This is the only work that occurs in the main thread. + * + * - We normalize and de-duplicate events to account for browser quirks. This + * may be done in the worker thread. + * + * - Forward these native events (with the associated top-level type used to + * trap it) to `EventPluginHub`, which in turn will ask plugins if they want + * to extract any synthetic events. + * + * - The `EventPluginHub` will then process each event by annotating them with + * "dispatches", a sequence of listeners and IDs that care about that event. + * + * - The `EventPluginHub` then dispatches the events. + * + * Overview of React and the event system: + * + * +------------+ . + * | DOM | . + * +------------+ . + * | . + * v . + * +------------+ . + * | ReactEvent | . + * | Listener | . + * +------------+ . +-----------+ + * | . +--------+|SimpleEvent| + * | . | |Plugin | + * +-----|------+ . v +-----------+ + * | | | . +--------------+ +------------+ + * | +-----------.--->|EventPluginHub| | Event | + * | | . | | +-----------+ | Propagators| + * | ReactEvent | . | | |TapEvent | |------------| + * | Emitter | . | |<---+|Plugin | |other plugin| + * | | . | | +-----------+ | utilities | + * | +-----------.--->| | +------------+ + * | | | . +--------------+ + * +-----|------+ . ^ +-----------+ + * | . | |Enter/Leave| + * + . +-------+|Plugin | + * +-------------+ . +-----------+ + * | application | . + * |-------------| . + * | | . + * | | . + * +-------------+ . + * . + * React Core . General Purpose Event Plugin System + */ + +var alreadyListeningTo = {}; +var isMonitoringScrollValue = false; +var reactTopListenersCounter = 0; + +// For events like 'submit' which don't consistently bubble (which we trap at a +// lower node than `document`), binding at `document` would cause duplicate +// events so we don't include them here +var topEventMapping = { + topAbort: 'abort', + topBlur: 'blur', + topCanPlay: 'canplay', + topCanPlayThrough: 'canplaythrough', + topChange: 'change', + topClick: 'click', + topCompositionEnd: 'compositionend', + topCompositionStart: 'compositionstart', + topCompositionUpdate: 'compositionupdate', + topContextMenu: 'contextmenu', + topCopy: 'copy', + topCut: 'cut', + topDoubleClick: 'dblclick', + topDrag: 'drag', + topDragEnd: 'dragend', + topDragEnter: 'dragenter', + topDragExit: 'dragexit', + topDragLeave: 'dragleave', + topDragOver: 'dragover', + topDragStart: 'dragstart', + topDrop: 'drop', + topDurationChange: 'durationchange', + topEmptied: 'emptied', + topEncrypted: 'encrypted', + topEnded: 'ended', + topError: 'error', + topFocus: 'focus', + topInput: 'input', + topKeyDown: 'keydown', + topKeyPress: 'keypress', + topKeyUp: 'keyup', + topLoadedData: 'loadeddata', + topLoadedMetadata: 'loadedmetadata', + topLoadStart: 'loadstart', + topMouseDown: 'mousedown', + topMouseMove: 'mousemove', + topMouseOut: 'mouseout', + topMouseOver: 'mouseover', + topMouseUp: 'mouseup', + topPaste: 'paste', + topPause: 'pause', + topPlay: 'play', + topPlaying: 'playing', + topProgress: 'progress', + topRateChange: 'ratechange', + topScroll: 'scroll', + topSeeked: 'seeked', + topSeeking: 'seeking', + topSelectionChange: 'selectionchange', + topStalled: 'stalled', + topSuspend: 'suspend', + topTextInput: 'textInput', + topTimeUpdate: 'timeupdate', + topTouchCancel: 'touchcancel', + topTouchEnd: 'touchend', + topTouchMove: 'touchmove', + topTouchStart: 'touchstart', + topVolumeChange: 'volumechange', + topWaiting: 'waiting', + topWheel: 'wheel' +}; + +/** + * To ensure no conflicts with other potential React instances on the page + */ +var topListenersIDKey = '_reactListenersID' + String(Math.random()).slice(2); + +function getListeningForDocument(mountAt) { + // In IE8, `mountAt` is a host object and doesn't have `hasOwnProperty` + // directly. + if (!Object.prototype.hasOwnProperty.call(mountAt, topListenersIDKey)) { + mountAt[topListenersIDKey] = reactTopListenersCounter++; + alreadyListeningTo[mountAt[topListenersIDKey]] = {}; + } + return alreadyListeningTo[mountAt[topListenersIDKey]]; +} + +/** + * `ReactBrowserEventEmitter` is used to attach top-level event listeners. For + * example: + * + * ReactBrowserEventEmitter.putListener('myID', 'onClick', myFunction); + * + * This would allocate a "registration" of `('onClick', myFunction)` on 'myID'. + * + * @internal + */ +var ReactBrowserEventEmitter = assign({}, ReactEventEmitterMixin, { + + /** + * Injectable event backend + */ + ReactEventListener: null, + + injection: { + /** + * @param {object} ReactEventListener + */ + injectReactEventListener: function (ReactEventListener) { + ReactEventListener.setHandleTopLevel(ReactBrowserEventEmitter.handleTopLevel); + ReactBrowserEventEmitter.ReactEventListener = ReactEventListener; + } + }, + + /** + * Sets whether or not any created callbacks should be enabled. + * + * @param {boolean} enabled True if callbacks should be enabled. + */ + setEnabled: function (enabled) { + if (ReactBrowserEventEmitter.ReactEventListener) { + ReactBrowserEventEmitter.ReactEventListener.setEnabled(enabled); + } + }, + + /** + * @return {boolean} True if callbacks are enabled. + */ + isEnabled: function () { + return !!(ReactBrowserEventEmitter.ReactEventListener && ReactBrowserEventEmitter.ReactEventListener.isEnabled()); + }, + + /** + * We listen for bubbled touch events on the document object. + * + * Firefox v8.01 (and possibly others) exhibited strange behavior when + * mounting `onmousemove` events at some node that was not the document + * element. The symptoms were that if your mouse is not moving over something + * contained within that mount point (for example on the background) the + * top-level listeners for `onmousemove` won't be called. However, if you + * register the `mousemove` on the document object, then it will of course + * catch all `mousemove`s. This along with iOS quirks, justifies restricting + * top-level listeners to the document object only, at least for these + * movement types of events and possibly all events. + * + * @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html + * + * Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but + * they bubble to document. + * + * @param {string} registrationName Name of listener (e.g. `onClick`). + * @param {object} contentDocumentHandle Document which owns the container + */ + listenTo: function (registrationName, contentDocumentHandle) { + var mountAt = contentDocumentHandle; + var isListening = getListeningForDocument(mountAt); + var dependencies = EventPluginRegistry.registrationNameDependencies[registrationName]; + + var topLevelTypes = EventConstants.topLevelTypes; + for (var i = 0; i < dependencies.length; i++) { + var dependency = dependencies[i]; + if (!(isListening.hasOwnProperty(dependency) && isListening[dependency])) { + if (dependency === topLevelTypes.topWheel) { + if (isEventSupported('wheel')) { + ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'wheel', mountAt); + } else if (isEventSupported('mousewheel')) { + ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'mousewheel', mountAt); + } else { + // Firefox needs to capture a different mouse scroll event. + // @see http://www.quirksmode.org/dom/events/tests/scroll.html + ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'DOMMouseScroll', mountAt); + } + } else if (dependency === topLevelTypes.topScroll) { + + if (isEventSupported('scroll', true)) { + ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topScroll, 'scroll', mountAt); + } else { + ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topScroll, 'scroll', ReactBrowserEventEmitter.ReactEventListener.WINDOW_HANDLE); + } + } else if (dependency === topLevelTypes.topFocus || dependency === topLevelTypes.topBlur) { + + if (isEventSupported('focus', true)) { + ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topFocus, 'focus', mountAt); + ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topBlur, 'blur', mountAt); + } else if (isEventSupported('focusin')) { + // IE has `focusin` and `focusout` events which bubble. + // @see http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html + ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topFocus, 'focusin', mountAt); + ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topBlur, 'focusout', mountAt); + } + + // to make sure blur and focus event listeners are only attached once + isListening[topLevelTypes.topBlur] = true; + isListening[topLevelTypes.topFocus] = true; + } else if (topEventMapping.hasOwnProperty(dependency)) { + ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(dependency, topEventMapping[dependency], mountAt); + } + + isListening[dependency] = true; + } + } + }, + + trapBubbledEvent: function (topLevelType, handlerBaseName, handle) { + return ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelType, handlerBaseName, handle); + }, + + trapCapturedEvent: function (topLevelType, handlerBaseName, handle) { + return ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelType, handlerBaseName, handle); + }, + + /** + * Listens to window scroll and resize events. We cache scroll values so that + * application code can access them without triggering reflows. + * + * NOTE: Scroll events do not bubble. + * + * @see http://www.quirksmode.org/dom/events/scroll.html + */ + ensureScrollValueMonitoring: function () { + if (!isMonitoringScrollValue) { + var refresh = ViewportMetrics.refreshScrollValues; + ReactBrowserEventEmitter.ReactEventListener.monitorScrollValue(refresh); + isMonitoringScrollValue = true; + } + }, + + eventNameDispatchConfigs: EventPluginHub.eventNameDispatchConfigs, + + registrationNameModules: EventPluginHub.registrationNameModules, + + putListener: EventPluginHub.putListener, + + getListener: EventPluginHub.getListener, + + deleteListener: EventPluginHub.deleteListener, + + deleteAllListeners: EventPluginHub.deleteAllListeners + +}); + +ReactPerf.measureMethods(ReactBrowserEventEmitter, 'ReactBrowserEventEmitter', { + putListener: 'putListener', + deleteListener: 'deleteListener' +}); + +module.exports = ReactBrowserEventEmitter; +},{"114":114,"133":133,"15":15,"16":16,"17":17,"24":24,"62":62,"78":78}],29:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @typechecks + * @providesModule ReactCSSTransitionGroup + */ + +'use strict'; + +var React = _dereq_(26); + +var assign = _dereq_(24); + +var ReactTransitionGroup = _dereq_(94); +var ReactCSSTransitionGroupChild = _dereq_(30); + +function createTransitionTimeoutPropValidator(transitionType) { + var timeoutPropName = 'transition' + transitionType + 'Timeout'; + var enabledPropName = 'transition' + transitionType; + + return function (props) { + // If the transition is enabled + if (props[enabledPropName]) { + // If no timeout duration is provided + if (props[timeoutPropName] == null) { + return new Error(timeoutPropName + ' wasn\'t supplied to ReactCSSTransitionGroup: ' + 'this can cause unreliable animations and won\'t be supported in ' + 'a future version of React. See ' + 'https://fb.me/react-animation-transition-group-timeout for more ' + 'information.'); + + // If the duration isn't a number + } else if (typeof props[timeoutPropName] !== 'number') { + return new Error(timeoutPropName + ' must be a number (in milliseconds)'); + } + } + }; +} + +var ReactCSSTransitionGroup = React.createClass({ + displayName: 'ReactCSSTransitionGroup', + + propTypes: { + transitionName: ReactCSSTransitionGroupChild.propTypes.name, + + transitionAppear: React.PropTypes.bool, + transitionEnter: React.PropTypes.bool, + transitionLeave: React.PropTypes.bool, + transitionAppearTimeout: createTransitionTimeoutPropValidator('Appear'), + transitionEnterTimeout: createTransitionTimeoutPropValidator('Enter'), + transitionLeaveTimeout: createTransitionTimeoutPropValidator('Leave') + }, + + getDefaultProps: function () { + return { + transitionAppear: false, + transitionEnter: true, + transitionLeave: true + }; + }, + + _wrapChild: function (child) { + // We need to provide this childFactory so that + // ReactCSSTransitionGroupChild can receive updates to name, enter, and + // leave while it is leaving. + return React.createElement(ReactCSSTransitionGroupChild, { + name: this.props.transitionName, + appear: this.props.transitionAppear, + enter: this.props.transitionEnter, + leave: this.props.transitionLeave, + appearTimeout: this.props.transitionAppearTimeout, + enterTimeout: this.props.transitionEnterTimeout, + leaveTimeout: this.props.transitionLeaveTimeout + }, child); + }, + + render: function () { + return React.createElement(ReactTransitionGroup, assign({}, this.props, { childFactory: this._wrapChild })); + } +}); + +module.exports = ReactCSSTransitionGroup; +},{"24":24,"26":26,"30":30,"94":94}],30:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @typechecks + * @providesModule ReactCSSTransitionGroupChild + */ + +'use strict'; + +var React = _dereq_(26); +var ReactDOM = _dereq_(40); + +var CSSCore = _dereq_(145); +var ReactTransitionEvents = _dereq_(93); + +var onlyChild = _dereq_(135); + +// We don't remove the element from the DOM until we receive an animationend or +// transitionend event. If the user screws up and forgets to add an animation +// their node will be stuck in the DOM forever, so we detect if an animation +// does not start and if it doesn't, we just call the end listener immediately. +var TICK = 17; + +var ReactCSSTransitionGroupChild = React.createClass({ + displayName: 'ReactCSSTransitionGroupChild', + + propTypes: { + name: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.shape({ + enter: React.PropTypes.string, + leave: React.PropTypes.string, + active: React.PropTypes.string + }), React.PropTypes.shape({ + enter: React.PropTypes.string, + enterActive: React.PropTypes.string, + leave: React.PropTypes.string, + leaveActive: React.PropTypes.string, + appear: React.PropTypes.string, + appearActive: React.PropTypes.string + })]).isRequired, + + // Once we require timeouts to be specified, we can remove the + // boolean flags (appear etc.) and just accept a number + // or a bool for the timeout flags (appearTimeout etc.) + appear: React.PropTypes.bool, + enter: React.PropTypes.bool, + leave: React.PropTypes.bool, + appearTimeout: React.PropTypes.number, + enterTimeout: React.PropTypes.number, + leaveTimeout: React.PropTypes.number + }, + + transition: function (animationType, finishCallback, userSpecifiedDelay) { + var node = ReactDOM.findDOMNode(this); + + if (!node) { + if (finishCallback) { + finishCallback(); + } + return; + } + + var className = this.props.name[animationType] || this.props.name + '-' + animationType; + var activeClassName = this.props.name[animationType + 'Active'] || className + '-active'; + var timeout = null; + + var endListener = function (e) { + if (e && e.target !== node) { + return; + } + + clearTimeout(timeout); + + CSSCore.removeClass(node, className); + CSSCore.removeClass(node, activeClassName); + + ReactTransitionEvents.removeEndEventListener(node, endListener); + + // Usually this optional callback is used for informing an owner of + // a leave animation and telling it to remove the child. + if (finishCallback) { + finishCallback(); + } + }; + + CSSCore.addClass(node, className); + + // Need to do this to actually trigger a transition. + this.queueClass(activeClassName); + + // If the user specified a timeout delay. + if (userSpecifiedDelay) { + // Clean-up the animation after the specified delay + timeout = setTimeout(endListener, userSpecifiedDelay); + this.transitionTimeouts.push(timeout); + } else { + // DEPRECATED: this listener will be removed in a future version of react + ReactTransitionEvents.addEndEventListener(node, endListener); + } + }, + + queueClass: function (className) { + this.classNameQueue.push(className); + + if (!this.timeout) { + this.timeout = setTimeout(this.flushClassNameQueue, TICK); + } + }, + + flushClassNameQueue: function () { + if (this.isMounted()) { + this.classNameQueue.forEach(CSSCore.addClass.bind(CSSCore, ReactDOM.findDOMNode(this))); + } + this.classNameQueue.length = 0; + this.timeout = null; + }, + + componentWillMount: function () { + this.classNameQueue = []; + this.transitionTimeouts = []; + }, + + componentWillUnmount: function () { + if (this.timeout) { + clearTimeout(this.timeout); + } + this.transitionTimeouts.forEach(function (timeout) { + clearTimeout(timeout); + }); + }, + + componentWillAppear: function (done) { + if (this.props.appear) { + this.transition('appear', done, this.props.appearTimeout); + } else { + done(); + } + }, + + componentWillEnter: function (done) { + if (this.props.enter) { + this.transition('enter', done, this.props.enterTimeout); + } else { + done(); + } + }, + + componentWillLeave: function (done) { + if (this.props.leave) { + this.transition('leave', done, this.props.leaveTimeout); + } else { + done(); + } + }, + + render: function () { + return onlyChild(this.props.children); + } +}); + +module.exports = ReactCSSTransitionGroupChild; +},{"135":135,"145":145,"26":26,"40":40,"93":93}],31:[function(_dereq_,module,exports){ +/** + * Copyright 2014-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactChildReconciler + * @typechecks static-only + */ + +'use strict'; + +var ReactReconciler = _dereq_(84); + +var instantiateReactComponent = _dereq_(132); +var shouldUpdateReactComponent = _dereq_(141); +var traverseAllChildren = _dereq_(142); +var warning = _dereq_(173); + +function instantiateChild(childInstances, child, name) { + // We found a component instance. + var keyUnique = childInstances[name] === undefined; + if ("development" !== 'production') { + "development" !== 'production' ? warning(keyUnique, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.', name) : undefined; + } + if (child != null && keyUnique) { + childInstances[name] = instantiateReactComponent(child, null); + } +} + +/** + * ReactChildReconciler provides helpers for initializing or updating a set of + * children. Its output is suitable for passing it onto ReactMultiChild which + * does diffed reordering and insertion. + */ +var ReactChildReconciler = { + /** + * Generates a "mount image" for each of the supplied children. In the case + * of `ReactDOMComponent`, a mount image is a string of markup. + * + * @param {?object} nestedChildNodes Nested child maps. + * @return {?object} A set of child instances. + * @internal + */ + instantiateChildren: function (nestedChildNodes, transaction, context) { + if (nestedChildNodes == null) { + return null; + } + var childInstances = {}; + traverseAllChildren(nestedChildNodes, instantiateChild, childInstances); + return childInstances; + }, + + /** + * Updates the rendered children and returns a new set of children. + * + * @param {?object} prevChildren Previously initialized set of children. + * @param {?object} nextChildren Flat child element maps. + * @param {ReactReconcileTransaction} transaction + * @param {object} context + * @return {?object} A new set of child instances. + * @internal + */ + updateChildren: function (prevChildren, nextChildren, transaction, context) { + // We currently don't have a way to track moves here but if we use iterators + // instead of for..in we can zip the iterators and check if an item has + // moved. + // TODO: If nothing has changed, return the prevChildren object so that we + // can quickly bailout if nothing has changed. + if (!nextChildren && !prevChildren) { + return null; + } + var name; + for (name in nextChildren) { + if (!nextChildren.hasOwnProperty(name)) { + continue; + } + var prevChild = prevChildren && prevChildren[name]; + var prevElement = prevChild && prevChild._currentElement; + var nextElement = nextChildren[name]; + if (prevChild != null && shouldUpdateReactComponent(prevElement, nextElement)) { + ReactReconciler.receiveComponent(prevChild, nextElement, transaction, context); + nextChildren[name] = prevChild; + } else { + if (prevChild) { + ReactReconciler.unmountComponent(prevChild, name); + } + // The child must be instantiated before it's mounted. + var nextChildInstance = instantiateReactComponent(nextElement, null); + nextChildren[name] = nextChildInstance; + } + } + // Unmount children that are no longer present. + for (name in prevChildren) { + if (prevChildren.hasOwnProperty(name) && !(nextChildren && nextChildren.hasOwnProperty(name))) { + ReactReconciler.unmountComponent(prevChildren[name]); + } + } + return nextChildren; + }, + + /** + * Unmounts all rendered children. This should be used to clean up children + * when this component is unmounted. + * + * @param {?object} renderedChildren Previously initialized set of children. + * @internal + */ + unmountChildren: function (renderedChildren) { + for (var name in renderedChildren) { + if (renderedChildren.hasOwnProperty(name)) { + var renderedChild = renderedChildren[name]; + ReactReconciler.unmountComponent(renderedChild); + } + } + } + +}; + +module.exports = ReactChildReconciler; +},{"132":132,"141":141,"142":142,"173":173,"84":84}],32:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactChildren + */ + +'use strict'; + +var PooledClass = _dereq_(25); +var ReactElement = _dereq_(57); + +var emptyFunction = _dereq_(153); +var traverseAllChildren = _dereq_(142); + +var twoArgumentPooler = PooledClass.twoArgumentPooler; +var fourArgumentPooler = PooledClass.fourArgumentPooler; + +var userProvidedKeyEscapeRegex = /\/(?!\/)/g; +function escapeUserProvidedKey(text) { + return ('' + text).replace(userProvidedKeyEscapeRegex, '//'); +} + +/** + * PooledClass representing the bookkeeping associated with performing a child + * traversal. Allows avoiding binding callbacks. + * + * @constructor ForEachBookKeeping + * @param {!function} forEachFunction Function to perform traversal with. + * @param {?*} forEachContext Context to perform context with. + */ +function ForEachBookKeeping(forEachFunction, forEachContext) { + this.func = forEachFunction; + this.context = forEachContext; + this.count = 0; +} +ForEachBookKeeping.prototype.destructor = function () { + this.func = null; + this.context = null; + this.count = 0; +}; +PooledClass.addPoolingTo(ForEachBookKeeping, twoArgumentPooler); + +function forEachSingleChild(bookKeeping, child, name) { + var func = bookKeeping.func; + var context = bookKeeping.context; + + func.call(context, child, bookKeeping.count++); +} + +/** + * Iterates through children that are typically specified as `props.children`. + * + * The provided forEachFunc(child, index) will be called for each + * leaf child. + * + * @param {?*} children Children tree container. + * @param {function(*, int)} forEachFunc + * @param {*} forEachContext Context for forEachContext. + */ +function forEachChildren(children, forEachFunc, forEachContext) { + if (children == null) { + return children; + } + var traverseContext = ForEachBookKeeping.getPooled(forEachFunc, forEachContext); + traverseAllChildren(children, forEachSingleChild, traverseContext); + ForEachBookKeeping.release(traverseContext); +} + +/** + * PooledClass representing the bookkeeping associated with performing a child + * mapping. Allows avoiding binding callbacks. + * + * @constructor MapBookKeeping + * @param {!*} mapResult Object containing the ordered map of results. + * @param {!function} mapFunction Function to perform mapping with. + * @param {?*} mapContext Context to perform mapping with. + */ +function MapBookKeeping(mapResult, keyPrefix, mapFunction, mapContext) { + this.result = mapResult; + this.keyPrefix = keyPrefix; + this.func = mapFunction; + this.context = mapContext; + this.count = 0; +} +MapBookKeeping.prototype.destructor = function () { + this.result = null; + this.keyPrefix = null; + this.func = null; + this.context = null; + this.count = 0; +}; +PooledClass.addPoolingTo(MapBookKeeping, fourArgumentPooler); + +function mapSingleChildIntoContext(bookKeeping, child, childKey) { + var result = bookKeeping.result; + var keyPrefix = bookKeeping.keyPrefix; + var func = bookKeeping.func; + var context = bookKeeping.context; + + var mappedChild = func.call(context, child, bookKeeping.count++); + if (Array.isArray(mappedChild)) { + mapIntoWithKeyPrefixInternal(mappedChild, result, childKey, emptyFunction.thatReturnsArgument); + } else if (mappedChild != null) { + if (ReactElement.isValidElement(mappedChild)) { + mappedChild = ReactElement.cloneAndReplaceKey(mappedChild, + // Keep both the (mapped) and old keys if they differ, just as + // traverseAllChildren used to do for objects as children + keyPrefix + (mappedChild !== child ? escapeUserProvidedKey(mappedChild.key || '') + '/' : '') + childKey); + } + result.push(mappedChild); + } +} + +function mapIntoWithKeyPrefixInternal(children, array, prefix, func, context) { + var escapedPrefix = ''; + if (prefix != null) { + escapedPrefix = escapeUserProvidedKey(prefix) + '/'; + } + var traverseContext = MapBookKeeping.getPooled(array, escapedPrefix, func, context); + traverseAllChildren(children, mapSingleChildIntoContext, traverseContext); + MapBookKeeping.release(traverseContext); +} + +/** + * Maps children that are typically specified as `props.children`. + * + * The provided mapFunction(child, key, index) will be called for each + * leaf child. + * + * @param {?*} children Children tree container. + * @param {function(*, int)} func The map function. + * @param {*} context Context for mapFunction. + * @return {object} Object containing the ordered map of results. + */ +function mapChildren(children, func, context) { + if (children == null) { + return children; + } + var result = []; + mapIntoWithKeyPrefixInternal(children, result, null, func, context); + return result; +} + +function forEachSingleChildDummy(traverseContext, child, name) { + return null; +} + +/** + * Count the number of children that are typically specified as + * `props.children`. + * + * @param {?*} children Children tree container. + * @return {number} The number of children. + */ +function countChildren(children, context) { + return traverseAllChildren(children, forEachSingleChildDummy, null); +} + +/** + * Flatten a children object (typically specified as `props.children`) and + * return an array with appropriately re-keyed children. + */ +function toArray(children) { + var result = []; + mapIntoWithKeyPrefixInternal(children, result, null, emptyFunction.thatReturnsArgument); + return result; +} + +var ReactChildren = { + forEach: forEachChildren, + map: mapChildren, + mapIntoWithKeyPrefixInternal: mapIntoWithKeyPrefixInternal, + count: countChildren, + toArray: toArray +}; + +module.exports = ReactChildren; +},{"142":142,"153":153,"25":25,"57":57}],33:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactClass + */ + +'use strict'; + +var ReactComponent = _dereq_(34); +var ReactElement = _dereq_(57); +var ReactPropTypeLocations = _dereq_(81); +var ReactPropTypeLocationNames = _dereq_(80); +var ReactNoopUpdateQueue = _dereq_(76); + +var assign = _dereq_(24); +var emptyObject = _dereq_(154); +var invariant = _dereq_(161); +var keyMirror = _dereq_(165); +var keyOf = _dereq_(166); +var warning = _dereq_(173); + +var MIXINS_KEY = keyOf({ mixins: null }); + +/** + * Policies that describe methods in `ReactClassInterface`. + */ +var SpecPolicy = keyMirror({ + /** + * These methods may be defined only once by the class specification or mixin. + */ + DEFINE_ONCE: null, + /** + * These methods may be defined by both the class specification and mixins. + * Subsequent definitions will be chained. These methods must return void. + */ + DEFINE_MANY: null, + /** + * These methods are overriding the base class. + */ + OVERRIDE_BASE: null, + /** + * These methods are similar to DEFINE_MANY, except we assume they return + * objects. We try to merge the keys of the return values of all the mixed in + * functions. If there is a key conflict we throw. + */ + DEFINE_MANY_MERGED: null +}); + +var injectedMixins = []; + +var warnedSetProps = false; +function warnSetProps() { + if (!warnedSetProps) { + warnedSetProps = true; + "development" !== 'production' ? warning(false, 'setProps(...) and replaceProps(...) are deprecated. ' + 'Instead, call render again at the top level.') : undefined; + } +} + +/** + * Composite components are higher-level components that compose other composite + * or native components. + * + * To create a new type of `ReactClass`, pass a specification of + * your new class to `React.createClass`. The only requirement of your class + * specification is that you implement a `render` method. + * + * var MyComponent = React.createClass({ + * render: function() { + * return <div>Hello World</div>; + * } + * }); + * + * The class specification supports a specific protocol of methods that have + * special meaning (e.g. `render`). See `ReactClassInterface` for + * more the comprehensive protocol. Any other properties and methods in the + * class specification will be available on the prototype. + * + * @interface ReactClassInterface + * @internal + */ +var ReactClassInterface = { + + /** + * An array of Mixin objects to include when defining your component. + * + * @type {array} + * @optional + */ + mixins: SpecPolicy.DEFINE_MANY, + + /** + * An object containing properties and methods that should be defined on + * the component's constructor instead of its prototype (static methods). + * + * @type {object} + * @optional + */ + statics: SpecPolicy.DEFINE_MANY, + + /** + * Definition of prop types for this component. + * + * @type {object} + * @optional + */ + propTypes: SpecPolicy.DEFINE_MANY, + + /** + * Definition of context types for this component. + * + * @type {object} + * @optional + */ + contextTypes: SpecPolicy.DEFINE_MANY, + + /** + * Definition of context types this component sets for its children. + * + * @type {object} + * @optional + */ + childContextTypes: SpecPolicy.DEFINE_MANY, + + // ==== Definition methods ==== + + /** + * Invoked when the component is mounted. Values in the mapping will be set on + * `this.props` if that prop is not specified (i.e. using an `in` check). + * + * This method is invoked before `getInitialState` and therefore cannot rely + * on `this.state` or use `this.setState`. + * + * @return {object} + * @optional + */ + getDefaultProps: SpecPolicy.DEFINE_MANY_MERGED, + + /** + * Invoked once before the component is mounted. The return value will be used + * as the initial value of `this.state`. + * + * getInitialState: function() { + * return { + * isOn: false, + * fooBaz: new BazFoo() + * } + * } + * + * @return {object} + * @optional + */ + getInitialState: SpecPolicy.DEFINE_MANY_MERGED, + + /** + * @return {object} + * @optional + */ + getChildContext: SpecPolicy.DEFINE_MANY_MERGED, + + /** + * Uses props from `this.props` and state from `this.state` to render the + * structure of the component. + * + * No guarantees are made about when or how often this method is invoked, so + * it must not have side effects. + * + * render: function() { + * var name = this.props.name; + * return <div>Hello, {name}!</div>; + * } + * + * @return {ReactComponent} + * @nosideeffects + * @required + */ + render: SpecPolicy.DEFINE_ONCE, + + // ==== Delegate methods ==== + + /** + * Invoked when the component is initially created and about to be mounted. + * This may have side effects, but any external subscriptions or data created + * by this method must be cleaned up in `componentWillUnmount`. + * + * @optional + */ + componentWillMount: SpecPolicy.DEFINE_MANY, + + /** + * Invoked when the component has been mounted and has a DOM representation. + * However, there is no guarantee that the DOM node is in the document. + * + * Use this as an opportunity to operate on the DOM when the component has + * been mounted (initialized and rendered) for the first time. + * + * @param {DOMElement} rootNode DOM element representing the component. + * @optional + */ + componentDidMount: SpecPolicy.DEFINE_MANY, + + /** + * Invoked before the component receives new props. + * + * Use this as an opportunity to react to a prop transition by updating the + * state using `this.setState`. Current props are accessed via `this.props`. + * + * componentWillReceiveProps: function(nextProps, nextContext) { + * this.setState({ + * likesIncreasing: nextProps.likeCount > this.props.likeCount + * }); + * } + * + * NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop + * transition may cause a state change, but the opposite is not true. If you + * need it, you are probably looking for `componentWillUpdate`. + * + * @param {object} nextProps + * @optional + */ + componentWillReceiveProps: SpecPolicy.DEFINE_MANY, + + /** + * Invoked while deciding if the component should be updated as a result of + * receiving new props, state and/or context. + * + * Use this as an opportunity to `return false` when you're certain that the + * transition to the new props/state/context will not require a component + * update. + * + * shouldComponentUpdate: function(nextProps, nextState, nextContext) { + * return !equal(nextProps, this.props) || + * !equal(nextState, this.state) || + * !equal(nextContext, this.context); + * } + * + * @param {object} nextProps + * @param {?object} nextState + * @param {?object} nextContext + * @return {boolean} True if the component should update. + * @optional + */ + shouldComponentUpdate: SpecPolicy.DEFINE_ONCE, + + /** + * Invoked when the component is about to update due to a transition from + * `this.props`, `this.state` and `this.context` to `nextProps`, `nextState` + * and `nextContext`. + * + * Use this as an opportunity to perform preparation before an update occurs. + * + * NOTE: You **cannot** use `this.setState()` in this method. + * + * @param {object} nextProps + * @param {?object} nextState + * @param {?object} nextContext + * @param {ReactReconcileTransaction} transaction + * @optional + */ + componentWillUpdate: SpecPolicy.DEFINE_MANY, + + /** + * Invoked when the component's DOM representation has been updated. + * + * Use this as an opportunity to operate on the DOM when the component has + * been updated. + * + * @param {object} prevProps + * @param {?object} prevState + * @param {?object} prevContext + * @param {DOMElement} rootNode DOM element representing the component. + * @optional + */ + componentDidUpdate: SpecPolicy.DEFINE_MANY, + + /** + * Invoked when the component is about to be removed from its parent and have + * its DOM representation destroyed. + * + * Use this as an opportunity to deallocate any external resources. + * + * NOTE: There is no `componentDidUnmount` since your component will have been + * destroyed by that point. + * + * @optional + */ + componentWillUnmount: SpecPolicy.DEFINE_MANY, + + // ==== Advanced methods ==== + + /** + * Updates the component's currently mounted DOM representation. + * + * By default, this implements React's rendering and reconciliation algorithm. + * Sophisticated clients may wish to override this. + * + * @param {ReactReconcileTransaction} transaction + * @internal + * @overridable + */ + updateComponent: SpecPolicy.OVERRIDE_BASE + +}; + +/** + * Mapping from class specification keys to special processing functions. + * + * Although these are declared like instance properties in the specification + * when defining classes using `React.createClass`, they are actually static + * and are accessible on the constructor instead of the prototype. Despite + * being static, they must be defined outside of the "statics" key under + * which all other static methods are defined. + */ +var RESERVED_SPEC_KEYS = { + displayName: function (Constructor, displayName) { + Constructor.displayName = displayName; + }, + mixins: function (Constructor, mixins) { + if (mixins) { + for (var i = 0; i < mixins.length; i++) { + mixSpecIntoComponent(Constructor, mixins[i]); + } + } + }, + childContextTypes: function (Constructor, childContextTypes) { + if ("development" !== 'production') { + validateTypeDef(Constructor, childContextTypes, ReactPropTypeLocations.childContext); + } + Constructor.childContextTypes = assign({}, Constructor.childContextTypes, childContextTypes); + }, + contextTypes: function (Constructor, contextTypes) { + if ("development" !== 'production') { + validateTypeDef(Constructor, contextTypes, ReactPropTypeLocations.context); + } + Constructor.contextTypes = assign({}, Constructor.contextTypes, contextTypes); + }, + /** + * Special case getDefaultProps which should move into statics but requires + * automatic merging. + */ + getDefaultProps: function (Constructor, getDefaultProps) { + if (Constructor.getDefaultProps) { + Constructor.getDefaultProps = createMergedResultFunction(Constructor.getDefaultProps, getDefaultProps); + } else { + Constructor.getDefaultProps = getDefaultProps; + } + }, + propTypes: function (Constructor, propTypes) { + if ("development" !== 'production') { + validateTypeDef(Constructor, propTypes, ReactPropTypeLocations.prop); + } + Constructor.propTypes = assign({}, Constructor.propTypes, propTypes); + }, + statics: function (Constructor, statics) { + mixStaticSpecIntoComponent(Constructor, statics); + }, + autobind: function () {} }; + +// noop +function validateTypeDef(Constructor, typeDef, location) { + for (var propName in typeDef) { + if (typeDef.hasOwnProperty(propName)) { + // use a warning instead of an invariant so components + // don't show up in prod but not in __DEV__ + "development" !== 'production' ? warning(typeof typeDef[propName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', Constructor.displayName || 'ReactClass', ReactPropTypeLocationNames[location], propName) : undefined; + } + } +} + +function validateMethodOverride(proto, name) { + var specPolicy = ReactClassInterface.hasOwnProperty(name) ? ReactClassInterface[name] : null; + + // Disallow overriding of base class methods unless explicitly allowed. + if (ReactClassMixin.hasOwnProperty(name)) { + !(specPolicy === SpecPolicy.OVERRIDE_BASE) ? "development" !== 'production' ? invariant(false, 'ReactClassInterface: You are attempting to override ' + '`%s` from your class specification. Ensure that your method names ' + 'do not overlap with React methods.', name) : invariant(false) : undefined; + } + + // Disallow defining methods more than once unless explicitly allowed. + if (proto.hasOwnProperty(name)) { + !(specPolicy === SpecPolicy.DEFINE_MANY || specPolicy === SpecPolicy.DEFINE_MANY_MERGED) ? "development" !== 'production' ? invariant(false, 'ReactClassInterface: You are attempting to define ' + '`%s` on your component more than once. This conflict may be due ' + 'to a mixin.', name) : invariant(false) : undefined; + } +} + +/** + * Mixin helper which handles policy validation and reserved + * specification keys when building React classses. + */ +function mixSpecIntoComponent(Constructor, spec) { + if (!spec) { + return; + } + + !(typeof spec !== 'function') ? "development" !== 'production' ? invariant(false, 'ReactClass: You\'re attempting to ' + 'use a component class as a mixin. Instead, just use a regular object.') : invariant(false) : undefined; + !!ReactElement.isValidElement(spec) ? "development" !== 'production' ? invariant(false, 'ReactClass: You\'re attempting to ' + 'use a component as a mixin. Instead, just use a regular object.') : invariant(false) : undefined; + + var proto = Constructor.prototype; + + // By handling mixins before any other properties, we ensure the same + // chaining order is applied to methods with DEFINE_MANY policy, whether + // mixins are listed before or after these methods in the spec. + if (spec.hasOwnProperty(MIXINS_KEY)) { + RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins); + } + + for (var name in spec) { + if (!spec.hasOwnProperty(name)) { + continue; + } + + if (name === MIXINS_KEY) { + // We have already handled mixins in a special case above. + continue; + } + + var property = spec[name]; + validateMethodOverride(proto, name); + + if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) { + RESERVED_SPEC_KEYS[name](Constructor, property); + } else { + // Setup methods on prototype: + // The following member methods should not be automatically bound: + // 1. Expected ReactClass methods (in the "interface"). + // 2. Overridden methods (that were mixed in). + var isReactClassMethod = ReactClassInterface.hasOwnProperty(name); + var isAlreadyDefined = proto.hasOwnProperty(name); + var isFunction = typeof property === 'function'; + var shouldAutoBind = isFunction && !isReactClassMethod && !isAlreadyDefined && spec.autobind !== false; + + if (shouldAutoBind) { + if (!proto.__reactAutoBindMap) { + proto.__reactAutoBindMap = {}; + } + proto.__reactAutoBindMap[name] = property; + proto[name] = property; + } else { + if (isAlreadyDefined) { + var specPolicy = ReactClassInterface[name]; + + // These cases should already be caught by validateMethodOverride. + !(isReactClassMethod && (specPolicy === SpecPolicy.DEFINE_MANY_MERGED || specPolicy === SpecPolicy.DEFINE_MANY)) ? "development" !== 'production' ? invariant(false, 'ReactClass: Unexpected spec policy %s for key %s ' + 'when mixing in component specs.', specPolicy, name) : invariant(false) : undefined; + + // For methods which are defined more than once, call the existing + // methods before calling the new property, merging if appropriate. + if (specPolicy === SpecPolicy.DEFINE_MANY_MERGED) { + proto[name] = createMergedResultFunction(proto[name], property); + } else if (specPolicy === SpecPolicy.DEFINE_MANY) { + proto[name] = createChainedFunction(proto[name], property); + } + } else { + proto[name] = property; + if ("development" !== 'production') { + // Add verbose displayName to the function, which helps when looking + // at profiling tools. + if (typeof property === 'function' && spec.displayName) { + proto[name].displayName = spec.displayName + '_' + name; + } + } + } + } + } + } +} + +function mixStaticSpecIntoComponent(Constructor, statics) { + if (!statics) { + return; + } + for (var name in statics) { + var property = statics[name]; + if (!statics.hasOwnProperty(name)) { + continue; + } + + var isReserved = (name in RESERVED_SPEC_KEYS); + !!isReserved ? "development" !== 'production' ? invariant(false, 'ReactClass: You are attempting to define a reserved ' + 'property, `%s`, that shouldn\'t be on the "statics" key. Define it ' + 'as an instance property instead; it will still be accessible on the ' + 'constructor.', name) : invariant(false) : undefined; + + var isInherited = (name in Constructor); + !!isInherited ? "development" !== 'production' ? invariant(false, 'ReactClass: You are attempting to define ' + '`%s` on your component more than once. This conflict may be ' + 'due to a mixin.', name) : invariant(false) : undefined; + Constructor[name] = property; + } +} + +/** + * Merge two objects, but throw if both contain the same key. + * + * @param {object} one The first object, which is mutated. + * @param {object} two The second object + * @return {object} one after it has been mutated to contain everything in two. + */ +function mergeIntoWithNoDuplicateKeys(one, two) { + !(one && two && typeof one === 'object' && typeof two === 'object') ? "development" !== 'production' ? invariant(false, 'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.') : invariant(false) : undefined; + + for (var key in two) { + if (two.hasOwnProperty(key)) { + !(one[key] === undefined) ? "development" !== 'production' ? invariant(false, 'mergeIntoWithNoDuplicateKeys(): ' + 'Tried to merge two objects with the same key: `%s`. This conflict ' + 'may be due to a mixin; in particular, this may be caused by two ' + 'getInitialState() or getDefaultProps() methods returning objects ' + 'with clashing keys.', key) : invariant(false) : undefined; + one[key] = two[key]; + } + } + return one; +} + +/** + * Creates a function that invokes two functions and merges their return values. + * + * @param {function} one Function to invoke first. + * @param {function} two Function to invoke second. + * @return {function} Function that invokes the two argument functions. + * @private + */ +function createMergedResultFunction(one, two) { + return function mergedResult() { + var a = one.apply(this, arguments); + var b = two.apply(this, arguments); + if (a == null) { + return b; + } else if (b == null) { + return a; + } + var c = {}; + mergeIntoWithNoDuplicateKeys(c, a); + mergeIntoWithNoDuplicateKeys(c, b); + return c; + }; +} + +/** + * Creates a function that invokes two functions and ignores their return vales. + * + * @param {function} one Function to invoke first. + * @param {function} two Function to invoke second. + * @return {function} Function that invokes the two argument functions. + * @private + */ +function createChainedFunction(one, two) { + return function chainedFunction() { + one.apply(this, arguments); + two.apply(this, arguments); + }; +} + +/** + * Binds a method to the component. + * + * @param {object} component Component whose method is going to be bound. + * @param {function} method Method to be bound. + * @return {function} The bound method. + */ +function bindAutoBindMethod(component, method) { + var boundMethod = method.bind(component); + if ("development" !== 'production') { + boundMethod.__reactBoundContext = component; + boundMethod.__reactBoundMethod = method; + boundMethod.__reactBoundArguments = null; + var componentName = component.constructor.displayName; + var _bind = boundMethod.bind; + /* eslint-disable block-scoped-var, no-undef */ + boundMethod.bind = function (newThis) { + for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + + // User is trying to bind() an autobound method; we effectively will + // ignore the value of "this" that the user is trying to use, so + // let's warn. + if (newThis !== component && newThis !== null) { + "development" !== 'production' ? warning(false, 'bind(): React component methods may only be bound to the ' + 'component instance. See %s', componentName) : undefined; + } else if (!args.length) { + "development" !== 'production' ? warning(false, 'bind(): You are binding a component method to the component. ' + 'React does this for you automatically in a high-performance ' + 'way, so you can safely remove this call. See %s', componentName) : undefined; + return boundMethod; + } + var reboundMethod = _bind.apply(boundMethod, arguments); + reboundMethod.__reactBoundContext = component; + reboundMethod.__reactBoundMethod = method; + reboundMethod.__reactBoundArguments = args; + return reboundMethod; + /* eslint-enable */ + }; + } + return boundMethod; +} + +/** + * Binds all auto-bound methods in a component. + * + * @param {object} component Component whose method is going to be bound. + */ +function bindAutoBindMethods(component) { + for (var autoBindKey in component.__reactAutoBindMap) { + if (component.__reactAutoBindMap.hasOwnProperty(autoBindKey)) { + var method = component.__reactAutoBindMap[autoBindKey]; + component[autoBindKey] = bindAutoBindMethod(component, method); + } + } +} + +/** + * Add more to the ReactClass base class. These are all legacy features and + * therefore not already part of the modern ReactComponent. + */ +var ReactClassMixin = { + + /** + * TODO: This will be deprecated because state should always keep a consistent + * type signature and the only use case for this, is to avoid that. + */ + replaceState: function (newState, callback) { + this.updater.enqueueReplaceState(this, newState); + if (callback) { + this.updater.enqueueCallback(this, callback); + } + }, + + /** + * Checks whether or not this composite component is mounted. + * @return {boolean} True if mounted, false otherwise. + * @protected + * @final + */ + isMounted: function () { + return this.updater.isMounted(this); + }, + + /** + * Sets a subset of the props. + * + * @param {object} partialProps Subset of the next props. + * @param {?function} callback Called after props are updated. + * @final + * @public + * @deprecated + */ + setProps: function (partialProps, callback) { + if ("development" !== 'production') { + warnSetProps(); + } + this.updater.enqueueSetProps(this, partialProps); + if (callback) { + this.updater.enqueueCallback(this, callback); + } + }, + + /** + * Replace all the props. + * + * @param {object} newProps Subset of the next props. + * @param {?function} callback Called after props are updated. + * @final + * @public + * @deprecated + */ + replaceProps: function (newProps, callback) { + if ("development" !== 'production') { + warnSetProps(); + } + this.updater.enqueueReplaceProps(this, newProps); + if (callback) { + this.updater.enqueueCallback(this, callback); + } + } +}; + +var ReactClassComponent = function () {}; +assign(ReactClassComponent.prototype, ReactComponent.prototype, ReactClassMixin); + +/** + * Module for creating composite components. + * + * @class ReactClass + */ +var ReactClass = { + + /** + * Creates a composite component class given a class specification. + * + * @param {object} spec Class specification (which must define `render`). + * @return {function} Component constructor function. + * @public + */ + createClass: function (spec) { + var Constructor = function (props, context, updater) { + // This constructor is overridden by mocks. The argument is used + // by mocks to assert on what gets mounted. + + if ("development" !== 'production') { + "development" !== 'production' ? warning(this instanceof Constructor, 'Something is calling a React component directly. Use a factory or ' + 'JSX instead. See: https://fb.me/react-legacyfactory') : undefined; + } + + // Wire up auto-binding + if (this.__reactAutoBindMap) { + bindAutoBindMethods(this); + } + + this.props = props; + this.context = context; + this.refs = emptyObject; + this.updater = updater || ReactNoopUpdateQueue; + + this.state = null; + + // ReactClasses doesn't have constructors. Instead, they use the + // getInitialState and componentWillMount methods for initialization. + + var initialState = this.getInitialState ? this.getInitialState() : null; + if ("development" !== 'production') { + // We allow auto-mocks to proceed as if they're returning null. + if (typeof initialState === 'undefined' && this.getInitialState._isMockFunction) { + // This is probably bad practice. Consider warning here and + // deprecating this convenience. + initialState = null; + } + } + !(typeof initialState === 'object' && !Array.isArray(initialState)) ? "development" !== 'production' ? invariant(false, '%s.getInitialState(): must return an object or null', Constructor.displayName || 'ReactCompositeComponent') : invariant(false) : undefined; + + this.state = initialState; + }; + Constructor.prototype = new ReactClassComponent(); + Constructor.prototype.constructor = Constructor; + + injectedMixins.forEach(mixSpecIntoComponent.bind(null, Constructor)); + + mixSpecIntoComponent(Constructor, spec); + + // Initialize the defaultProps property after all mixins have been merged. + if (Constructor.getDefaultProps) { + Constructor.defaultProps = Constructor.getDefaultProps(); + } + + if ("development" !== 'production') { + // This is a tag to indicate that the use of these method names is ok, + // since it's used with createClass. If it's not, then it's likely a + // mistake so we'll warn you to use the static property, property + // initializer or constructor respectively. + if (Constructor.getDefaultProps) { + Constructor.getDefaultProps.isReactClassApproved = {}; + } + if (Constructor.prototype.getInitialState) { + Constructor.prototype.getInitialState.isReactClassApproved = {}; + } + } + + !Constructor.prototype.render ? "development" !== 'production' ? invariant(false, 'createClass(...): Class specification must implement a `render` method.') : invariant(false) : undefined; + + if ("development" !== 'production') { + "development" !== 'production' ? warning(!Constructor.prototype.componentShouldUpdate, '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', spec.displayName || 'A component') : undefined; + "development" !== 'production' ? warning(!Constructor.prototype.componentWillRecieveProps, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', spec.displayName || 'A component') : undefined; + } + + // Reduce time spent doing lookups by setting these on the prototype. + for (var methodName in ReactClassInterface) { + if (!Constructor.prototype[methodName]) { + Constructor.prototype[methodName] = null; + } + } + + return Constructor; + }, + + injection: { + injectMixin: function (mixin) { + injectedMixins.push(mixin); + } + } + +}; + +module.exports = ReactClass; +},{"154":154,"161":161,"165":165,"166":166,"173":173,"24":24,"34":34,"57":57,"76":76,"80":80,"81":81}],34:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactComponent + */ + +'use strict'; + +var ReactNoopUpdateQueue = _dereq_(76); + +var canDefineProperty = _dereq_(117); +var emptyObject = _dereq_(154); +var invariant = _dereq_(161); +var warning = _dereq_(173); + +/** + * Base class helpers for the updating state of a component. + */ +function ReactComponent(props, context, updater) { + this.props = props; + this.context = context; + this.refs = emptyObject; + // We initialize the default updater but the real one gets injected by the + // renderer. + this.updater = updater || ReactNoopUpdateQueue; +} + +ReactComponent.prototype.isReactComponent = {}; + +/** + * Sets a subset of the state. Always use this to mutate + * state. You should treat `this.state` as immutable. + * + * There is no guarantee that `this.state` will be immediately updated, so + * accessing `this.state` after calling this method may return the old value. + * + * There is no guarantee that calls to `setState` will run synchronously, + * as they may eventually be batched together. You can provide an optional + * callback that will be executed when the call to setState is actually + * completed. + * + * When a function is provided to setState, it will be called at some point in + * the future (not synchronously). It will be called with the up to date + * component arguments (state, props, context). These values can be different + * from this.* because your function may be called after receiveProps but before + * shouldComponentUpdate, and this new state, props, and context will not yet be + * assigned to this. + * + * @param {object|function} partialState Next partial state or function to + * produce next partial state to be merged with current state. + * @param {?function} callback Called after state is updated. + * @final + * @protected + */ +ReactComponent.prototype.setState = function (partialState, callback) { + !(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null) ? "development" !== 'production' ? invariant(false, 'setState(...): takes an object of state variables to update or a ' + 'function which returns an object of state variables.') : invariant(false) : undefined; + if ("development" !== 'production') { + "development" !== 'production' ? warning(partialState != null, 'setState(...): You passed an undefined or null state object; ' + 'instead, use forceUpdate().') : undefined; + } + this.updater.enqueueSetState(this, partialState); + if (callback) { + this.updater.enqueueCallback(this, callback); + } +}; + +/** + * Forces an update. This should only be invoked when it is known with + * certainty that we are **not** in a DOM transaction. + * + * You may want to call this when you know that some deeper aspect of the + * component's state has changed but `setState` was not called. + * + * This will not invoke `shouldComponentUpdate`, but it will invoke + * `componentWillUpdate` and `componentDidUpdate`. + * + * @param {?function} callback Called after update is complete. + * @final + * @protected + */ +ReactComponent.prototype.forceUpdate = function (callback) { + this.updater.enqueueForceUpdate(this); + if (callback) { + this.updater.enqueueCallback(this, callback); + } +}; + +/** + * Deprecated APIs. These APIs used to exist on classic React classes but since + * we would like to deprecate them, we're not going to move them over to this + * modern base class. Instead, we define a getter that warns if it's accessed. + */ +if ("development" !== 'production') { + var deprecatedAPIs = { + getDOMNode: ['getDOMNode', 'Use ReactDOM.findDOMNode(component) instead.'], + isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'], + replaceProps: ['replaceProps', 'Instead, call render again at the top level.'], + replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).'], + setProps: ['setProps', 'Instead, call render again at the top level.'] + }; + var defineDeprecationWarning = function (methodName, info) { + if (canDefineProperty) { + Object.defineProperty(ReactComponent.prototype, methodName, { + get: function () { + "development" !== 'production' ? warning(false, '%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]) : undefined; + return undefined; + } + }); + } + }; + for (var fnName in deprecatedAPIs) { + if (deprecatedAPIs.hasOwnProperty(fnName)) { + defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); + } + } +} + +module.exports = ReactComponent; +},{"117":117,"154":154,"161":161,"173":173,"76":76}],35:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactComponentBrowserEnvironment + */ + +'use strict'; + +var ReactDOMIDOperations = _dereq_(45); +var ReactMount = _dereq_(72); + +/** + * Abstracts away all functionality of the reconciler that requires knowledge of + * the browser context. TODO: These callers should be refactored to avoid the + * need for this injection. + */ +var ReactComponentBrowserEnvironment = { + + processChildrenUpdates: ReactDOMIDOperations.dangerouslyProcessChildrenUpdates, + + replaceNodeWithMarkupByID: ReactDOMIDOperations.dangerouslyReplaceNodeWithMarkupByID, + + /** + * If a particular environment requires that some resources be cleaned up, + * specify this in the injected Mixin. In the DOM, we would likely want to + * purge any cached node ID lookups. + * + * @private + */ + unmountIDFromEnvironment: function (rootNodeID) { + ReactMount.purgeID(rootNodeID); + } + +}; + +module.exports = ReactComponentBrowserEnvironment; +},{"45":45,"72":72}],36:[function(_dereq_,module,exports){ +/** + * Copyright 2014-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactComponentEnvironment + */ + +'use strict'; + +var invariant = _dereq_(161); + +var injected = false; + +var ReactComponentEnvironment = { + + /** + * Optionally injectable environment dependent cleanup hook. (server vs. + * browser etc). Example: A browser system caches DOM nodes based on component + * ID and must remove that cache entry when this instance is unmounted. + */ + unmountIDFromEnvironment: null, + + /** + * Optionally injectable hook for swapping out mount images in the middle of + * the tree. + */ + replaceNodeWithMarkupByID: null, + + /** + * Optionally injectable hook for processing a queue of child updates. Will + * later move into MultiChildComponents. + */ + processChildrenUpdates: null, + + injection: { + injectEnvironment: function (environment) { + !!injected ? "development" !== 'production' ? invariant(false, 'ReactCompositeComponent: injectEnvironment() can only be called once.') : invariant(false) : undefined; + ReactComponentEnvironment.unmountIDFromEnvironment = environment.unmountIDFromEnvironment; + ReactComponentEnvironment.replaceNodeWithMarkupByID = environment.replaceNodeWithMarkupByID; + ReactComponentEnvironment.processChildrenUpdates = environment.processChildrenUpdates; + injected = true; + } + } + +}; + +module.exports = ReactComponentEnvironment; +},{"161":161}],37:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactComponentWithPureRenderMixin + */ + +'use strict'; + +var shallowCompare = _dereq_(140); + +/** + * If your React component's render function is "pure", e.g. it will render the + * same result given the same props and state, provide this Mixin for a + * considerable performance boost. + * + * Most React components have pure render functions. + * + * Example: + * + * var ReactComponentWithPureRenderMixin = + * require('ReactComponentWithPureRenderMixin'); + * React.createClass({ + * mixins: [ReactComponentWithPureRenderMixin], + * + * render: function() { + * return <div className={this.props.className}>foo</div>; + * } + * }); + * + * Note: This only checks shallow equality for props and state. If these contain + * complex data structures this mixin may have false-negatives for deeper + * differences. Only mixin to components which have simple props and state, or + * use `forceUpdate()` when you know deep data structures have changed. + */ +var ReactComponentWithPureRenderMixin = { + shouldComponentUpdate: function (nextProps, nextState) { + return shallowCompare(this, nextProps, nextState); + } +}; + +module.exports = ReactComponentWithPureRenderMixin; +},{"140":140}],38:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactCompositeComponent + */ + +'use strict'; + +var ReactComponentEnvironment = _dereq_(36); +var ReactCurrentOwner = _dereq_(39); +var ReactElement = _dereq_(57); +var ReactInstanceMap = _dereq_(68); +var ReactPerf = _dereq_(78); +var ReactPropTypeLocations = _dereq_(81); +var ReactPropTypeLocationNames = _dereq_(80); +var ReactReconciler = _dereq_(84); +var ReactUpdateQueue = _dereq_(95); + +var assign = _dereq_(24); +var emptyObject = _dereq_(154); +var invariant = _dereq_(161); +var shouldUpdateReactComponent = _dereq_(141); +var warning = _dereq_(173); + +function getDeclarationErrorAddendum(component) { + var owner = component._currentElement._owner || null; + if (owner) { + var name = owner.getName(); + if (name) { + return ' Check the render method of `' + name + '`.'; + } + } + return ''; +} + +function StatelessComponent(Component) {} +StatelessComponent.prototype.render = function () { + var Component = ReactInstanceMap.get(this)._currentElement.type; + return Component(this.props, this.context, this.updater); +}; + +/** + * ------------------ The Life-Cycle of a Composite Component ------------------ + * + * - constructor: Initialization of state. The instance is now retained. + * - componentWillMount + * - render + * - [children's constructors] + * - [children's componentWillMount and render] + * - [children's componentDidMount] + * - componentDidMount + * + * Update Phases: + * - componentWillReceiveProps (only called if parent updated) + * - shouldComponentUpdate + * - componentWillUpdate + * - render + * - [children's constructors or receive props phases] + * - componentDidUpdate + * + * - componentWillUnmount + * - [children's componentWillUnmount] + * - [children destroyed] + * - (destroyed): The instance is now blank, released by React and ready for GC. + * + * ----------------------------------------------------------------------------- + */ + +/** + * An incrementing ID assigned to each component when it is mounted. This is + * used to enforce the order in which `ReactUpdates` updates dirty components. + * + * @private + */ +var nextMountID = 1; + +/** + * @lends {ReactCompositeComponent.prototype} + */ +var ReactCompositeComponentMixin = { + + /** + * Base constructor for all composite component. + * + * @param {ReactElement} element + * @final + * @internal + */ + construct: function (element) { + this._currentElement = element; + this._rootNodeID = null; + this._instance = null; + + // See ReactUpdateQueue + this._pendingElement = null; + this._pendingStateQueue = null; + this._pendingReplaceState = false; + this._pendingForceUpdate = false; + + this._renderedComponent = null; + + this._context = null; + this._mountOrder = 0; + this._topLevelWrapper = null; + + // See ReactUpdates and ReactUpdateQueue. + this._pendingCallbacks = null; + }, + + /** + * Initializes the component, renders markup, and registers event listeners. + * + * @param {string} rootID DOM ID of the root node. + * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction + * @return {?string} Rendered markup to be inserted into the DOM. + * @final + * @internal + */ + mountComponent: function (rootID, transaction, context) { + this._context = context; + this._mountOrder = nextMountID++; + this._rootNodeID = rootID; + + var publicProps = this._processProps(this._currentElement.props); + var publicContext = this._processContext(context); + + var Component = this._currentElement.type; + + // Initialize the public class + var inst; + var renderedElement; + + // This is a way to detect if Component is a stateless arrow function + // component, which is not newable. It might not be 100% reliable but is + // something we can do until we start detecting that Component extends + // React.Component. We already assume that typeof Component === 'function'. + var canInstantiate = ('prototype' in Component); + + if (canInstantiate) { + if ("development" !== 'production') { + ReactCurrentOwner.current = this; + try { + inst = new Component(publicProps, publicContext, ReactUpdateQueue); + } finally { + ReactCurrentOwner.current = null; + } + } else { + inst = new Component(publicProps, publicContext, ReactUpdateQueue); + } + } + + if (!canInstantiate || inst === null || inst === false || ReactElement.isValidElement(inst)) { + renderedElement = inst; + inst = new StatelessComponent(Component); + } + + if ("development" !== 'production') { + // This will throw later in _renderValidatedComponent, but add an early + // warning now to help debugging + if (inst.render == null) { + "development" !== 'production' ? warning(false, '%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`, returned ' + 'null/false from a stateless component, or tried to render an ' + 'element whose type is a function that isn\'t a React component.', Component.displayName || Component.name || 'Component') : undefined; + } else { + // We support ES6 inheriting from React.Component, the module pattern, + // and stateless components, but not ES6 classes that don't extend + "development" !== 'production' ? warning(Component.prototype && Component.prototype.isReactComponent || !canInstantiate || !(inst instanceof Component), '%s(...): React component classes must extend React.Component.', Component.displayName || Component.name || 'Component') : undefined; + } + } + + // These should be set up in the constructor, but as a convenience for + // simpler class abstractions, we set them up after the fact. + inst.props = publicProps; + inst.context = publicContext; + inst.refs = emptyObject; + inst.updater = ReactUpdateQueue; + + this._instance = inst; + + // Store a reference from the instance back to the internal representation + ReactInstanceMap.set(inst, this); + + if ("development" !== 'production') { + // Since plain JS classes are defined without any special initialization + // logic, we can not catch common errors early. Therefore, we have to + // catch them here, at initialization time, instead. + "development" !== 'production' ? warning(!inst.getInitialState || inst.getInitialState.isReactClassApproved, 'getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', this.getName() || 'a component') : undefined; + "development" !== 'production' ? warning(!inst.getDefaultProps || inst.getDefaultProps.isReactClassApproved, 'getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', this.getName() || 'a component') : undefined; + "development" !== 'production' ? warning(!inst.propTypes, 'propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', this.getName() || 'a component') : undefined; + "development" !== 'production' ? warning(!inst.contextTypes, 'contextTypes was defined as an instance property on %s. Use a ' + 'static property to define contextTypes instead.', this.getName() || 'a component') : undefined; + "development" !== 'production' ? warning(typeof inst.componentShouldUpdate !== 'function', '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', this.getName() || 'A component') : undefined; + "development" !== 'production' ? warning(typeof inst.componentDidUnmount !== 'function', '%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', this.getName() || 'A component') : undefined; + "development" !== 'production' ? warning(typeof inst.componentWillRecieveProps !== 'function', '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', this.getName() || 'A component') : undefined; + } + + var initialState = inst.state; + if (initialState === undefined) { + inst.state = initialState = null; + } + !(typeof initialState === 'object' && !Array.isArray(initialState)) ? "development" !== 'production' ? invariant(false, '%s.state: must be set to an object or null', this.getName() || 'ReactCompositeComponent') : invariant(false) : undefined; + + this._pendingStateQueue = null; + this._pendingReplaceState = false; + this._pendingForceUpdate = false; + + if (inst.componentWillMount) { + inst.componentWillMount(); + // When mounting, calls to `setState` by `componentWillMount` will set + // `this._pendingStateQueue` without triggering a re-render. + if (this._pendingStateQueue) { + inst.state = this._processPendingState(inst.props, inst.context); + } + } + + // If not a stateless component, we now render + if (renderedElement === undefined) { + renderedElement = this._renderValidatedComponent(); + } + + this._renderedComponent = this._instantiateReactComponent(renderedElement); + + var markup = ReactReconciler.mountComponent(this._renderedComponent, rootID, transaction, this._processChildContext(context)); + if (inst.componentDidMount) { + transaction.getReactMountReady().enqueue(inst.componentDidMount, inst); + } + + return markup; + }, + + /** + * Releases any resources allocated by `mountComponent`. + * + * @final + * @internal + */ + unmountComponent: function () { + var inst = this._instance; + + if (inst.componentWillUnmount) { + inst.componentWillUnmount(); + } + + ReactReconciler.unmountComponent(this._renderedComponent); + this._renderedComponent = null; + this._instance = null; + + // Reset pending fields + // Even if this component is scheduled for another update in ReactUpdates, + // it would still be ignored because these fields are reset. + this._pendingStateQueue = null; + this._pendingReplaceState = false; + this._pendingForceUpdate = false; + this._pendingCallbacks = null; + this._pendingElement = null; + + // These fields do not really need to be reset since this object is no + // longer accessible. + this._context = null; + this._rootNodeID = null; + this._topLevelWrapper = null; + + // Delete the reference from the instance to this internal representation + // which allow the internals to be properly cleaned up even if the user + // leaks a reference to the public instance. + ReactInstanceMap.remove(inst); + + // Some existing components rely on inst.props even after they've been + // destroyed (in event handlers). + // TODO: inst.props = null; + // TODO: inst.state = null; + // TODO: inst.context = null; + }, + + /** + * Filters the context object to only contain keys specified in + * `contextTypes` + * + * @param {object} context + * @return {?object} + * @private + */ + _maskContext: function (context) { + var maskedContext = null; + var Component = this._currentElement.type; + var contextTypes = Component.contextTypes; + if (!contextTypes) { + return emptyObject; + } + maskedContext = {}; + for (var contextName in contextTypes) { + maskedContext[contextName] = context[contextName]; + } + return maskedContext; + }, + + /** + * Filters the context object to only contain keys specified in + * `contextTypes`, and asserts that they are valid. + * + * @param {object} context + * @return {?object} + * @private + */ + _processContext: function (context) { + var maskedContext = this._maskContext(context); + if ("development" !== 'production') { + var Component = this._currentElement.type; + if (Component.contextTypes) { + this._checkPropTypes(Component.contextTypes, maskedContext, ReactPropTypeLocations.context); + } + } + return maskedContext; + }, + + /** + * @param {object} currentContext + * @return {object} + * @private + */ + _processChildContext: function (currentContext) { + var Component = this._currentElement.type; + var inst = this._instance; + var childContext = inst.getChildContext && inst.getChildContext(); + if (childContext) { + !(typeof Component.childContextTypes === 'object') ? "development" !== 'production' ? invariant(false, '%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', this.getName() || 'ReactCompositeComponent') : invariant(false) : undefined; + if ("development" !== 'production') { + this._checkPropTypes(Component.childContextTypes, childContext, ReactPropTypeLocations.childContext); + } + for (var name in childContext) { + !(name in Component.childContextTypes) ? "development" !== 'production' ? invariant(false, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', this.getName() || 'ReactCompositeComponent', name) : invariant(false) : undefined; + } + return assign({}, currentContext, childContext); + } + return currentContext; + }, + + /** + * Processes props by setting default values for unspecified props and + * asserting that the props are valid. Does not mutate its argument; returns + * a new props object with defaults merged in. + * + * @param {object} newProps + * @return {object} + * @private + */ + _processProps: function (newProps) { + if ("development" !== 'production') { + var Component = this._currentElement.type; + if (Component.propTypes) { + this._checkPropTypes(Component.propTypes, newProps, ReactPropTypeLocations.prop); + } + } + return newProps; + }, + + /** + * Assert that the props are valid + * + * @param {object} propTypes Map of prop name to a ReactPropType + * @param {object} props + * @param {string} location e.g. "prop", "context", "child context" + * @private + */ + _checkPropTypes: function (propTypes, props, location) { + // TODO: Stop validating prop types here and only use the element + // validation. + var componentName = this.getName(); + for (var propName in propTypes) { + if (propTypes.hasOwnProperty(propName)) { + var error; + try { + // This is intentionally an invariant that gets caught. It's the same + // behavior as without this statement except with a better message. + !(typeof propTypes[propName] === 'function') ? "development" !== 'production' ? invariant(false, '%s: %s type `%s` is invalid; it must be a function, usually ' + 'from React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], propName) : invariant(false) : undefined; + error = propTypes[propName](props, propName, componentName, location); + } catch (ex) { + error = ex; + } + if (error instanceof Error) { + // We may want to extend this logic for similar errors in + // top-level render calls, so I'm abstracting it away into + // a function to minimize refactoring in the future + var addendum = getDeclarationErrorAddendum(this); + + if (location === ReactPropTypeLocations.prop) { + // Preface gives us something to blacklist in warning module + "development" !== 'production' ? warning(false, 'Failed Composite propType: %s%s', error.message, addendum) : undefined; + } else { + "development" !== 'production' ? warning(false, 'Failed Context Types: %s%s', error.message, addendum) : undefined; + } + } + } + } + }, + + receiveComponent: function (nextElement, transaction, nextContext) { + var prevElement = this._currentElement; + var prevContext = this._context; + + this._pendingElement = null; + + this.updateComponent(transaction, prevElement, nextElement, prevContext, nextContext); + }, + + /** + * If any of `_pendingElement`, `_pendingStateQueue`, or `_pendingForceUpdate` + * is set, update the component. + * + * @param {ReactReconcileTransaction} transaction + * @internal + */ + performUpdateIfNecessary: function (transaction) { + if (this._pendingElement != null) { + ReactReconciler.receiveComponent(this, this._pendingElement || this._currentElement, transaction, this._context); + } + + if (this._pendingStateQueue !== null || this._pendingForceUpdate) { + this.updateComponent(transaction, this._currentElement, this._currentElement, this._context, this._context); + } + }, + + /** + * Perform an update to a mounted component. The componentWillReceiveProps and + * shouldComponentUpdate methods are called, then (assuming the update isn't + * skipped) the remaining update lifecycle methods are called and the DOM + * representation is updated. + * + * By default, this implements React's rendering and reconciliation algorithm. + * Sophisticated clients may wish to override this. + * + * @param {ReactReconcileTransaction} transaction + * @param {ReactElement} prevParentElement + * @param {ReactElement} nextParentElement + * @internal + * @overridable + */ + updateComponent: function (transaction, prevParentElement, nextParentElement, prevUnmaskedContext, nextUnmaskedContext) { + var inst = this._instance; + + var nextContext = this._context === nextUnmaskedContext ? inst.context : this._processContext(nextUnmaskedContext); + var nextProps; + + // Distinguish between a props update versus a simple state update + if (prevParentElement === nextParentElement) { + // Skip checking prop types again -- we don't read inst.props to avoid + // warning for DOM component props in this upgrade + nextProps = nextParentElement.props; + } else { + nextProps = this._processProps(nextParentElement.props); + // An update here will schedule an update but immediately set + // _pendingStateQueue which will ensure that any state updates gets + // immediately reconciled instead of waiting for the next batch. + + if (inst.componentWillReceiveProps) { + inst.componentWillReceiveProps(nextProps, nextContext); + } + } + + var nextState = this._processPendingState(nextProps, nextContext); + + var shouldUpdate = this._pendingForceUpdate || !inst.shouldComponentUpdate || inst.shouldComponentUpdate(nextProps, nextState, nextContext); + + if ("development" !== 'production') { + "development" !== 'production' ? warning(typeof shouldUpdate !== 'undefined', '%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', this.getName() || 'ReactCompositeComponent') : undefined; + } + + if (shouldUpdate) { + this._pendingForceUpdate = false; + // Will set `this.props`, `this.state` and `this.context`. + this._performComponentUpdate(nextParentElement, nextProps, nextState, nextContext, transaction, nextUnmaskedContext); + } else { + // If it's determined that a component should not update, we still want + // to set props and state but we shortcut the rest of the update. + this._currentElement = nextParentElement; + this._context = nextUnmaskedContext; + inst.props = nextProps; + inst.state = nextState; + inst.context = nextContext; + } + }, + + _processPendingState: function (props, context) { + var inst = this._instance; + var queue = this._pendingStateQueue; + var replace = this._pendingReplaceState; + this._pendingReplaceState = false; + this._pendingStateQueue = null; + + if (!queue) { + return inst.state; + } + + if (replace && queue.length === 1) { + return queue[0]; + } + + var nextState = assign({}, replace ? queue[0] : inst.state); + for (var i = replace ? 1 : 0; i < queue.length; i++) { + var partial = queue[i]; + assign(nextState, typeof partial === 'function' ? partial.call(inst, nextState, props, context) : partial); + } + + return nextState; + }, + + /** + * Merges new props and state, notifies delegate methods of update and + * performs update. + * + * @param {ReactElement} nextElement Next element + * @param {object} nextProps Next public object to set as properties. + * @param {?object} nextState Next object to set as state. + * @param {?object} nextContext Next public object to set as context. + * @param {ReactReconcileTransaction} transaction + * @param {?object} unmaskedContext + * @private + */ + _performComponentUpdate: function (nextElement, nextProps, nextState, nextContext, transaction, unmaskedContext) { + var inst = this._instance; + + var hasComponentDidUpdate = Boolean(inst.componentDidUpdate); + var prevProps; + var prevState; + var prevContext; + if (hasComponentDidUpdate) { + prevProps = inst.props; + prevState = inst.state; + prevContext = inst.context; + } + + if (inst.componentWillUpdate) { + inst.componentWillUpdate(nextProps, nextState, nextContext); + } + + this._currentElement = nextElement; + this._context = unmaskedContext; + inst.props = nextProps; + inst.state = nextState; + inst.context = nextContext; + + this._updateRenderedComponent(transaction, unmaskedContext); + + if (hasComponentDidUpdate) { + transaction.getReactMountReady().enqueue(inst.componentDidUpdate.bind(inst, prevProps, prevState, prevContext), inst); + } + }, + + /** + * Call the component's `render` method and update the DOM accordingly. + * + * @param {ReactReconcileTransaction} transaction + * @internal + */ + _updateRenderedComponent: function (transaction, context) { + var prevComponentInstance = this._renderedComponent; + var prevRenderedElement = prevComponentInstance._currentElement; + var nextRenderedElement = this._renderValidatedComponent(); + if (shouldUpdateReactComponent(prevRenderedElement, nextRenderedElement)) { + ReactReconciler.receiveComponent(prevComponentInstance, nextRenderedElement, transaction, this._processChildContext(context)); + } else { + // These two IDs are actually the same! But nothing should rely on that. + var thisID = this._rootNodeID; + var prevComponentID = prevComponentInstance._rootNodeID; + ReactReconciler.unmountComponent(prevComponentInstance); + + this._renderedComponent = this._instantiateReactComponent(nextRenderedElement); + var nextMarkup = ReactReconciler.mountComponent(this._renderedComponent, thisID, transaction, this._processChildContext(context)); + this._replaceNodeWithMarkupByID(prevComponentID, nextMarkup); + } + }, + + /** + * @protected + */ + _replaceNodeWithMarkupByID: function (prevComponentID, nextMarkup) { + ReactComponentEnvironment.replaceNodeWithMarkupByID(prevComponentID, nextMarkup); + }, + + /** + * @protected + */ + _renderValidatedComponentWithoutOwnerOrContext: function () { + var inst = this._instance; + var renderedComponent = inst.render(); + if ("development" !== 'production') { + // We allow auto-mocks to proceed as if they're returning null. + if (typeof renderedComponent === 'undefined' && inst.render._isMockFunction) { + // This is probably bad practice. Consider warning here and + // deprecating this convenience. + renderedComponent = null; + } + } + + return renderedComponent; + }, + + /** + * @private + */ + _renderValidatedComponent: function () { + var renderedComponent; + ReactCurrentOwner.current = this; + try { + renderedComponent = this._renderValidatedComponentWithoutOwnerOrContext(); + } finally { + ReactCurrentOwner.current = null; + } + !( + // TODO: An `isValidNode` function would probably be more appropriate + renderedComponent === null || renderedComponent === false || ReactElement.isValidElement(renderedComponent)) ? "development" !== 'production' ? invariant(false, '%s.render(): A valid ReactComponent must be returned. You may have ' + 'returned undefined, an array or some other invalid object.', this.getName() || 'ReactCompositeComponent') : invariant(false) : undefined; + return renderedComponent; + }, + + /** + * Lazily allocates the refs object and stores `component` as `ref`. + * + * @param {string} ref Reference name. + * @param {component} component Component to store as `ref`. + * @final + * @private + */ + attachRef: function (ref, component) { + var inst = this.getPublicInstance(); + !(inst != null) ? "development" !== 'production' ? invariant(false, 'Stateless function components cannot have refs.') : invariant(false) : undefined; + var publicComponentInstance = component.getPublicInstance(); + if ("development" !== 'production') { + var componentName = component && component.getName ? component.getName() : 'a component'; + "development" !== 'production' ? warning(publicComponentInstance != null, 'Stateless function components cannot be given refs ' + '(See ref "%s" in %s created by %s). ' + 'Attempts to access this ref will fail.', ref, componentName, this.getName()) : undefined; + } + var refs = inst.refs === emptyObject ? inst.refs = {} : inst.refs; + refs[ref] = publicComponentInstance; + }, + + /** + * Detaches a reference name. + * + * @param {string} ref Name to dereference. + * @final + * @private + */ + detachRef: function (ref) { + var refs = this.getPublicInstance().refs; + delete refs[ref]; + }, + + /** + * Get a text description of the component that can be used to identify it + * in error messages. + * @return {string} The name or null. + * @internal + */ + getName: function () { + var type = this._currentElement.type; + var constructor = this._instance && this._instance.constructor; + return type.displayName || constructor && constructor.displayName || type.name || constructor && constructor.name || null; + }, + + /** + * Get the publicly accessible representation of this component - i.e. what + * is exposed by refs and returned by render. Can be null for stateless + * components. + * + * @return {ReactComponent} the public component instance. + * @internal + */ + getPublicInstance: function () { + var inst = this._instance; + if (inst instanceof StatelessComponent) { + return null; + } + return inst; + }, + + // Stub + _instantiateReactComponent: null + +}; + +ReactPerf.measureMethods(ReactCompositeComponentMixin, 'ReactCompositeComponent', { + mountComponent: 'mountComponent', + updateComponent: 'updateComponent', + _renderValidatedComponent: '_renderValidatedComponent' +}); + +var ReactCompositeComponent = { + + Mixin: ReactCompositeComponentMixin + +}; + +module.exports = ReactCompositeComponent; +},{"141":141,"154":154,"161":161,"173":173,"24":24,"36":36,"39":39,"57":57,"68":68,"78":78,"80":80,"81":81,"84":84,"95":95}],39:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactCurrentOwner + */ + +'use strict'; + +/** + * Keeps track of the current owner. + * + * The current owner is the component who should own any components that are + * currently being constructed. + */ +var ReactCurrentOwner = { + + /** + * @internal + * @type {ReactComponent} + */ + current: null + +}; + +module.exports = ReactCurrentOwner; +},{}],40:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactDOM + */ + +/* globals __REACT_DEVTOOLS_GLOBAL_HOOK__*/ + +'use strict'; + +var ReactCurrentOwner = _dereq_(39); +var ReactDOMTextComponent = _dereq_(51); +var ReactDefaultInjection = _dereq_(54); +var ReactInstanceHandles = _dereq_(67); +var ReactMount = _dereq_(72); +var ReactPerf = _dereq_(78); +var ReactReconciler = _dereq_(84); +var ReactUpdates = _dereq_(96); +var ReactVersion = _dereq_(97); + +var findDOMNode = _dereq_(122); +var renderSubtreeIntoContainer = _dereq_(137); +var warning = _dereq_(173); + +ReactDefaultInjection.inject(); + +var render = ReactPerf.measure('React', 'render', ReactMount.render); + +var React = { + findDOMNode: findDOMNode, + render: render, + unmountComponentAtNode: ReactMount.unmountComponentAtNode, + version: ReactVersion, + + /* eslint-disable camelcase */ + unstable_batchedUpdates: ReactUpdates.batchedUpdates, + unstable_renderSubtreeIntoContainer: renderSubtreeIntoContainer +}; + +// Inject the runtime into a devtools global hook regardless of browser. +// Allows for debugging when the hook is injected on the page. +/* eslint-enable camelcase */ +if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject === 'function') { + __REACT_DEVTOOLS_GLOBAL_HOOK__.inject({ + CurrentOwner: ReactCurrentOwner, + InstanceHandles: ReactInstanceHandles, + Mount: ReactMount, + Reconciler: ReactReconciler, + TextComponent: ReactDOMTextComponent + }); +} + +if ("development" !== 'production') { + var ExecutionEnvironment = _dereq_(147); + if (ExecutionEnvironment.canUseDOM && window.top === window.self) { + + // First check if devtools is not installed + if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') { + // If we're in Chrome or Firefox, provide a download link if not installed. + if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) { + console.debug('Download the React DevTools for a better development experience: ' + 'https://fb.me/react-devtools'); + } + } + + // If we're in IE8, check to see if we are in compatibility mode and provide + // information on preventing compatibility mode + var ieCompatibilityMode = document.documentMode && document.documentMode < 8; + + "development" !== 'production' ? warning(!ieCompatibilityMode, 'Internet Explorer is running in compatibility mode; please add the ' + 'following tag to your HTML to prevent this from happening: ' + '<meta http-equiv="X-UA-Compatible" content="IE=edge" />') : undefined; + + var expectedFeatures = [ + // shims + Array.isArray, Array.prototype.every, Array.prototype.forEach, Array.prototype.indexOf, Array.prototype.map, Date.now, Function.prototype.bind, Object.keys, String.prototype.split, String.prototype.trim, + + // shams + Object.create, Object.freeze]; + + for (var i = 0; i < expectedFeatures.length; i++) { + if (!expectedFeatures[i]) { + console.error('One or more ES5 shim/shams expected by React are not available: ' + 'https://fb.me/react-warning-polyfills'); + break; + } + } + } +} + +module.exports = React; +},{"122":122,"137":137,"147":147,"173":173,"39":39,"51":51,"54":54,"67":67,"72":72,"78":78,"84":84,"96":96,"97":97}],41:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactDOMButton + */ + +'use strict'; + +var mouseListenerNames = { + onClick: true, + onDoubleClick: true, + onMouseDown: true, + onMouseMove: true, + onMouseUp: true, + + onClickCapture: true, + onDoubleClickCapture: true, + onMouseDownCapture: true, + onMouseMoveCapture: true, + onMouseUpCapture: true +}; + +/** + * Implements a <button> native component that does not receive mouse events + * when `disabled` is set. + */ +var ReactDOMButton = { + getNativeProps: function (inst, props, context) { + if (!props.disabled) { + return props; + } + + // Copy the props, except the mouse listeners + var nativeProps = {}; + for (var key in props) { + if (props.hasOwnProperty(key) && !mouseListenerNames[key]) { + nativeProps[key] = props[key]; + } + } + + return nativeProps; + } +}; + +module.exports = ReactDOMButton; +},{}],42:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactDOMComponent + * @typechecks static-only + */ + +/* global hasOwnProperty:true */ + +'use strict'; + +var AutoFocusUtils = _dereq_(2); +var CSSPropertyOperations = _dereq_(5); +var DOMProperty = _dereq_(10); +var DOMPropertyOperations = _dereq_(11); +var EventConstants = _dereq_(15); +var ReactBrowserEventEmitter = _dereq_(28); +var ReactComponentBrowserEnvironment = _dereq_(35); +var ReactDOMButton = _dereq_(41); +var ReactDOMInput = _dereq_(46); +var ReactDOMOption = _dereq_(47); +var ReactDOMSelect = _dereq_(48); +var ReactDOMTextarea = _dereq_(52); +var ReactMount = _dereq_(72); +var ReactMultiChild = _dereq_(73); +var ReactPerf = _dereq_(78); +var ReactUpdateQueue = _dereq_(95); + +var assign = _dereq_(24); +var canDefineProperty = _dereq_(117); +var escapeTextContentForBrowser = _dereq_(121); +var invariant = _dereq_(161); +var isEventSupported = _dereq_(133); +var keyOf = _dereq_(166); +var setInnerHTML = _dereq_(138); +var setTextContent = _dereq_(139); +var shallowEqual = _dereq_(171); +var validateDOMNesting = _dereq_(144); +var warning = _dereq_(173); + +var deleteListener = ReactBrowserEventEmitter.deleteListener; +var listenTo = ReactBrowserEventEmitter.listenTo; +var registrationNameModules = ReactBrowserEventEmitter.registrationNameModules; + +// For quickly matching children type, to test if can be treated as content. +var CONTENT_TYPES = { 'string': true, 'number': true }; + +var CHILDREN = keyOf({ children: null }); +var STYLE = keyOf({ style: null }); +var HTML = keyOf({ __html: null }); + +var ELEMENT_NODE_TYPE = 1; + +function getDeclarationErrorAddendum(internalInstance) { + if (internalInstance) { + var owner = internalInstance._currentElement._owner || null; + if (owner) { + var name = owner.getName(); + if (name) { + return ' This DOM node was rendered by `' + name + '`.'; + } + } + } + return ''; +} + +var legacyPropsDescriptor; +if ("development" !== 'production') { + legacyPropsDescriptor = { + props: { + enumerable: false, + get: function () { + var component = this._reactInternalComponent; + "development" !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .props of a DOM node; instead, ' + 'recreate the props as `render` did originally or read the DOM ' + 'properties/attributes directly from this node (e.g., ' + 'this.refs.box.className).%s', getDeclarationErrorAddendum(component)) : undefined; + return component._currentElement.props; + } + } + }; +} + +function legacyGetDOMNode() { + if ("development" !== 'production') { + var component = this._reactInternalComponent; + "development" !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .getDOMNode() of a DOM node; ' + 'instead, use the node directly.%s', getDeclarationErrorAddendum(component)) : undefined; + } + return this; +} + +function legacyIsMounted() { + var component = this._reactInternalComponent; + if ("development" !== 'production') { + "development" !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .isMounted() of a DOM node.%s', getDeclarationErrorAddendum(component)) : undefined; + } + return !!component; +} + +function legacySetStateEtc() { + if ("development" !== 'production') { + var component = this._reactInternalComponent; + "development" !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .setState(), .replaceState(), or ' + '.forceUpdate() of a DOM node. This is a no-op.%s', getDeclarationErrorAddendum(component)) : undefined; + } +} + +function legacySetProps(partialProps, callback) { + var component = this._reactInternalComponent; + if ("development" !== 'production') { + "development" !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .setProps() of a DOM node. ' + 'Instead, call ReactDOM.render again at the top level.%s', getDeclarationErrorAddendum(component)) : undefined; + } + if (!component) { + return; + } + ReactUpdateQueue.enqueueSetPropsInternal(component, partialProps); + if (callback) { + ReactUpdateQueue.enqueueCallbackInternal(component, callback); + } +} + +function legacyReplaceProps(partialProps, callback) { + var component = this._reactInternalComponent; + if ("development" !== 'production') { + "development" !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .replaceProps() of a DOM node. ' + 'Instead, call ReactDOM.render again at the top level.%s', getDeclarationErrorAddendum(component)) : undefined; + } + if (!component) { + return; + } + ReactUpdateQueue.enqueueReplacePropsInternal(component, partialProps); + if (callback) { + ReactUpdateQueue.enqueueCallbackInternal(component, callback); + } +} + +function friendlyStringify(obj) { + if (typeof obj === 'object') { + if (Array.isArray(obj)) { + return '[' + obj.map(friendlyStringify).join(', ') + ']'; + } else { + var pairs = []; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var keyEscaped = /^[a-z$_][\w$_]*$/i.test(key) ? key : JSON.stringify(key); + pairs.push(keyEscaped + ': ' + friendlyStringify(obj[key])); + } + } + return '{' + pairs.join(', ') + '}'; + } + } else if (typeof obj === 'string') { + return JSON.stringify(obj); + } else if (typeof obj === 'function') { + return '[function object]'; + } + // Differs from JSON.stringify in that undefined becauses undefined and that + // inf and nan don't become null + return String(obj); +} + +var styleMutationWarning = {}; + +function checkAndWarnForMutatedStyle(style1, style2, component) { + if (style1 == null || style2 == null) { + return; + } + if (shallowEqual(style1, style2)) { + return; + } + + var componentName = component._tag; + var owner = component._currentElement._owner; + var ownerName; + if (owner) { + ownerName = owner.getName(); + } + + var hash = ownerName + '|' + componentName; + + if (styleMutationWarning.hasOwnProperty(hash)) { + return; + } + + styleMutationWarning[hash] = true; + + "development" !== 'production' ? warning(false, '`%s` was passed a style object that has previously been mutated. ' + 'Mutating `style` is deprecated. Consider cloning it beforehand. Check ' + 'the `render` %s. Previous style: %s. Mutated style: %s.', componentName, owner ? 'of `' + ownerName + '`' : 'using <' + componentName + '>', friendlyStringify(style1), friendlyStringify(style2)) : undefined; +} + +/** + * @param {object} component + * @param {?object} props + */ +function assertValidProps(component, props) { + if (!props) { + return; + } + // Note the use of `==` which checks for null or undefined. + if ("development" !== 'production') { + if (voidElementTags[component._tag]) { + "development" !== 'production' ? warning(props.children == null && props.dangerouslySetInnerHTML == null, '%s is a void element tag and must not have `children` or ' + 'use `props.dangerouslySetInnerHTML`.%s', component._tag, component._currentElement._owner ? ' Check the render method of ' + component._currentElement._owner.getName() + '.' : '') : undefined; + } + } + if (props.dangerouslySetInnerHTML != null) { + !(props.children == null) ? "development" !== 'production' ? invariant(false, 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.') : invariant(false) : undefined; + !(typeof props.dangerouslySetInnerHTML === 'object' && HTML in props.dangerouslySetInnerHTML) ? "development" !== 'production' ? invariant(false, '`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' + 'Please visit https://fb.me/react-invariant-dangerously-set-inner-html ' + 'for more information.') : invariant(false) : undefined; + } + if ("development" !== 'production') { + "development" !== 'production' ? warning(props.innerHTML == null, 'Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.') : undefined; + "development" !== 'production' ? warning(!props.contentEditable || props.children == null, 'A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of ' + 'those nodes are unexpectedly modified or duplicated. This is ' + 'probably not intentional.') : undefined; + } + !(props.style == null || typeof props.style === 'object') ? "development" !== 'production' ? invariant(false, 'The `style` prop expects a mapping from style properties to values, ' + 'not a string. For example, style={{marginRight: spacing + \'em\'}} when ' + 'using JSX.%s', getDeclarationErrorAddendum(component)) : invariant(false) : undefined; +} + +function enqueuePutListener(id, registrationName, listener, transaction) { + if ("development" !== 'production') { + // IE8 has no API for event capturing and the `onScroll` event doesn't + // bubble. + "development" !== 'production' ? warning(registrationName !== 'onScroll' || isEventSupported('scroll', true), 'This browser doesn\'t support the `onScroll` event') : undefined; + } + var container = ReactMount.findReactContainerForID(id); + if (container) { + var doc = container.nodeType === ELEMENT_NODE_TYPE ? container.ownerDocument : container; + listenTo(registrationName, doc); + } + transaction.getReactMountReady().enqueue(putListener, { + id: id, + registrationName: registrationName, + listener: listener + }); +} + +function putListener() { + var listenerToPut = this; + ReactBrowserEventEmitter.putListener(listenerToPut.id, listenerToPut.registrationName, listenerToPut.listener); +} + +// There are so many media events, it makes sense to just +// maintain a list rather than create a `trapBubbledEvent` for each +var mediaEvents = { + topAbort: 'abort', + topCanPlay: 'canplay', + topCanPlayThrough: 'canplaythrough', + topDurationChange: 'durationchange', + topEmptied: 'emptied', + topEncrypted: 'encrypted', + topEnded: 'ended', + topError: 'error', + topLoadedData: 'loadeddata', + topLoadedMetadata: 'loadedmetadata', + topLoadStart: 'loadstart', + topPause: 'pause', + topPlay: 'play', + topPlaying: 'playing', + topProgress: 'progress', + topRateChange: 'ratechange', + topSeeked: 'seeked', + topSeeking: 'seeking', + topStalled: 'stalled', + topSuspend: 'suspend', + topTimeUpdate: 'timeupdate', + topVolumeChange: 'volumechange', + topWaiting: 'waiting' +}; + +function trapBubbledEventsLocal() { + var inst = this; + // If a component renders to null or if another component fatals and causes + // the state of the tree to be corrupted, `node` here can be null. + !inst._rootNodeID ? "development" !== 'production' ? invariant(false, 'Must be mounted to trap events') : invariant(false) : undefined; + var node = ReactMount.getNode(inst._rootNodeID); + !node ? "development" !== 'production' ? invariant(false, 'trapBubbledEvent(...): Requires node to be rendered.') : invariant(false) : undefined; + + switch (inst._tag) { + case 'iframe': + inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, 'load', node)]; + break; + case 'video': + case 'audio': + + inst._wrapperState.listeners = []; + // create listener for each media event + for (var event in mediaEvents) { + if (mediaEvents.hasOwnProperty(event)) { + inst._wrapperState.listeners.push(ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes[event], mediaEvents[event], node)); + } + } + + break; + case 'img': + inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topError, 'error', node), ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, 'load', node)]; + break; + case 'form': + inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topReset, 'reset', node), ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topSubmit, 'submit', node)]; + break; + } +} + +function mountReadyInputWrapper() { + ReactDOMInput.mountReadyWrapper(this); +} + +function postUpdateSelectWrapper() { + ReactDOMSelect.postUpdateWrapper(this); +} + +// For HTML, certain tags should omit their close tag. We keep a whitelist for +// those special cased tags. + +var omittedCloseTags = { + 'area': true, + 'base': true, + 'br': true, + 'col': true, + 'embed': true, + 'hr': true, + 'img': true, + 'input': true, + 'keygen': true, + 'link': true, + 'meta': true, + 'param': true, + 'source': true, + 'track': true, + 'wbr': true +}; + +// NOTE: menuitem's close tag should be omitted, but that causes problems. +var newlineEatingTags = { + 'listing': true, + 'pre': true, + 'textarea': true +}; + +// For HTML, certain tags cannot have children. This has the same purpose as +// `omittedCloseTags` except that `menuitem` should still have its closing tag. + +var voidElementTags = assign({ + 'menuitem': true +}, omittedCloseTags); + +// We accept any tag to be rendered but since this gets injected into arbitrary +// HTML, we want to make sure that it's a safe tag. +// http://www.w3.org/TR/REC-xml/#NT-Name + +var VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset +var validatedTagCache = {}; +var hasOwnProperty = ({}).hasOwnProperty; + +function validateDangerousTag(tag) { + if (!hasOwnProperty.call(validatedTagCache, tag)) { + !VALID_TAG_REGEX.test(tag) ? "development" !== 'production' ? invariant(false, 'Invalid tag: %s', tag) : invariant(false) : undefined; + validatedTagCache[tag] = true; + } +} + +function processChildContextDev(context, inst) { + // Pass down our tag name to child components for validation purposes + context = assign({}, context); + var info = context[validateDOMNesting.ancestorInfoContextKey]; + context[validateDOMNesting.ancestorInfoContextKey] = validateDOMNesting.updatedAncestorInfo(info, inst._tag, inst); + return context; +} + +function isCustomComponent(tagName, props) { + return tagName.indexOf('-') >= 0 || props.is != null; +} + +/** + * Creates a new React class that is idempotent and capable of containing other + * React components. It accepts event listeners and DOM properties that are + * valid according to `DOMProperty`. + * + * - Event listeners: `onClick`, `onMouseDown`, etc. + * - DOM properties: `className`, `name`, `title`, etc. + * + * The `style` property functions differently from the DOM API. It accepts an + * object mapping of style properties to values. + * + * @constructor ReactDOMComponent + * @extends ReactMultiChild + */ +function ReactDOMComponent(tag) { + validateDangerousTag(tag); + this._tag = tag.toLowerCase(); + this._renderedChildren = null; + this._previousStyle = null; + this._previousStyleCopy = null; + this._rootNodeID = null; + this._wrapperState = null; + this._topLevelWrapper = null; + this._nodeWithLegacyProperties = null; + if ("development" !== 'production') { + this._unprocessedContextDev = null; + this._processedContextDev = null; + } +} + +ReactDOMComponent.displayName = 'ReactDOMComponent'; + +ReactDOMComponent.Mixin = { + + construct: function (element) { + this._currentElement = element; + }, + + /** + * Generates root tag markup then recurses. This method has side effects and + * is not idempotent. + * + * @internal + * @param {string} rootID The root DOM ID for this node. + * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction + * @param {object} context + * @return {string} The computed markup. + */ + mountComponent: function (rootID, transaction, context) { + this._rootNodeID = rootID; + + var props = this._currentElement.props; + + switch (this._tag) { + case 'iframe': + case 'img': + case 'form': + case 'video': + case 'audio': + this._wrapperState = { + listeners: null + }; + transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); + break; + case 'button': + props = ReactDOMButton.getNativeProps(this, props, context); + break; + case 'input': + ReactDOMInput.mountWrapper(this, props, context); + props = ReactDOMInput.getNativeProps(this, props, context); + break; + case 'option': + ReactDOMOption.mountWrapper(this, props, context); + props = ReactDOMOption.getNativeProps(this, props, context); + break; + case 'select': + ReactDOMSelect.mountWrapper(this, props, context); + props = ReactDOMSelect.getNativeProps(this, props, context); + context = ReactDOMSelect.processChildContext(this, props, context); + break; + case 'textarea': + ReactDOMTextarea.mountWrapper(this, props, context); + props = ReactDOMTextarea.getNativeProps(this, props, context); + break; + } + + assertValidProps(this, props); + if ("development" !== 'production') { + if (context[validateDOMNesting.ancestorInfoContextKey]) { + validateDOMNesting(this._tag, this, context[validateDOMNesting.ancestorInfoContextKey]); + } + } + + if ("development" !== 'production') { + this._unprocessedContextDev = context; + this._processedContextDev = processChildContextDev(context, this); + context = this._processedContextDev; + } + + var mountImage; + if (transaction.useCreateElement) { + var ownerDocument = context[ReactMount.ownerDocumentContextKey]; + var el = ownerDocument.createElementNS('http://www.w3.org/1999/xhtml', this._currentElement.type); + DOMPropertyOperations.setAttributeForID(el, this._rootNodeID); + // Populate node cache + ReactMount.getID(el); + this._updateDOMProperties({}, props, transaction, el); + this._createInitialChildren(transaction, props, context, el); + mountImage = el; + } else { + var tagOpen = this._createOpenTagMarkupAndPutListeners(transaction, props); + var tagContent = this._createContentMarkup(transaction, props, context); + if (!tagContent && omittedCloseTags[this._tag]) { + mountImage = tagOpen + '/>'; + } else { + mountImage = tagOpen + '>' + tagContent + '</' + this._currentElement.type + '>'; + } + } + + switch (this._tag) { + case 'input': + transaction.getReactMountReady().enqueue(mountReadyInputWrapper, this); + // falls through + case 'button': + case 'select': + case 'textarea': + if (props.autoFocus) { + transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this); + } + break; + } + + return mountImage; + }, + + /** + * Creates markup for the open tag and all attributes. + * + * This method has side effects because events get registered. + * + * Iterating over object properties is faster than iterating over arrays. + * @see http://jsperf.com/obj-vs-arr-iteration + * + * @private + * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction + * @param {object} props + * @return {string} Markup of opening tag. + */ + _createOpenTagMarkupAndPutListeners: function (transaction, props) { + var ret = '<' + this._currentElement.type; + + for (var propKey in props) { + if (!props.hasOwnProperty(propKey)) { + continue; + } + var propValue = props[propKey]; + if (propValue == null) { + continue; + } + if (registrationNameModules.hasOwnProperty(propKey)) { + if (propValue) { + enqueuePutListener(this._rootNodeID, propKey, propValue, transaction); + } + } else { + if (propKey === STYLE) { + if (propValue) { + if ("development" !== 'production') { + // See `_updateDOMProperties`. style block + this._previousStyle = propValue; + } + propValue = this._previousStyleCopy = assign({}, props.style); + } + propValue = CSSPropertyOperations.createMarkupForStyles(propValue); + } + var markup = null; + if (this._tag != null && isCustomComponent(this._tag, props)) { + if (propKey !== CHILDREN) { + markup = DOMPropertyOperations.createMarkupForCustomAttribute(propKey, propValue); + } + } else { + markup = DOMPropertyOperations.createMarkupForProperty(propKey, propValue); + } + if (markup) { + ret += ' ' + markup; + } + } + } + + // For static pages, no need to put React ID and checksum. Saves lots of + // bytes. + if (transaction.renderToStaticMarkup) { + return ret; + } + + var markupForID = DOMPropertyOperations.createMarkupForID(this._rootNodeID); + return ret + ' ' + markupForID; + }, + + /** + * Creates markup for the content between the tags. + * + * @private + * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction + * @param {object} props + * @param {object} context + * @return {string} Content markup. + */ + _createContentMarkup: function (transaction, props, context) { + var ret = ''; + + // Intentional use of != to avoid catching zero/false. + var innerHTML = props.dangerouslySetInnerHTML; + if (innerHTML != null) { + if (innerHTML.__html != null) { + ret = innerHTML.__html; + } + } else { + var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null; + var childrenToUse = contentToUse != null ? null : props.children; + if (contentToUse != null) { + // TODO: Validate that text is allowed as a child of this node + ret = escapeTextContentForBrowser(contentToUse); + } else if (childrenToUse != null) { + var mountImages = this.mountChildren(childrenToUse, transaction, context); + ret = mountImages.join(''); + } + } + if (newlineEatingTags[this._tag] && ret.charAt(0) === '\n') { + // text/html ignores the first character in these tags if it's a newline + // Prefer to break application/xml over text/html (for now) by adding + // a newline specifically to get eaten by the parser. (Alternately for + // textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first + // \r is normalized out by HTMLTextAreaElement#value.) + // See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre> + // See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions> + // See: <http://www.w3.org/TR/html5/syntax.html#newlines> + // See: Parsing of "textarea" "listing" and "pre" elements + // from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody> + return '\n' + ret; + } else { + return ret; + } + }, + + _createInitialChildren: function (transaction, props, context, el) { + // Intentional use of != to avoid catching zero/false. + var innerHTML = props.dangerouslySetInnerHTML; + if (innerHTML != null) { + if (innerHTML.__html != null) { + setInnerHTML(el, innerHTML.__html); + } + } else { + var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null; + var childrenToUse = contentToUse != null ? null : props.children; + if (contentToUse != null) { + // TODO: Validate that text is allowed as a child of this node + setTextContent(el, contentToUse); + } else if (childrenToUse != null) { + var mountImages = this.mountChildren(childrenToUse, transaction, context); + for (var i = 0; i < mountImages.length; i++) { + el.appendChild(mountImages[i]); + } + } + } + }, + + /** + * Receives a next element and updates the component. + * + * @internal + * @param {ReactElement} nextElement + * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction + * @param {object} context + */ + receiveComponent: function (nextElement, transaction, context) { + var prevElement = this._currentElement; + this._currentElement = nextElement; + this.updateComponent(transaction, prevElement, nextElement, context); + }, + + /** + * Updates a native DOM component after it has already been allocated and + * attached to the DOM. Reconciles the root DOM node, then recurses. + * + * @param {ReactReconcileTransaction} transaction + * @param {ReactElement} prevElement + * @param {ReactElement} nextElement + * @internal + * @overridable + */ + updateComponent: function (transaction, prevElement, nextElement, context) { + var lastProps = prevElement.props; + var nextProps = this._currentElement.props; + + switch (this._tag) { + case 'button': + lastProps = ReactDOMButton.getNativeProps(this, lastProps); + nextProps = ReactDOMButton.getNativeProps(this, nextProps); + break; + case 'input': + ReactDOMInput.updateWrapper(this); + lastProps = ReactDOMInput.getNativeProps(this, lastProps); + nextProps = ReactDOMInput.getNativeProps(this, nextProps); + break; + case 'option': + lastProps = ReactDOMOption.getNativeProps(this, lastProps); + nextProps = ReactDOMOption.getNativeProps(this, nextProps); + break; + case 'select': + lastProps = ReactDOMSelect.getNativeProps(this, lastProps); + nextProps = ReactDOMSelect.getNativeProps(this, nextProps); + break; + case 'textarea': + ReactDOMTextarea.updateWrapper(this); + lastProps = ReactDOMTextarea.getNativeProps(this, lastProps); + nextProps = ReactDOMTextarea.getNativeProps(this, nextProps); + break; + } + + if ("development" !== 'production') { + // If the context is reference-equal to the old one, pass down the same + // processed object so the update bailout in ReactReconciler behaves + // correctly (and identically in dev and prod). See #5005. + if (this._unprocessedContextDev !== context) { + this._unprocessedContextDev = context; + this._processedContextDev = processChildContextDev(context, this); + } + context = this._processedContextDev; + } + + assertValidProps(this, nextProps); + this._updateDOMProperties(lastProps, nextProps, transaction, null); + this._updateDOMChildren(lastProps, nextProps, transaction, context); + + if (!canDefineProperty && this._nodeWithLegacyProperties) { + this._nodeWithLegacyProperties.props = nextProps; + } + + if (this._tag === 'select') { + // <select> value update needs to occur after <option> children + // reconciliation + transaction.getReactMountReady().enqueue(postUpdateSelectWrapper, this); + } + }, + + /** + * Reconciles the properties by detecting differences in property values and + * updating the DOM as necessary. This function is probably the single most + * critical path for performance optimization. + * + * TODO: Benchmark whether checking for changed values in memory actually + * improves performance (especially statically positioned elements). + * TODO: Benchmark the effects of putting this at the top since 99% of props + * do not change for a given reconciliation. + * TODO: Benchmark areas that can be improved with caching. + * + * @private + * @param {object} lastProps + * @param {object} nextProps + * @param {ReactReconcileTransaction} transaction + * @param {?DOMElement} node + */ + _updateDOMProperties: function (lastProps, nextProps, transaction, node) { + var propKey; + var styleName; + var styleUpdates; + for (propKey in lastProps) { + if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey)) { + continue; + } + if (propKey === STYLE) { + var lastStyle = this._previousStyleCopy; + for (styleName in lastStyle) { + if (lastStyle.hasOwnProperty(styleName)) { + styleUpdates = styleUpdates || {}; + styleUpdates[styleName] = ''; + } + } + this._previousStyleCopy = null; + } else if (registrationNameModules.hasOwnProperty(propKey)) { + if (lastProps[propKey]) { + // Only call deleteListener if there was a listener previously or + // else willDeleteListener gets called when there wasn't actually a + // listener (e.g., onClick={null}) + deleteListener(this._rootNodeID, propKey); + } + } else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) { + if (!node) { + node = ReactMount.getNode(this._rootNodeID); + } + DOMPropertyOperations.deleteValueForProperty(node, propKey); + } + } + for (propKey in nextProps) { + var nextProp = nextProps[propKey]; + var lastProp = propKey === STYLE ? this._previousStyleCopy : lastProps[propKey]; + if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp) { + continue; + } + if (propKey === STYLE) { + if (nextProp) { + if ("development" !== 'production') { + checkAndWarnForMutatedStyle(this._previousStyleCopy, this._previousStyle, this); + this._previousStyle = nextProp; + } + nextProp = this._previousStyleCopy = assign({}, nextProp); + } else { + this._previousStyleCopy = null; + } + if (lastProp) { + // Unset styles on `lastProp` but not on `nextProp`. + for (styleName in lastProp) { + if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) { + styleUpdates = styleUpdates || {}; + styleUpdates[styleName] = ''; + } + } + // Update styles that changed since `lastProp`. + for (styleName in nextProp) { + if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) { + styleUpdates = styleUpdates || {}; + styleUpdates[styleName] = nextProp[styleName]; + } + } + } else { + // Relies on `updateStylesByID` not mutating `styleUpdates`. + styleUpdates = nextProp; + } + } else if (registrationNameModules.hasOwnProperty(propKey)) { + if (nextProp) { + enqueuePutListener(this._rootNodeID, propKey, nextProp, transaction); + } else if (lastProp) { + deleteListener(this._rootNodeID, propKey); + } + } else if (isCustomComponent(this._tag, nextProps)) { + if (!node) { + node = ReactMount.getNode(this._rootNodeID); + } + if (propKey === CHILDREN) { + nextProp = null; + } + DOMPropertyOperations.setValueForAttribute(node, propKey, nextProp); + } else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) { + if (!node) { + node = ReactMount.getNode(this._rootNodeID); + } + // If we're updating to null or undefined, we should remove the property + // from the DOM node instead of inadvertantly setting to a string. This + // brings us in line with the same behavior we have on initial render. + if (nextProp != null) { + DOMPropertyOperations.setValueForProperty(node, propKey, nextProp); + } else { + DOMPropertyOperations.deleteValueForProperty(node, propKey); + } + } + } + if (styleUpdates) { + if (!node) { + node = ReactMount.getNode(this._rootNodeID); + } + CSSPropertyOperations.setValueForStyles(node, styleUpdates); + } + }, + + /** + * Reconciles the children with the various properties that affect the + * children content. + * + * @param {object} lastProps + * @param {object} nextProps + * @param {ReactReconcileTransaction} transaction + * @param {object} context + */ + _updateDOMChildren: function (lastProps, nextProps, transaction, context) { + var lastContent = CONTENT_TYPES[typeof lastProps.children] ? lastProps.children : null; + var nextContent = CONTENT_TYPES[typeof nextProps.children] ? nextProps.children : null; + + var lastHtml = lastProps.dangerouslySetInnerHTML && lastProps.dangerouslySetInnerHTML.__html; + var nextHtml = nextProps.dangerouslySetInnerHTML && nextProps.dangerouslySetInnerHTML.__html; + + // Note the use of `!=` which checks for null or undefined. + var lastChildren = lastContent != null ? null : lastProps.children; + var nextChildren = nextContent != null ? null : nextProps.children; + + // 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, context); + } else if (lastHasContentOrHtml && !nextHasContentOrHtml) { + this.updateTextContent(''); + } + + if (nextContent != null) { + if (lastContent !== nextContent) { + this.updateTextContent('' + nextContent); + } + } else if (nextHtml != null) { + if (lastHtml !== nextHtml) { + this.updateMarkup('' + nextHtml); + } + } else if (nextChildren != null) { + this.updateChildren(nextChildren, transaction, context); + } + }, + + /** + * Destroys all event registrations for this instance. Does not remove from + * the DOM. That must be done by the parent. + * + * @internal + */ + unmountComponent: function () { + switch (this._tag) { + case 'iframe': + case 'img': + case 'form': + case 'video': + case 'audio': + var listeners = this._wrapperState.listeners; + if (listeners) { + for (var i = 0; i < listeners.length; i++) { + listeners[i].remove(); + } + } + break; + case 'input': + ReactDOMInput.unmountWrapper(this); + break; + case 'html': + case 'head': + case 'body': + /** + * Components like <html> <head> and <body> can't be removed or added + * easily in a cross-browser way, however it's valuable to be able to + * take advantage of React's reconciliation for styling and <title> + * management. So we just document it and throw in dangerous cases. + */ + !false ? "development" !== 'production' ? invariant(false, '<%s> tried to unmount. Because of cross-browser quirks it is ' + 'impossible to unmount some top-level components (eg <html>, ' + '<head>, and <body>) reliably and efficiently. To fix this, have a ' + 'single top-level component that never unmounts render these ' + 'elements.', this._tag) : invariant(false) : undefined; + break; + } + + this.unmountChildren(); + ReactBrowserEventEmitter.deleteAllListeners(this._rootNodeID); + ReactComponentBrowserEnvironment.unmountIDFromEnvironment(this._rootNodeID); + this._rootNodeID = null; + this._wrapperState = null; + if (this._nodeWithLegacyProperties) { + var node = this._nodeWithLegacyProperties; + node._reactInternalComponent = null; + this._nodeWithLegacyProperties = null; + } + }, + + getPublicInstance: function () { + if (!this._nodeWithLegacyProperties) { + var node = ReactMount.getNode(this._rootNodeID); + + node._reactInternalComponent = this; + node.getDOMNode = legacyGetDOMNode; + node.isMounted = legacyIsMounted; + node.setState = legacySetStateEtc; + node.replaceState = legacySetStateEtc; + node.forceUpdate = legacySetStateEtc; + node.setProps = legacySetProps; + node.replaceProps = legacyReplaceProps; + + if ("development" !== 'production') { + if (canDefineProperty) { + Object.defineProperties(node, legacyPropsDescriptor); + } else { + // updateComponent will update this property on subsequent renders + node.props = this._currentElement.props; + } + } else { + // updateComponent will update this property on subsequent renders + node.props = this._currentElement.props; + } + + this._nodeWithLegacyProperties = node; + } + return this._nodeWithLegacyProperties; + } + +}; + +ReactPerf.measureMethods(ReactDOMComponent, 'ReactDOMComponent', { + mountComponent: 'mountComponent', + updateComponent: 'updateComponent' +}); + +assign(ReactDOMComponent.prototype, ReactDOMComponent.Mixin, ReactMultiChild.Mixin); + +module.exports = ReactDOMComponent; +},{"10":10,"11":11,"117":117,"121":121,"133":133,"138":138,"139":139,"144":144,"15":15,"161":161,"166":166,"171":171,"173":173,"2":2,"24":24,"28":28,"35":35,"41":41,"46":46,"47":47,"48":48,"5":5,"52":52,"72":72,"73":73,"78":78,"95":95}],43:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactDOMFactories + * @typechecks static-only + */ + +'use strict'; + +var ReactElement = _dereq_(57); +var ReactElementValidator = _dereq_(58); + +var mapObject = _dereq_(167); + +/** + * Create a factory that creates HTML tag elements. + * + * @param {string} tag Tag name (e.g. `div`). + * @private + */ +function createDOMFactory(tag) { + if ("development" !== 'production') { + return ReactElementValidator.createFactory(tag); + } + return ReactElement.createFactory(tag); +} + +/** + * Creates a mapping from supported HTML tags to `ReactDOMComponent` classes. + * This is also accessible via `React.DOM`. + * + * @public + */ +var ReactDOMFactories = mapObject({ + a: 'a', + abbr: 'abbr', + address: 'address', + area: 'area', + article: 'article', + aside: 'aside', + audio: 'audio', + b: 'b', + base: 'base', + bdi: 'bdi', + bdo: 'bdo', + big: 'big', + blockquote: 'blockquote', + body: 'body', + br: 'br', + button: 'button', + canvas: 'canvas', + caption: 'caption', + cite: 'cite', + code: 'code', + col: 'col', + colgroup: 'colgroup', + data: 'data', + datalist: 'datalist', + dd: 'dd', + del: 'del', + details: 'details', + dfn: 'dfn', + dialog: 'dialog', + div: 'div', + dl: 'dl', + dt: 'dt', + em: 'em', + embed: 'embed', + fieldset: 'fieldset', + figcaption: 'figcaption', + figure: 'figure', + footer: 'footer', + form: 'form', + h1: 'h1', + h2: 'h2', + h3: 'h3', + h4: 'h4', + h5: 'h5', + h6: 'h6', + head: 'head', + header: 'header', + hgroup: 'hgroup', + hr: 'hr', + html: 'html', + i: 'i', + iframe: 'iframe', + img: 'img', + input: 'input', + ins: 'ins', + kbd: 'kbd', + keygen: 'keygen', + label: 'label', + legend: 'legend', + li: 'li', + link: 'link', + main: 'main', + map: 'map', + mark: 'mark', + menu: 'menu', + menuitem: 'menuitem', + meta: 'meta', + meter: 'meter', + nav: 'nav', + noscript: 'noscript', + object: 'object', + ol: 'ol', + optgroup: 'optgroup', + option: 'option', + output: 'output', + p: 'p', + param: 'param', + picture: 'picture', + pre: 'pre', + progress: 'progress', + q: 'q', + rp: 'rp', + rt: 'rt', + ruby: 'ruby', + s: 's', + samp: 'samp', + script: 'script', + section: 'section', + select: 'select', + small: 'small', + source: 'source', + span: 'span', + strong: 'strong', + style: 'style', + sub: 'sub', + summary: 'summary', + sup: 'sup', + table: 'table', + tbody: 'tbody', + td: 'td', + textarea: 'textarea', + tfoot: 'tfoot', + th: 'th', + thead: 'thead', + time: 'time', + title: 'title', + tr: 'tr', + track: 'track', + u: 'u', + ul: 'ul', + 'var': 'var', + video: 'video', + wbr: 'wbr', + + // SVG + circle: 'circle', + clipPath: 'clipPath', + defs: 'defs', + ellipse: 'ellipse', + g: 'g', + image: 'image', + line: 'line', + linearGradient: 'linearGradient', + mask: 'mask', + path: 'path', + pattern: 'pattern', + polygon: 'polygon', + polyline: 'polyline', + radialGradient: 'radialGradient', + rect: 'rect', + stop: 'stop', + svg: 'svg', + text: 'text', + tspan: 'tspan' + +}, createDOMFactory); + +module.exports = ReactDOMFactories; +},{"167":167,"57":57,"58":58}],44:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactDOMFeatureFlags + */ + +'use strict'; + +var ReactDOMFeatureFlags = { + useCreateElement: false +}; + +module.exports = ReactDOMFeatureFlags; +},{}],45:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactDOMIDOperations + * @typechecks static-only + */ + +'use strict'; + +var DOMChildrenOperations = _dereq_(9); +var DOMPropertyOperations = _dereq_(11); +var ReactMount = _dereq_(72); +var ReactPerf = _dereq_(78); + +var invariant = _dereq_(161); + +/** + * Errors for properties that should not be updated with `updatePropertyByID()`. + * + * @type {object} + * @private + */ +var INVALID_PROPERTY_ERRORS = { + dangerouslySetInnerHTML: '`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.', + style: '`style` must be set using `updateStylesByID()`.' +}; + +/** + * Operations used to process updates to DOM nodes. + */ +var ReactDOMIDOperations = { + + /** + * Updates a DOM node with new property values. This should only be used to + * update DOM properties in `DOMProperty`. + * + * @param {string} id ID of the node to update. + * @param {string} name A valid property name, see `DOMProperty`. + * @param {*} value New value of the property. + * @internal + */ + updatePropertyByID: function (id, name, value) { + var node = ReactMount.getNode(id); + !!INVALID_PROPERTY_ERRORS.hasOwnProperty(name) ? "development" !== 'production' ? invariant(false, 'updatePropertyByID(...): %s', INVALID_PROPERTY_ERRORS[name]) : invariant(false) : undefined; + + // If we're updating to null or undefined, we should remove the property + // from the DOM node instead of inadvertantly setting to a string. This + // brings us in line with the same behavior we have on initial render. + if (value != null) { + DOMPropertyOperations.setValueForProperty(node, name, value); + } else { + DOMPropertyOperations.deleteValueForProperty(node, name); + } + }, + + /** + * Replaces a DOM node that exists in the document with markup. + * + * @param {string} id ID of child to be replaced. + * @param {string} markup Dangerous markup to inject in place of child. + * @internal + * @see {Danger.dangerouslyReplaceNodeWithMarkup} + */ + dangerouslyReplaceNodeWithMarkupByID: function (id, markup) { + var node = ReactMount.getNode(id); + DOMChildrenOperations.dangerouslyReplaceNodeWithMarkup(node, markup); + }, + + /** + * Updates a component's children by processing a series of updates. + * + * @param {array<object>} updates List of update configurations. + * @param {array<string>} markup List of markup strings. + * @internal + */ + dangerouslyProcessChildrenUpdates: function (updates, markup) { + for (var i = 0; i < updates.length; i++) { + updates[i].parentNode = ReactMount.getNode(updates[i].parentID); + } + DOMChildrenOperations.processUpdates(updates, markup); + } +}; + +ReactPerf.measureMethods(ReactDOMIDOperations, 'ReactDOMIDOperations', { + dangerouslyReplaceNodeWithMarkupByID: 'dangerouslyReplaceNodeWithMarkupByID', + dangerouslyProcessChildrenUpdates: 'dangerouslyProcessChildrenUpdates' +}); + +module.exports = ReactDOMIDOperations; +},{"11":11,"161":161,"72":72,"78":78,"9":9}],46:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactDOMInput + */ + +'use strict'; + +var ReactDOMIDOperations = _dereq_(45); +var LinkedValueUtils = _dereq_(23); +var ReactMount = _dereq_(72); +var ReactUpdates = _dereq_(96); + +var assign = _dereq_(24); +var invariant = _dereq_(161); + +var instancesByReactID = {}; + +function forceUpdateIfMounted() { + if (this._rootNodeID) { + // DOM component is still mounted; update + ReactDOMInput.updateWrapper(this); + } +} + +/** + * Implements an <input> native component that allows setting these optional + * props: `checked`, `value`, `defaultChecked`, and `defaultValue`. + * + * If `checked` or `value` are not supplied (or null/undefined), user actions + * that affect the checked state or value will trigger updates to the element. + * + * If they are supplied (and not null/undefined), the rendered element will not + * trigger updates to the element. Instead, the props must change in order for + * the rendered element to be updated. + * + * The rendered element will be initialized as unchecked (or `defaultChecked`) + * with an empty value (or `defaultValue`). + * + * @see http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html + */ +var ReactDOMInput = { + getNativeProps: function (inst, props, context) { + var value = LinkedValueUtils.getValue(props); + var checked = LinkedValueUtils.getChecked(props); + + var nativeProps = assign({}, props, { + defaultChecked: undefined, + defaultValue: undefined, + value: value != null ? value : inst._wrapperState.initialValue, + checked: checked != null ? checked : inst._wrapperState.initialChecked, + onChange: inst._wrapperState.onChange + }); + + return nativeProps; + }, + + mountWrapper: function (inst, props) { + if ("development" !== 'production') { + LinkedValueUtils.checkPropTypes('input', props, inst._currentElement._owner); + } + + var defaultValue = props.defaultValue; + inst._wrapperState = { + initialChecked: props.defaultChecked || false, + initialValue: defaultValue != null ? defaultValue : null, + onChange: _handleChange.bind(inst) + }; + }, + + mountReadyWrapper: function (inst) { + // Can't be in mountWrapper or else server rendering leaks. + instancesByReactID[inst._rootNodeID] = inst; + }, + + unmountWrapper: function (inst) { + delete instancesByReactID[inst._rootNodeID]; + }, + + updateWrapper: function (inst) { + var props = inst._currentElement.props; + + // TODO: Shouldn't this be getChecked(props)? + var checked = props.checked; + if (checked != null) { + ReactDOMIDOperations.updatePropertyByID(inst._rootNodeID, 'checked', checked || false); + } + + var value = LinkedValueUtils.getValue(props); + if (value != null) { + // Cast `value` to a string to ensure the value is set correctly. While + // browsers typically do this as necessary, jsdom doesn't. + ReactDOMIDOperations.updatePropertyByID(inst._rootNodeID, 'value', '' + value); + } + } +}; + +function _handleChange(event) { + var props = this._currentElement.props; + + var returnValue = LinkedValueUtils.executeOnChange(props, event); + + // Here we use asap to wait until all updates have propagated, which + // is important when using controlled components within layers: + // https://github.com/facebook/react/issues/1698 + ReactUpdates.asap(forceUpdateIfMounted, this); + + var name = props.name; + if (props.type === 'radio' && name != null) { + var rootNode = ReactMount.getNode(this._rootNodeID); + var queryRoot = rootNode; + + while (queryRoot.parentNode) { + queryRoot = queryRoot.parentNode; + } + + // If `rootNode.form` was non-null, then we could try `form.elements`, + // but that sometimes behaves strangely in IE8. We could also try using + // `form.getElementsByName`, but that will only return direct children + // and won't include inputs that use the HTML5 `form=` attribute. Since + // the input might not even be in a form, let's just use the global + // `querySelectorAll` to ensure we don't miss anything. + var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type="radio"]'); + + for (var i = 0; i < group.length; i++) { + var otherNode = group[i]; + if (otherNode === rootNode || otherNode.form !== rootNode.form) { + continue; + } + // This will throw if radio buttons rendered by different copies of React + // and the same name are rendered into the same form (same as #1939). + // That's probably okay; we don't support it just as we don't support + // mixing React with non-React. + var otherID = ReactMount.getID(otherNode); + !otherID ? "development" !== 'production' ? invariant(false, 'ReactDOMInput: Mixing React and non-React radio inputs with the ' + 'same `name` is not supported.') : invariant(false) : undefined; + var otherInstance = instancesByReactID[otherID]; + !otherInstance ? "development" !== 'production' ? invariant(false, 'ReactDOMInput: Unknown radio button ID %s.', otherID) : invariant(false) : undefined; + // If this is a controlled radio button group, forcing the input that + // was previously checked to update will cause it to be come re-checked + // as appropriate. + ReactUpdates.asap(forceUpdateIfMounted, otherInstance); + } + } + + return returnValue; +} + +module.exports = ReactDOMInput; +},{"161":161,"23":23,"24":24,"45":45,"72":72,"96":96}],47:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactDOMOption + */ + +'use strict'; + +var ReactChildren = _dereq_(32); +var ReactDOMSelect = _dereq_(48); + +var assign = _dereq_(24); +var warning = _dereq_(173); + +var valueContextKey = ReactDOMSelect.valueContextKey; + +/** + * Implements an <option> native component that warns when `selected` is set. + */ +var ReactDOMOption = { + mountWrapper: function (inst, props, context) { + // TODO (yungsters): Remove support for `selected` in <option>. + if ("development" !== 'production') { + "development" !== 'production' ? warning(props.selected == null, 'Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.') : undefined; + } + + // Look up whether this option is 'selected' via context + var selectValue = context[valueContextKey]; + + // If context key is null (e.g., no specified value or after initial mount) + // or missing (e.g., for <datalist>), we don't change props.selected + var selected = null; + if (selectValue != null) { + selected = false; + if (Array.isArray(selectValue)) { + // multiple + for (var i = 0; i < selectValue.length; i++) { + if ('' + selectValue[i] === '' + props.value) { + selected = true; + break; + } + } + } else { + selected = '' + selectValue === '' + props.value; + } + } + + inst._wrapperState = { selected: selected }; + }, + + getNativeProps: function (inst, props, context) { + var nativeProps = assign({ selected: undefined, children: undefined }, props); + + // Read state only from initial mount because <select> updates value + // manually; we need the initial state only for server rendering + if (inst._wrapperState.selected != null) { + nativeProps.selected = inst._wrapperState.selected; + } + + var content = ''; + + // Flatten children and warn if they aren't strings or numbers; + // invalid types are ignored. + ReactChildren.forEach(props.children, function (child) { + if (child == null) { + return; + } + if (typeof child === 'string' || typeof child === 'number') { + content += child; + } else { + "development" !== 'production' ? warning(false, 'Only strings and numbers are supported as <option> children.') : undefined; + } + }); + + nativeProps.children = content; + return nativeProps; + } + +}; + +module.exports = ReactDOMOption; +},{"173":173,"24":24,"32":32,"48":48}],48:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactDOMSelect + */ + +'use strict'; + +var LinkedValueUtils = _dereq_(23); +var ReactMount = _dereq_(72); +var ReactUpdates = _dereq_(96); + +var assign = _dereq_(24); +var warning = _dereq_(173); + +var valueContextKey = '__ReactDOMSelect_value$' + Math.random().toString(36).slice(2); + +function updateOptionsIfPendingUpdateAndMounted() { + if (this._rootNodeID && this._wrapperState.pendingUpdate) { + this._wrapperState.pendingUpdate = false; + + var props = this._currentElement.props; + var value = LinkedValueUtils.getValue(props); + + if (value != null) { + updateOptions(this, Boolean(props.multiple), value); + } + } +} + +function getDeclarationErrorAddendum(owner) { + if (owner) { + var name = owner.getName(); + if (name) { + return ' Check the render method of `' + name + '`.'; + } + } + return ''; +} + +var valuePropNames = ['value', 'defaultValue']; + +/** + * Validation function for `value` and `defaultValue`. + * @private + */ +function checkSelectPropTypes(inst, props) { + var owner = inst._currentElement._owner; + LinkedValueUtils.checkPropTypes('select', props, owner); + + for (var i = 0; i < valuePropNames.length; i++) { + var propName = valuePropNames[i]; + if (props[propName] == null) { + continue; + } + if (props.multiple) { + "development" !== 'production' ? warning(Array.isArray(props[propName]), 'The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, getDeclarationErrorAddendum(owner)) : undefined; + } else { + "development" !== 'production' ? warning(!Array.isArray(props[propName]), 'The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, getDeclarationErrorAddendum(owner)) : undefined; + } + } +} + +/** + * @param {ReactDOMComponent} inst + * @param {boolean} multiple + * @param {*} propValue A stringable (with `multiple`, a list of stringables). + * @private + */ +function updateOptions(inst, multiple, propValue) { + var selectedValue, i; + var options = ReactMount.getNode(inst._rootNodeID).options; + + if (multiple) { + selectedValue = {}; + for (i = 0; i < propValue.length; i++) { + selectedValue['' + propValue[i]] = true; + } + for (i = 0; i < options.length; i++) { + var selected = selectedValue.hasOwnProperty(options[i].value); + if (options[i].selected !== selected) { + options[i].selected = selected; + } + } + } else { + // Do not set `select.value` as exact behavior isn't consistent across all + // browsers for all cases. + selectedValue = '' + propValue; + for (i = 0; i < options.length; i++) { + if (options[i].value === selectedValue) { + options[i].selected = true; + return; + } + } + if (options.length) { + options[0].selected = true; + } + } +} + +/** + * Implements a <select> native component that allows optionally setting the + * props `value` and `defaultValue`. If `multiple` is false, the prop must be a + * stringable. If `multiple` is true, the prop must be an array of stringables. + * + * If `value` is not supplied (or null/undefined), user actions that change the + * selected option will trigger updates to the rendered options. + * + * If it is supplied (and not null/undefined), the rendered options will not + * update in response to user actions. Instead, the `value` prop must change in + * order for the rendered options to update. + * + * If `defaultValue` is provided, any options with the supplied values will be + * selected. + */ +var ReactDOMSelect = { + valueContextKey: valueContextKey, + + getNativeProps: function (inst, props, context) { + return assign({}, props, { + onChange: inst._wrapperState.onChange, + value: undefined + }); + }, + + mountWrapper: function (inst, props) { + if ("development" !== 'production') { + checkSelectPropTypes(inst, props); + } + + var value = LinkedValueUtils.getValue(props); + inst._wrapperState = { + pendingUpdate: false, + initialValue: value != null ? value : props.defaultValue, + onChange: _handleChange.bind(inst), + wasMultiple: Boolean(props.multiple) + }; + }, + + processChildContext: function (inst, props, context) { + // Pass down initial value so initial generated markup has correct + // `selected` attributes + var childContext = assign({}, context); + childContext[valueContextKey] = inst._wrapperState.initialValue; + return childContext; + }, + + postUpdateWrapper: function (inst) { + var props = inst._currentElement.props; + + // After the initial mount, we control selected-ness manually so don't pass + // the context value down + inst._wrapperState.initialValue = undefined; + + var wasMultiple = inst._wrapperState.wasMultiple; + inst._wrapperState.wasMultiple = Boolean(props.multiple); + + var value = LinkedValueUtils.getValue(props); + if (value != null) { + inst._wrapperState.pendingUpdate = false; + updateOptions(inst, Boolean(props.multiple), value); + } else if (wasMultiple !== Boolean(props.multiple)) { + // For simplicity, reapply `defaultValue` if `multiple` is toggled. + if (props.defaultValue != null) { + updateOptions(inst, Boolean(props.multiple), props.defaultValue); + } else { + // Revert the select back to its default unselected state. + updateOptions(inst, Boolean(props.multiple), props.multiple ? [] : ''); + } + } + } +}; + +function _handleChange(event) { + var props = this._currentElement.props; + var returnValue = LinkedValueUtils.executeOnChange(props, event); + + this._wrapperState.pendingUpdate = true; + ReactUpdates.asap(updateOptionsIfPendingUpdateAndMounted, this); + return returnValue; +} + +module.exports = ReactDOMSelect; +},{"173":173,"23":23,"24":24,"72":72,"96":96}],49:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactDOMSelection + */ + +'use strict'; + +var ExecutionEnvironment = _dereq_(147); + +var getNodeForCharacterOffset = _dereq_(130); +var getTextContentAccessor = _dereq_(131); + +/** + * While `isCollapsed` is available on the Selection object and `collapsed` + * is available on the Range object, IE11 sometimes gets them wrong. + * If the anchor/focus nodes and offsets are the same, the range is collapsed. + */ +function isCollapsed(anchorNode, anchorOffset, focusNode, focusOffset) { + return anchorNode === focusNode && anchorOffset === focusOffset; +} + +/** + * Get the appropriate anchor and focus node/offset pairs for IE. + * + * The catch here is that IE's selection API doesn't provide information + * about whether the selection is forward or backward, so we have to + * behave as though it's always forward. + * + * IE text differs from modern selection in that it behaves as though + * block elements end with a new line. This means character offsets will + * differ between the two APIs. + * + * @param {DOMElement} node + * @return {object} + */ +function getIEOffsets(node) { + var selection = document.selection; + var selectedRange = selection.createRange(); + var selectedLength = selectedRange.text.length; + + // Duplicate selection so we can move range without breaking user selection. + var fromStart = selectedRange.duplicate(); + fromStart.moveToElementText(node); + fromStart.setEndPoint('EndToStart', selectedRange); + + var startOffset = fromStart.text.length; + var endOffset = startOffset + selectedLength; + + return { + start: startOffset, + end: endOffset + }; +} + +/** + * @param {DOMElement} node + * @return {?object} + */ +function getModernOffsets(node) { + var selection = window.getSelection && window.getSelection(); + + if (!selection || selection.rangeCount === 0) { + return null; + } + + var anchorNode = selection.anchorNode; + var anchorOffset = selection.anchorOffset; + var focusNode = selection.focusNode; + var focusOffset = selection.focusOffset; + + var currentRange = selection.getRangeAt(0); + + // In Firefox, range.startContainer and range.endContainer can be "anonymous + // divs", e.g. the up/down buttons on an <input type="number">. Anonymous + // divs do not seem to expose properties, triggering a "Permission denied + // error" if any of its properties are accessed. The only seemingly possible + // way to avoid erroring is to access a property that typically works for + // non-anonymous divs and catch any error that may otherwise arise. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=208427 + try { + /* eslint-disable no-unused-expressions */ + currentRange.startContainer.nodeType; + currentRange.endContainer.nodeType; + /* eslint-enable no-unused-expressions */ + } catch (e) { + return null; + } + + // If the node and offset values are the same, the selection is collapsed. + // `Selection.isCollapsed` is available natively, but IE sometimes gets + // this value wrong. + var isSelectionCollapsed = isCollapsed(selection.anchorNode, selection.anchorOffset, selection.focusNode, selection.focusOffset); + + var rangeLength = isSelectionCollapsed ? 0 : currentRange.toString().length; + + var tempRange = currentRange.cloneRange(); + tempRange.selectNodeContents(node); + tempRange.setEnd(currentRange.startContainer, currentRange.startOffset); + + var isTempRangeCollapsed = isCollapsed(tempRange.startContainer, tempRange.startOffset, tempRange.endContainer, tempRange.endOffset); + + var start = isTempRangeCollapsed ? 0 : tempRange.toString().length; + var end = start + rangeLength; + + // Detect whether the selection is backward. + var detectionRange = document.createRange(); + detectionRange.setStart(anchorNode, anchorOffset); + detectionRange.setEnd(focusNode, focusOffset); + var isBackward = detectionRange.collapsed; + + return { + start: isBackward ? end : start, + end: isBackward ? start : end + }; +} + +/** + * @param {DOMElement|DOMTextNode} node + * @param {object} offsets + */ +function setIEOffsets(node, offsets) { + var range = document.selection.createRange().duplicate(); + var start, end; + + if (typeof offsets.end === 'undefined') { + start = offsets.start; + end = start; + } else if (offsets.start > offsets.end) { + start = offsets.end; + end = offsets.start; + } else { + start = offsets.start; + end = offsets.end; + } + + range.moveToElementText(node); + range.moveStart('character', start); + range.setEndPoint('EndToStart', range); + range.moveEnd('character', end - start); + range.select(); +} + +/** + * In modern non-IE browsers, we can support both forward and backward + * selections. + * + * Note: IE10+ supports the Selection object, but it does not support + * the `extend` method, which means that even in modern IE, it's not possible + * to programatically create a backward selection. Thus, for all IE + * versions, we use the old IE API to create our selections. + * + * @param {DOMElement|DOMTextNode} node + * @param {object} offsets + */ +function setModernOffsets(node, offsets) { + if (!window.getSelection) { + return; + } + + var selection = window.getSelection(); + var length = node[getTextContentAccessor()].length; + var start = Math.min(offsets.start, length); + var end = typeof offsets.end === 'undefined' ? start : Math.min(offsets.end, length); + + // IE 11 uses modern selection, but doesn't support the extend method. + // Flip backward selections, so we can set with a single range. + if (!selection.extend && start > end) { + var temp = end; + end = start; + start = temp; + } + + var startMarker = getNodeForCharacterOffset(node, start); + var endMarker = getNodeForCharacterOffset(node, end); + + if (startMarker && endMarker) { + var range = document.createRange(); + range.setStart(startMarker.node, startMarker.offset); + selection.removeAllRanges(); + + if (start > end) { + selection.addRange(range); + selection.extend(endMarker.node, endMarker.offset); + } else { + range.setEnd(endMarker.node, endMarker.offset); + selection.addRange(range); + } + } +} + +var useIEOffsets = ExecutionEnvironment.canUseDOM && 'selection' in document && !('getSelection' in window); + +var ReactDOMSelection = { + /** + * @param {DOMElement} node + */ + getOffsets: useIEOffsets ? getIEOffsets : getModernOffsets, + + /** + * @param {DOMElement|DOMTextNode} node + * @param {object} offsets + */ + setOffsets: useIEOffsets ? setIEOffsets : setModernOffsets +}; + +module.exports = ReactDOMSelection; +},{"130":130,"131":131,"147":147}],50:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactDOMServer + */ + +'use strict'; + +var ReactDefaultInjection = _dereq_(54); +var ReactServerRendering = _dereq_(88); +var ReactVersion = _dereq_(97); + +ReactDefaultInjection.inject(); + +var ReactDOMServer = { + renderToString: ReactServerRendering.renderToString, + renderToStaticMarkup: ReactServerRendering.renderToStaticMarkup, + version: ReactVersion +}; + +module.exports = ReactDOMServer; +},{"54":54,"88":88,"97":97}],51:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactDOMTextComponent + * @typechecks static-only + */ + +'use strict'; + +var DOMChildrenOperations = _dereq_(9); +var DOMPropertyOperations = _dereq_(11); +var ReactComponentBrowserEnvironment = _dereq_(35); +var ReactMount = _dereq_(72); + +var assign = _dereq_(24); +var escapeTextContentForBrowser = _dereq_(121); +var setTextContent = _dereq_(139); +var validateDOMNesting = _dereq_(144); + +/** + * Text nodes violate a couple assumptions that React makes about components: + * + * - When mounting text into the DOM, adjacent text nodes are merged. + * - Text nodes cannot be assigned a React root ID. + * + * This component is used to wrap strings in elements so that they can undergo + * the same reconciliation that is applied to elements. + * + * TODO: Investigate representing React components in the DOM with text nodes. + * + * @class ReactDOMTextComponent + * @extends ReactComponent + * @internal + */ +var ReactDOMTextComponent = function (props) { + // This constructor and its argument is currently used by mocks. +}; + +assign(ReactDOMTextComponent.prototype, { + + /** + * @param {ReactText} text + * @internal + */ + construct: function (text) { + // TODO: This is really a ReactText (ReactNode), not a ReactElement + this._currentElement = text; + this._stringText = '' + text; + + // Properties + this._rootNodeID = null; + this._mountIndex = 0; + }, + + /** + * Creates the markup for this text node. This node is not intended to have + * any features besides containing text content. + * + * @param {string} rootID DOM ID of the root node. + * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction + * @return {string} Markup for this text node. + * @internal + */ + mountComponent: function (rootID, transaction, context) { + if ("development" !== 'production') { + if (context[validateDOMNesting.ancestorInfoContextKey]) { + validateDOMNesting('span', null, context[validateDOMNesting.ancestorInfoContextKey]); + } + } + + this._rootNodeID = rootID; + if (transaction.useCreateElement) { + var ownerDocument = context[ReactMount.ownerDocumentContextKey]; + var el = ownerDocument.createElementNS('http://www.w3.org/1999/xhtml', 'span'); + DOMPropertyOperations.setAttributeForID(el, rootID); + // Populate node cache + ReactMount.getID(el); + setTextContent(el, this._stringText); + return el; + } else { + var escapedText = escapeTextContentForBrowser(this._stringText); + + if (transaction.renderToStaticMarkup) { + // Normally we'd wrap this in a `span` for the reasons stated above, but + // since this is a situation where React won't take over (static pages), + // we can simply return the text as it is. + return escapedText; + } + + return '<span ' + DOMPropertyOperations.createMarkupForID(rootID) + '>' + escapedText + '</span>'; + } + }, + + /** + * Updates this component by updating the text content. + * + * @param {ReactText} nextText The next text content + * @param {ReactReconcileTransaction} transaction + * @internal + */ + receiveComponent: function (nextText, transaction) { + if (nextText !== this._currentElement) { + this._currentElement = nextText; + var nextStringText = '' + nextText; + if (nextStringText !== this._stringText) { + // TODO: Save this as pending props and use performUpdateIfNecessary + // and/or updateComponent to do the actual update for consistency with + // other component types? + this._stringText = nextStringText; + var node = ReactMount.getNode(this._rootNodeID); + DOMChildrenOperations.updateTextContent(node, nextStringText); + } + } + }, + + unmountComponent: function () { + ReactComponentBrowserEnvironment.unmountIDFromEnvironment(this._rootNodeID); + } + +}); + +module.exports = ReactDOMTextComponent; +},{"11":11,"121":121,"139":139,"144":144,"24":24,"35":35,"72":72,"9":9}],52:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactDOMTextarea + */ + +'use strict'; + +var LinkedValueUtils = _dereq_(23); +var ReactDOMIDOperations = _dereq_(45); +var ReactUpdates = _dereq_(96); + +var assign = _dereq_(24); +var invariant = _dereq_(161); +var warning = _dereq_(173); + +function forceUpdateIfMounted() { + if (this._rootNodeID) { + // DOM component is still mounted; update + ReactDOMTextarea.updateWrapper(this); + } +} + +/** + * Implements a <textarea> native component that allows setting `value`, and + * `defaultValue`. This differs from the traditional DOM API because value is + * usually set as PCDATA children. + * + * If `value` is not supplied (or null/undefined), user actions that affect the + * value will trigger updates to the element. + * + * If `value` is supplied (and not null/undefined), the rendered element will + * not trigger updates to the element. Instead, the `value` prop must change in + * order for the rendered element to be updated. + * + * The rendered element will be initialized with an empty value, the prop + * `defaultValue` if specified, or the children content (deprecated). + */ +var ReactDOMTextarea = { + getNativeProps: function (inst, props, context) { + !(props.dangerouslySetInnerHTML == null) ? "development" !== 'production' ? invariant(false, '`dangerouslySetInnerHTML` does not make sense on <textarea>.') : invariant(false) : undefined; + + // Always set children to the same thing. In IE9, the selection range will + // get reset if `textContent` is mutated. + var nativeProps = assign({}, props, { + defaultValue: undefined, + value: undefined, + children: inst._wrapperState.initialValue, + onChange: inst._wrapperState.onChange + }); + + return nativeProps; + }, + + mountWrapper: function (inst, props) { + if ("development" !== 'production') { + LinkedValueUtils.checkPropTypes('textarea', props, inst._currentElement._owner); + } + + var defaultValue = props.defaultValue; + // TODO (yungsters): Remove support for children content in <textarea>. + var children = props.children; + if (children != null) { + if ("development" !== 'production') { + "development" !== 'production' ? warning(false, 'Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.') : undefined; + } + !(defaultValue == null) ? "development" !== 'production' ? invariant(false, 'If you supply `defaultValue` on a <textarea>, do not pass children.') : invariant(false) : undefined; + if (Array.isArray(children)) { + !(children.length <= 1) ? "development" !== 'production' ? invariant(false, '<textarea> can only have at most one child.') : invariant(false) : undefined; + children = children[0]; + } + + defaultValue = '' + children; + } + if (defaultValue == null) { + defaultValue = ''; + } + var value = LinkedValueUtils.getValue(props); + + inst._wrapperState = { + // We save the initial value so that `ReactDOMComponent` doesn't update + // `textContent` (unnecessary since we update value). + // The initial value can be a boolean or object so that's why it's + // forced to be a string. + initialValue: '' + (value != null ? value : defaultValue), + onChange: _handleChange.bind(inst) + }; + }, + + updateWrapper: function (inst) { + var props = inst._currentElement.props; + var value = LinkedValueUtils.getValue(props); + if (value != null) { + // Cast `value` to a string to ensure the value is set correctly. While + // browsers typically do this as necessary, jsdom doesn't. + ReactDOMIDOperations.updatePropertyByID(inst._rootNodeID, 'value', '' + value); + } + } +}; + +function _handleChange(event) { + var props = this._currentElement.props; + var returnValue = LinkedValueUtils.executeOnChange(props, event); + ReactUpdates.asap(forceUpdateIfMounted, this); + return returnValue; +} + +module.exports = ReactDOMTextarea; +},{"161":161,"173":173,"23":23,"24":24,"45":45,"96":96}],53:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactDefaultBatchingStrategy + */ + +'use strict'; + +var ReactUpdates = _dereq_(96); +var Transaction = _dereq_(113); + +var assign = _dereq_(24); +var emptyFunction = _dereq_(153); + +var RESET_BATCHED_UPDATES = { + initialize: emptyFunction, + close: function () { + ReactDefaultBatchingStrategy.isBatchingUpdates = false; + } +}; + +var FLUSH_BATCHED_UPDATES = { + initialize: emptyFunction, + close: ReactUpdates.flushBatchedUpdates.bind(ReactUpdates) +}; + +var TRANSACTION_WRAPPERS = [FLUSH_BATCHED_UPDATES, RESET_BATCHED_UPDATES]; + +function ReactDefaultBatchingStrategyTransaction() { + this.reinitializeTransaction(); +} + +assign(ReactDefaultBatchingStrategyTransaction.prototype, Transaction.Mixin, { + getTransactionWrappers: function () { + return TRANSACTION_WRAPPERS; + } +}); + +var transaction = new ReactDefaultBatchingStrategyTransaction(); + +var ReactDefaultBatchingStrategy = { + isBatchingUpdates: false, + + /** + * Call the provided function in a context within which calls to `setState` + * and friends are batched such that components aren't updated unnecessarily. + */ + batchedUpdates: function (callback, a, b, c, d, e) { + var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates; + + ReactDefaultBatchingStrategy.isBatchingUpdates = true; + + // The code is written this way to avoid extra allocations + if (alreadyBatchingUpdates) { + callback(a, b, c, d, e); + } else { + transaction.perform(callback, null, a, b, c, d, e); + } + } +}; + +module.exports = ReactDefaultBatchingStrategy; +},{"113":113,"153":153,"24":24,"96":96}],54:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactDefaultInjection + */ + +'use strict'; + +var BeforeInputEventPlugin = _dereq_(3); +var ChangeEventPlugin = _dereq_(7); +var ClientReactRootIndex = _dereq_(8); +var DefaultEventPluginOrder = _dereq_(13); +var EnterLeaveEventPlugin = _dereq_(14); +var ExecutionEnvironment = _dereq_(147); +var HTMLDOMPropertyConfig = _dereq_(21); +var ReactBrowserComponentMixin = _dereq_(27); +var ReactComponentBrowserEnvironment = _dereq_(35); +var ReactDefaultBatchingStrategy = _dereq_(53); +var ReactDOMComponent = _dereq_(42); +var ReactDOMTextComponent = _dereq_(51); +var ReactEventListener = _dereq_(63); +var ReactInjection = _dereq_(65); +var ReactInstanceHandles = _dereq_(67); +var ReactMount = _dereq_(72); +var ReactReconcileTransaction = _dereq_(83); +var SelectEventPlugin = _dereq_(99); +var ServerReactRootIndex = _dereq_(100); +var SimpleEventPlugin = _dereq_(101); +var SVGDOMPropertyConfig = _dereq_(98); + +var alreadyInjected = false; + +function inject() { + if (alreadyInjected) { + // TODO: This is currently true because these injections are shared between + // the client and the server package. They should be built independently + // and not share any injection state. Then this problem will be solved. + return; + } + alreadyInjected = true; + + ReactInjection.EventEmitter.injectReactEventListener(ReactEventListener); + + /** + * Inject modules for resolving DOM hierarchy and plugin ordering. + */ + ReactInjection.EventPluginHub.injectEventPluginOrder(DefaultEventPluginOrder); + ReactInjection.EventPluginHub.injectInstanceHandle(ReactInstanceHandles); + ReactInjection.EventPluginHub.injectMount(ReactMount); + + /** + * Some important event plugins included by default (without having to require + * them). + */ + ReactInjection.EventPluginHub.injectEventPluginsByName({ + SimpleEventPlugin: SimpleEventPlugin, + EnterLeaveEventPlugin: EnterLeaveEventPlugin, + ChangeEventPlugin: ChangeEventPlugin, + SelectEventPlugin: SelectEventPlugin, + BeforeInputEventPlugin: BeforeInputEventPlugin + }); + + ReactInjection.NativeComponent.injectGenericComponentClass(ReactDOMComponent); + + ReactInjection.NativeComponent.injectTextComponentClass(ReactDOMTextComponent); + + ReactInjection.Class.injectMixin(ReactBrowserComponentMixin); + + ReactInjection.DOMProperty.injectDOMPropertyConfig(HTMLDOMPropertyConfig); + ReactInjection.DOMProperty.injectDOMPropertyConfig(SVGDOMPropertyConfig); + + ReactInjection.EmptyComponent.injectEmptyComponent('noscript'); + + ReactInjection.Updates.injectReconcileTransaction(ReactReconcileTransaction); + ReactInjection.Updates.injectBatchingStrategy(ReactDefaultBatchingStrategy); + + ReactInjection.RootIndex.injectCreateReactRootIndex(ExecutionEnvironment.canUseDOM ? ClientReactRootIndex.createReactRootIndex : ServerReactRootIndex.createReactRootIndex); + + ReactInjection.Component.injectEnvironment(ReactComponentBrowserEnvironment); + + if ("development" !== 'production') { + var url = ExecutionEnvironment.canUseDOM && window.location.href || ''; + if (/[?&]react_perf\b/.test(url)) { + var ReactDefaultPerf = _dereq_(55); + ReactDefaultPerf.start(); + } + } +} + +module.exports = { + inject: inject +}; +},{"100":100,"101":101,"13":13,"14":14,"147":147,"21":21,"27":27,"3":3,"35":35,"42":42,"51":51,"53":53,"55":55,"63":63,"65":65,"67":67,"7":7,"72":72,"8":8,"83":83,"98":98,"99":99}],55:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactDefaultPerf + * @typechecks static-only + */ + +'use strict'; + +var DOMProperty = _dereq_(10); +var ReactDefaultPerfAnalysis = _dereq_(56); +var ReactMount = _dereq_(72); +var ReactPerf = _dereq_(78); + +var performanceNow = _dereq_(170); + +function roundFloat(val) { + return Math.floor(val * 100) / 100; +} + +function addValue(obj, key, val) { + obj[key] = (obj[key] || 0) + val; +} + +var ReactDefaultPerf = { + _allMeasurements: [], // last item in the list is the current one + _mountStack: [0], + _injected: false, + + start: function () { + if (!ReactDefaultPerf._injected) { + ReactPerf.injection.injectMeasure(ReactDefaultPerf.measure); + } + + ReactDefaultPerf._allMeasurements.length = 0; + ReactPerf.enableMeasure = true; + }, + + stop: function () { + ReactPerf.enableMeasure = false; + }, + + getLastMeasurements: function () { + return ReactDefaultPerf._allMeasurements; + }, + + printExclusive: function (measurements) { + measurements = measurements || ReactDefaultPerf._allMeasurements; + var summary = ReactDefaultPerfAnalysis.getExclusiveSummary(measurements); + console.table(summary.map(function (item) { + return { + 'Component class name': item.componentName, + 'Total inclusive time (ms)': roundFloat(item.inclusive), + 'Exclusive mount time (ms)': roundFloat(item.exclusive), + 'Exclusive render time (ms)': roundFloat(item.render), + 'Mount time per instance (ms)': roundFloat(item.exclusive / item.count), + 'Render time per instance (ms)': roundFloat(item.render / item.count), + 'Instances': item.count + }; + })); + // TODO: ReactDefaultPerfAnalysis.getTotalTime() does not return the correct + // number. + }, + + printInclusive: function (measurements) { + measurements = measurements || ReactDefaultPerf._allMeasurements; + var summary = ReactDefaultPerfAnalysis.getInclusiveSummary(measurements); + console.table(summary.map(function (item) { + return { + 'Owner > component': item.componentName, + 'Inclusive time (ms)': roundFloat(item.time), + 'Instances': item.count + }; + })); + console.log('Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms'); + }, + + getMeasurementsSummaryMap: function (measurements) { + var summary = ReactDefaultPerfAnalysis.getInclusiveSummary(measurements, true); + return summary.map(function (item) { + return { + 'Owner > component': item.componentName, + 'Wasted time (ms)': item.time, + 'Instances': item.count + }; + }); + }, + + printWasted: function (measurements) { + measurements = measurements || ReactDefaultPerf._allMeasurements; + console.table(ReactDefaultPerf.getMeasurementsSummaryMap(measurements)); + console.log('Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms'); + }, + + printDOM: function (measurements) { + measurements = measurements || ReactDefaultPerf._allMeasurements; + var summary = ReactDefaultPerfAnalysis.getDOMSummary(measurements); + console.table(summary.map(function (item) { + var result = {}; + result[DOMProperty.ID_ATTRIBUTE_NAME] = item.id; + result.type = item.type; + result.args = JSON.stringify(item.args); + return result; + })); + console.log('Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms'); + }, + + _recordWrite: function (id, fnName, totalTime, args) { + // TODO: totalTime isn't that useful since it doesn't count paints/reflows + var writes = ReactDefaultPerf._allMeasurements[ReactDefaultPerf._allMeasurements.length - 1].writes; + writes[id] = writes[id] || []; + writes[id].push({ + type: fnName, + time: totalTime, + args: args + }); + }, + + measure: function (moduleName, fnName, func) { + return function () { + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + var totalTime; + var rv; + var start; + + if (fnName === '_renderNewRootComponent' || fnName === 'flushBatchedUpdates') { + // A "measurement" is a set of metrics recorded for each flush. We want + // to group the metrics for a given flush together so we can look at the + // components that rendered and the DOM operations that actually + // happened to determine the amount of "wasted work" performed. + ReactDefaultPerf._allMeasurements.push({ + exclusive: {}, + inclusive: {}, + render: {}, + counts: {}, + writes: {}, + displayNames: {}, + totalTime: 0, + created: {} + }); + start = performanceNow(); + rv = func.apply(this, args); + ReactDefaultPerf._allMeasurements[ReactDefaultPerf._allMeasurements.length - 1].totalTime = performanceNow() - start; + return rv; + } else if (fnName === '_mountImageIntoNode' || moduleName === 'ReactBrowserEventEmitter' || moduleName === 'ReactDOMIDOperations' || moduleName === 'CSSPropertyOperations' || moduleName === 'DOMChildrenOperations' || moduleName === 'DOMPropertyOperations') { + start = performanceNow(); + rv = func.apply(this, args); + totalTime = performanceNow() - start; + + if (fnName === '_mountImageIntoNode') { + var mountID = ReactMount.getID(args[1]); + ReactDefaultPerf._recordWrite(mountID, fnName, totalTime, args[0]); + } else if (fnName === 'dangerouslyProcessChildrenUpdates') { + // special format + args[0].forEach(function (update) { + var writeArgs = {}; + if (update.fromIndex !== null) { + writeArgs.fromIndex = update.fromIndex; + } + if (update.toIndex !== null) { + writeArgs.toIndex = update.toIndex; + } + if (update.textContent !== null) { + writeArgs.textContent = update.textContent; + } + if (update.markupIndex !== null) { + writeArgs.markup = args[1][update.markupIndex]; + } + ReactDefaultPerf._recordWrite(update.parentID, update.type, totalTime, writeArgs); + }); + } else { + // basic format + var id = args[0]; + if (typeof id === 'object') { + id = ReactMount.getID(args[0]); + } + ReactDefaultPerf._recordWrite(id, fnName, totalTime, Array.prototype.slice.call(args, 1)); + } + return rv; + } else if (moduleName === 'ReactCompositeComponent' && (fnName === 'mountComponent' || fnName === 'updateComponent' || // TODO: receiveComponent()? + fnName === '_renderValidatedComponent')) { + + if (this._currentElement.type === ReactMount.TopLevelWrapper) { + return func.apply(this, args); + } + + var rootNodeID = fnName === 'mountComponent' ? args[0] : this._rootNodeID; + var isRender = fnName === '_renderValidatedComponent'; + var isMount = fnName === 'mountComponent'; + + var mountStack = ReactDefaultPerf._mountStack; + var entry = ReactDefaultPerf._allMeasurements[ReactDefaultPerf._allMeasurements.length - 1]; + + if (isRender) { + addValue(entry.counts, rootNodeID, 1); + } else if (isMount) { + entry.created[rootNodeID] = true; + mountStack.push(0); + } + + start = performanceNow(); + rv = func.apply(this, args); + totalTime = performanceNow() - start; + + if (isRender) { + addValue(entry.render, rootNodeID, totalTime); + } else if (isMount) { + var subMountTime = mountStack.pop(); + mountStack[mountStack.length - 1] += totalTime; + addValue(entry.exclusive, rootNodeID, totalTime - subMountTime); + addValue(entry.inclusive, rootNodeID, totalTime); + } else { + addValue(entry.inclusive, rootNodeID, totalTime); + } + + entry.displayNames[rootNodeID] = { + current: this.getName(), + owner: this._currentElement._owner ? this._currentElement._owner.getName() : '<root>' + }; + + return rv; + } else { + return func.apply(this, args); + } + }; + } +}; + +module.exports = ReactDefaultPerf; +},{"10":10,"170":170,"56":56,"72":72,"78":78}],56:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactDefaultPerfAnalysis + */ + +'use strict'; + +var assign = _dereq_(24); + +// Don't try to save users less than 1.2ms (a number I made up) +var DONT_CARE_THRESHOLD = 1.2; +var DOM_OPERATION_TYPES = { + '_mountImageIntoNode': 'set innerHTML', + INSERT_MARKUP: 'set innerHTML', + MOVE_EXISTING: 'move', + REMOVE_NODE: 'remove', + SET_MARKUP: 'set innerHTML', + TEXT_CONTENT: 'set textContent', + 'setValueForProperty': 'update attribute', + 'setValueForAttribute': 'update attribute', + 'deleteValueForProperty': 'remove attribute', + 'setValueForStyles': 'update styles', + 'replaceNodeWithMarkup': 'replace', + 'updateTextContent': 'set textContent' +}; + +function getTotalTime(measurements) { + // TODO: return number of DOM ops? could be misleading. + // TODO: measure dropped frames after reconcile? + // TODO: log total time of each reconcile and the top-level component + // class that triggered it. + var totalTime = 0; + for (var i = 0; i < measurements.length; i++) { + var measurement = measurements[i]; + totalTime += measurement.totalTime; + } + return totalTime; +} + +function getDOMSummary(measurements) { + var items = []; + measurements.forEach(function (measurement) { + Object.keys(measurement.writes).forEach(function (id) { + measurement.writes[id].forEach(function (write) { + items.push({ + id: id, + type: DOM_OPERATION_TYPES[write.type] || write.type, + args: write.args + }); + }); + }); + }); + return items; +} + +function getExclusiveSummary(measurements) { + var candidates = {}; + var displayName; + + for (var i = 0; i < measurements.length; i++) { + var measurement = measurements[i]; + var allIDs = assign({}, measurement.exclusive, measurement.inclusive); + + for (var id in allIDs) { + displayName = measurement.displayNames[id].current; + + candidates[displayName] = candidates[displayName] || { + componentName: displayName, + inclusive: 0, + exclusive: 0, + render: 0, + count: 0 + }; + if (measurement.render[id]) { + candidates[displayName].render += measurement.render[id]; + } + if (measurement.exclusive[id]) { + candidates[displayName].exclusive += measurement.exclusive[id]; + } + if (measurement.inclusive[id]) { + candidates[displayName].inclusive += measurement.inclusive[id]; + } + if (measurement.counts[id]) { + candidates[displayName].count += measurement.counts[id]; + } + } + } + + // Now make a sorted array with the results. + var arr = []; + for (displayName in candidates) { + if (candidates[displayName].exclusive >= DONT_CARE_THRESHOLD) { + arr.push(candidates[displayName]); + } + } + + arr.sort(function (a, b) { + return b.exclusive - a.exclusive; + }); + + return arr; +} + +function getInclusiveSummary(measurements, onlyClean) { + var candidates = {}; + var inclusiveKey; + + for (var i = 0; i < measurements.length; i++) { + var measurement = measurements[i]; + var allIDs = assign({}, measurement.exclusive, measurement.inclusive); + var cleanComponents; + + if (onlyClean) { + cleanComponents = getUnchangedComponents(measurement); + } + + for (var id in allIDs) { + if (onlyClean && !cleanComponents[id]) { + continue; + } + + var displayName = measurement.displayNames[id]; + + // Inclusive time is not useful for many components without knowing where + // they are instantiated. So we aggregate inclusive time with both the + // owner and current displayName as the key. + inclusiveKey = displayName.owner + ' > ' + displayName.current; + + candidates[inclusiveKey] = candidates[inclusiveKey] || { + componentName: inclusiveKey, + time: 0, + count: 0 + }; + + if (measurement.inclusive[id]) { + candidates[inclusiveKey].time += measurement.inclusive[id]; + } + if (measurement.counts[id]) { + candidates[inclusiveKey].count += measurement.counts[id]; + } + } + } + + // Now make a sorted array with the results. + var arr = []; + for (inclusiveKey in candidates) { + if (candidates[inclusiveKey].time >= DONT_CARE_THRESHOLD) { + arr.push(candidates[inclusiveKey]); + } + } + + arr.sort(function (a, b) { + return b.time - a.time; + }); + + return arr; +} + +function getUnchangedComponents(measurement) { + // For a given reconcile, look at which components did not actually + // render anything to the DOM and return a mapping of their ID to + // the amount of time it took to render the entire subtree. + var cleanComponents = {}; + var dirtyLeafIDs = Object.keys(measurement.writes); + var allIDs = assign({}, measurement.exclusive, measurement.inclusive); + + for (var id in allIDs) { + var isDirty = false; + // For each component that rendered, see if a component that triggered + // a DOM op is in its subtree. + for (var i = 0; i < dirtyLeafIDs.length; i++) { + if (dirtyLeafIDs[i].indexOf(id) === 0) { + isDirty = true; + break; + } + } + // check if component newly created + if (measurement.created[id]) { + isDirty = true; + } + if (!isDirty && measurement.counts[id] > 0) { + cleanComponents[id] = true; + } + } + return cleanComponents; +} + +var ReactDefaultPerfAnalysis = { + getExclusiveSummary: getExclusiveSummary, + getInclusiveSummary: getInclusiveSummary, + getDOMSummary: getDOMSummary, + getTotalTime: getTotalTime +}; + +module.exports = ReactDefaultPerfAnalysis; +},{"24":24}],57:[function(_dereq_,module,exports){ +/** + * Copyright 2014-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactElement + */ + +'use strict'; + +var ReactCurrentOwner = _dereq_(39); + +var assign = _dereq_(24); +var canDefineProperty = _dereq_(117); + +// The Symbol used to tag the ReactElement type. If there is no native Symbol +// nor polyfill, then a plain number is used for performance. +var REACT_ELEMENT_TYPE = typeof Symbol === 'function' && Symbol['for'] && Symbol['for']('react.element') || 0xeac7; + +var RESERVED_PROPS = { + key: true, + ref: true, + __self: true, + __source: true +}; + +/** + * Base constructor for all React elements. This is only used to make this + * work with a dynamic instanceof check. Nothing should live on this prototype. + * + * @param {*} type + * @param {*} key + * @param {string|object} ref + * @param {*} self A *temporary* helper to detect places where `this` is + * different from the `owner` when React.createElement is called, so that we + * can warn. We want to get rid of owner and replace string `ref`s with arrow + * functions, and as long as `this` and owner are the same, there will be no + * change in behavior. + * @param {*} source An annotation object (added by a transpiler or otherwise) + * indicating filename, line number, and/or other information. + * @param {*} owner + * @param {*} props + * @internal + */ +var ReactElement = function (type, key, ref, self, source, owner, props) { + var element = { + // This tag allow us to uniquely identify this as a React Element + $$typeof: REACT_ELEMENT_TYPE, + + // Built-in properties that belong on the element + type: type, + key: key, + ref: ref, + props: props, + + // Record the component responsible for creating this element. + _owner: owner + }; + + if ("development" !== 'production') { + // The validation flag is currently mutative. We put it on + // an external backing store so that we can freeze the whole object. + // This can be replaced with a WeakMap once they are implemented in + // commonly used development environments. + element._store = {}; + + // To make comparing ReactElements easier for testing purposes, we make + // the validation flag non-enumerable (where possible, which should + // include every environment we run tests in), so the test framework + // ignores it. + if (canDefineProperty) { + Object.defineProperty(element._store, 'validated', { + configurable: false, + enumerable: false, + writable: true, + value: false + }); + // self and source are DEV only properties. + Object.defineProperty(element, '_self', { + configurable: false, + enumerable: false, + writable: false, + value: self + }); + // Two elements created in two different places should be considered + // equal for testing purposes and therefore we hide it from enumeration. + Object.defineProperty(element, '_source', { + configurable: false, + enumerable: false, + writable: false, + value: source + }); + } else { + element._store.validated = false; + element._self = self; + element._source = source; + } + Object.freeze(element.props); + Object.freeze(element); + } + + return element; +}; + +ReactElement.createElement = function (type, config, children) { + var propName; + + // Reserved names are extracted + var props = {}; + + var key = null; + var ref = null; + var self = null; + var source = null; + + if (config != null) { + ref = config.ref === undefined ? null : config.ref; + key = config.key === undefined ? null : '' + config.key; + self = config.__self === undefined ? null : config.__self; + source = config.__source === undefined ? null : config.__source; + // Remaining properties are added to a new props object + for (propName in config) { + if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { + props[propName] = config[propName]; + } + } + } + + // Children can be more than one argument, and those are transferred onto + // the newly allocated props object. + var childrenLength = arguments.length - 2; + if (childrenLength === 1) { + props.children = children; + } else if (childrenLength > 1) { + var childArray = Array(childrenLength); + for (var i = 0; i < childrenLength; i++) { + childArray[i] = arguments[i + 2]; + } + props.children = childArray; + } + + // Resolve default props + if (type && type.defaultProps) { + var defaultProps = type.defaultProps; + for (propName in defaultProps) { + if (typeof props[propName] === 'undefined') { + props[propName] = defaultProps[propName]; + } + } + } + + return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); +}; + +ReactElement.createFactory = function (type) { + var factory = ReactElement.createElement.bind(null, type); + // Expose the type on the factory and the prototype so that it can be + // easily accessed on elements. E.g. `<Foo />.type === Foo`. + // This should not be named `constructor` since this may not be the function + // that created the element, and it may not even be a constructor. + // Legacy hook TODO: Warn if this is accessed + factory.type = type; + return factory; +}; + +ReactElement.cloneAndReplaceKey = function (oldElement, newKey) { + var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props); + + return newElement; +}; + +ReactElement.cloneAndReplaceProps = function (oldElement, newProps) { + var newElement = ReactElement(oldElement.type, oldElement.key, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, newProps); + + if ("development" !== 'production') { + // If the key on the original is valid, then the clone is valid + newElement._store.validated = oldElement._store.validated; + } + + return newElement; +}; + +ReactElement.cloneElement = function (element, config, children) { + var propName; + + // Original props are copied + var props = assign({}, element.props); + + // Reserved names are extracted + var key = element.key; + var ref = element.ref; + // Self is preserved since the owner is preserved. + var self = element._self; + // Source is preserved since cloneElement is unlikely to be targeted by a + // transpiler, and the original source is probably a better indicator of the + // true owner. + var source = element._source; + + // Owner will be preserved, unless ref is overridden + var owner = element._owner; + + if (config != null) { + if (config.ref !== undefined) { + // Silently steal the ref from the parent. + ref = config.ref; + owner = ReactCurrentOwner.current; + } + if (config.key !== undefined) { + key = '' + config.key; + } + // Remaining properties override existing props + for (propName in config) { + if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { + props[propName] = config[propName]; + } + } + } + + // Children can be more than one argument, and those are transferred onto + // the newly allocated props object. + var childrenLength = arguments.length - 2; + if (childrenLength === 1) { + props.children = children; + } else if (childrenLength > 1) { + var childArray = Array(childrenLength); + for (var i = 0; i < childrenLength; i++) { + childArray[i] = arguments[i + 2]; + } + props.children = childArray; + } + + return ReactElement(element.type, key, ref, self, source, owner, props); +}; + +/** + * @param {?object} object + * @return {boolean} True if `object` is a valid component. + * @final + */ +ReactElement.isValidElement = function (object) { + return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; +}; + +module.exports = ReactElement; +},{"117":117,"24":24,"39":39}],58:[function(_dereq_,module,exports){ +/** + * Copyright 2014-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactElementValidator + */ + +/** + * ReactElementValidator provides a wrapper around a element factory + * which validates the props passed to the element. This is intended to be + * used only in DEV and could be replaced by a static type checker for languages + * that support it. + */ + +'use strict'; + +var ReactElement = _dereq_(57); +var ReactPropTypeLocations = _dereq_(81); +var ReactPropTypeLocationNames = _dereq_(80); +var ReactCurrentOwner = _dereq_(39); + +var canDefineProperty = _dereq_(117); +var getIteratorFn = _dereq_(129); +var invariant = _dereq_(161); +var warning = _dereq_(173); + +function getDeclarationErrorAddendum() { + if (ReactCurrentOwner.current) { + var name = ReactCurrentOwner.current.getName(); + if (name) { + return ' Check the render method of `' + name + '`.'; + } + } + return ''; +} + +/** + * Warn if there's no key explicitly set on dynamic arrays of children or + * object keys are not valid. This allows us to keep track of children between + * updates. + */ +var ownerHasKeyUseWarning = {}; + +var loggedTypeFailures = {}; + +/** + * Warn if the element doesn't have an explicit key assigned to it. + * This element is in an array. The array could grow and shrink or be + * reordered. All children that haven't already been validated are required to + * have a "key" property assigned to it. + * + * @internal + * @param {ReactElement} element Element that requires a key. + * @param {*} parentType element's parent's type. + */ +function validateExplicitKey(element, parentType) { + if (!element._store || element._store.validated || element.key != null) { + return; + } + element._store.validated = true; + + var addenda = getAddendaForKeyUse('uniqueKey', element, parentType); + if (addenda === null) { + // we already showed the warning + return; + } + "development" !== 'production' ? warning(false, 'Each child in an array or iterator should have a unique "key" prop.' + '%s%s%s', addenda.parentOrOwner || '', addenda.childOwner || '', addenda.url || '') : undefined; +} + +/** + * Shared warning and monitoring code for the key warnings. + * + * @internal + * @param {string} messageType A key used for de-duping warnings. + * @param {ReactElement} element Component that requires a key. + * @param {*} parentType element's parent's type. + * @returns {?object} A set of addenda to use in the warning message, or null + * if the warning has already been shown before (and shouldn't be shown again). + */ +function getAddendaForKeyUse(messageType, element, parentType) { + var addendum = getDeclarationErrorAddendum(); + if (!addendum) { + var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name; + if (parentName) { + addendum = ' Check the top-level render call using <' + parentName + '>.'; + } + } + + var memoizer = ownerHasKeyUseWarning[messageType] || (ownerHasKeyUseWarning[messageType] = {}); + if (memoizer[addendum]) { + return null; + } + memoizer[addendum] = true; + + var addenda = { + parentOrOwner: addendum, + url: ' See https://fb.me/react-warning-keys for more information.', + childOwner: null + }; + + // Usually the current owner is the offender, but if it accepts children as a + // property, it may be the creator of the child that's responsible for + // assigning it a key. + if (element && element._owner && element._owner !== ReactCurrentOwner.current) { + // Give the component that originally created this child. + addenda.childOwner = ' It was passed a child from ' + element._owner.getName() + '.'; + } + + return addenda; +} + +/** + * Ensure that every element either is passed in a static location, in an + * array with an explicit keys property defined, or in an object literal + * with valid key property. + * + * @internal + * @param {ReactNode} node Statically passed child of any type. + * @param {*} parentType node's parent's type. + */ +function validateChildKeys(node, parentType) { + if (typeof node !== 'object') { + return; + } + if (Array.isArray(node)) { + for (var i = 0; i < node.length; i++) { + var child = node[i]; + if (ReactElement.isValidElement(child)) { + validateExplicitKey(child, parentType); + } + } + } else if (ReactElement.isValidElement(node)) { + // This element was passed in a valid location. + if (node._store) { + node._store.validated = true; + } + } else if (node) { + var iteratorFn = getIteratorFn(node); + // Entry iterators provide implicit keys. + if (iteratorFn) { + if (iteratorFn !== node.entries) { + var iterator = iteratorFn.call(node); + var step; + while (!(step = iterator.next()).done) { + if (ReactElement.isValidElement(step.value)) { + validateExplicitKey(step.value, parentType); + } + } + } + } + } +} + +/** + * Assert that the props are valid + * + * @param {string} componentName Name of the component for error messages. + * @param {object} propTypes Map of prop name to a ReactPropType + * @param {object} props + * @param {string} location e.g. "prop", "context", "child context" + * @private + */ +function checkPropTypes(componentName, propTypes, props, location) { + for (var propName in propTypes) { + if (propTypes.hasOwnProperty(propName)) { + var error; + // Prop type validation may throw. In case they do, we don't want to + // fail the render phase where it didn't fail before. So we log it. + // After these have been cleaned up, we'll let them throw. + try { + // This is intentionally an invariant that gets caught. It's the same + // behavior as without this statement except with a better message. + !(typeof propTypes[propName] === 'function') ? "development" !== 'production' ? invariant(false, '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], propName) : invariant(false) : undefined; + error = propTypes[propName](props, propName, componentName, location); + } catch (ex) { + error = ex; + } + "development" !== 'production' ? warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', ReactPropTypeLocationNames[location], propName, typeof error) : undefined; + if (error instanceof Error && !(error.message in loggedTypeFailures)) { + // Only monitor this failure once because there tends to be a lot of the + // same error. + loggedTypeFailures[error.message] = true; + + var addendum = getDeclarationErrorAddendum(); + "development" !== 'production' ? warning(false, 'Failed propType: %s%s', error.message, addendum) : undefined; + } + } + } +} + +/** + * Given an element, validate that its props follow the propTypes definition, + * provided by the type. + * + * @param {ReactElement} element + */ +function validatePropTypes(element) { + var componentClass = element.type; + if (typeof componentClass !== 'function') { + return; + } + var name = componentClass.displayName || componentClass.name; + if (componentClass.propTypes) { + checkPropTypes(name, componentClass.propTypes, element.props, ReactPropTypeLocations.prop); + } + if (typeof componentClass.getDefaultProps === 'function') { + "development" !== 'production' ? warning(componentClass.getDefaultProps.isReactClassApproved, 'getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.') : undefined; + } +} + +var ReactElementValidator = { + + createElement: function (type, props, children) { + var validType = typeof type === 'string' || typeof type === 'function'; + // We warn in this case but don't throw. We expect the element creation to + // succeed and there will likely be errors in render. + "development" !== 'production' ? warning(validType, 'React.createElement: type should not be null, undefined, boolean, or ' + 'number. It should be a string (for DOM elements) or a ReactClass ' + '(for composite components).%s', getDeclarationErrorAddendum()) : undefined; + + var element = ReactElement.createElement.apply(this, arguments); + + // The result can be nullish if a mock or a custom function is used. + // TODO: Drop this when these are no longer allowed as the type argument. + if (element == null) { + return element; + } + + // Skip key warning if the type isn't valid since our key validation logic + // doesn't expect a non-string/function type and can throw confusing errors. + // We don't want exception behavior to differ between dev and prod. + // (Rendering will throw with a helpful message and as soon as the type is + // fixed, the key warnings will appear.) + if (validType) { + for (var i = 2; i < arguments.length; i++) { + validateChildKeys(arguments[i], type); + } + } + + validatePropTypes(element); + + return element; + }, + + createFactory: function (type) { + var validatedFactory = ReactElementValidator.createElement.bind(null, type); + // Legacy hook TODO: Warn if this is accessed + validatedFactory.type = type; + + if ("development" !== 'production') { + if (canDefineProperty) { + Object.defineProperty(validatedFactory, 'type', { + enumerable: false, + get: function () { + "development" !== 'production' ? warning(false, 'Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.') : undefined; + Object.defineProperty(this, 'type', { + value: type + }); + return type; + } + }); + } + } + + return validatedFactory; + }, + + cloneElement: function (element, props, children) { + var newElement = ReactElement.cloneElement.apply(this, arguments); + for (var i = 2; i < arguments.length; i++) { + validateChildKeys(arguments[i], newElement.type); + } + validatePropTypes(newElement); + return newElement; + } + +}; + +module.exports = ReactElementValidator; +},{"117":117,"129":129,"161":161,"173":173,"39":39,"57":57,"80":80,"81":81}],59:[function(_dereq_,module,exports){ +/** + * Copyright 2014-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactEmptyComponent + */ + +'use strict'; + +var ReactElement = _dereq_(57); +var ReactEmptyComponentRegistry = _dereq_(60); +var ReactReconciler = _dereq_(84); + +var assign = _dereq_(24); + +var placeholderElement; + +var ReactEmptyComponentInjection = { + injectEmptyComponent: function (component) { + placeholderElement = ReactElement.createElement(component); + } +}; + +var ReactEmptyComponent = function (instantiate) { + this._currentElement = null; + this._rootNodeID = null; + this._renderedComponent = instantiate(placeholderElement); +}; +assign(ReactEmptyComponent.prototype, { + construct: function (element) {}, + mountComponent: function (rootID, transaction, context) { + ReactEmptyComponentRegistry.registerNullComponentID(rootID); + this._rootNodeID = rootID; + return ReactReconciler.mountComponent(this._renderedComponent, rootID, transaction, context); + }, + receiveComponent: function () {}, + unmountComponent: function (rootID, transaction, context) { + ReactReconciler.unmountComponent(this._renderedComponent); + ReactEmptyComponentRegistry.deregisterNullComponentID(this._rootNodeID); + this._rootNodeID = null; + this._renderedComponent = null; + } +}); + +ReactEmptyComponent.injection = ReactEmptyComponentInjection; + +module.exports = ReactEmptyComponent; +},{"24":24,"57":57,"60":60,"84":84}],60:[function(_dereq_,module,exports){ +/** + * Copyright 2014-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactEmptyComponentRegistry + */ + +'use strict'; + +// This registry keeps track of the React IDs of the components that rendered to +// `null` (in reality a placeholder such as `noscript`) +var nullComponentIDsRegistry = {}; + +/** + * @param {string} id Component's `_rootNodeID`. + * @return {boolean} True if the component is rendered to null. + */ +function isNullComponentID(id) { + return !!nullComponentIDsRegistry[id]; +} + +/** + * Mark the component as having rendered to null. + * @param {string} id Component's `_rootNodeID`. + */ +function registerNullComponentID(id) { + nullComponentIDsRegistry[id] = true; +} + +/** + * Unmark the component as having rendered to null: it renders to something now. + * @param {string} id Component's `_rootNodeID`. + */ +function deregisterNullComponentID(id) { + delete nullComponentIDsRegistry[id]; +} + +var ReactEmptyComponentRegistry = { + isNullComponentID: isNullComponentID, + registerNullComponentID: registerNullComponentID, + deregisterNullComponentID: deregisterNullComponentID +}; + +module.exports = ReactEmptyComponentRegistry; +},{}],61:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactErrorUtils + * @typechecks + */ + +'use strict'; + +var caughtError = null; + +/** + * Call a function while guarding against errors that happens within it. + * + * @param {?String} name of the guard to use for logging or debugging + * @param {Function} func The function to invoke + * @param {*} a First argument + * @param {*} b Second argument + */ +function invokeGuardedCallback(name, func, a, b) { + try { + return func(a, b); + } catch (x) { + if (caughtError === null) { + caughtError = x; + } + return undefined; + } +} + +var ReactErrorUtils = { + invokeGuardedCallback: invokeGuardedCallback, + + /** + * Invoked by ReactTestUtils.Simulate so that any errors thrown by the event + * handler are sure to be rethrown by rethrowCaughtError. + */ + invokeGuardedCallbackWithCatch: invokeGuardedCallback, + + /** + * During execution of guarded functions we will capture the first error which + * we will rethrow to be handled by the top level error handler. + */ + rethrowCaughtError: function () { + if (caughtError) { + var error = caughtError; + caughtError = null; + throw error; + } + } +}; + +if ("development" !== 'production') { + /** + * To help development we can get better devtools integration by simulating a + * real browser event. + */ + if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') { + var fakeNode = document.createElementNS('http://www.w3.org/1999/xhtml', 'react'); + ReactErrorUtils.invokeGuardedCallback = function (name, func, a, b) { + var boundFunc = func.bind(null, a, b); + var evtType = 'react-' + name; + fakeNode.addEventListener(evtType, boundFunc, false); + var evt = document.createEvent('Event'); + evt.initEvent(evtType, false, false); + fakeNode.dispatchEvent(evt); + fakeNode.removeEventListener(evtType, boundFunc, false); + }; + } +} + +module.exports = ReactErrorUtils; +},{}],62:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactEventEmitterMixin + */ + +'use strict'; + +var EventPluginHub = _dereq_(16); + +function runEventQueueInBatch(events) { + EventPluginHub.enqueueEvents(events); + EventPluginHub.processEventQueue(false); +} + +var ReactEventEmitterMixin = { + + /** + * Streams a fired top-level event to `EventPluginHub` where plugins have the + * opportunity to create `ReactEvent`s to be dispatched. + * + * @param {string} topLevelType Record from `EventConstants`. + * @param {object} topLevelTarget The listening component root node. + * @param {string} topLevelTargetID ID of `topLevelTarget`. + * @param {object} nativeEvent Native environment event. + */ + handleTopLevel: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) { + var events = EventPluginHub.extractEvents(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget); + runEventQueueInBatch(events); + } +}; + +module.exports = ReactEventEmitterMixin; +},{"16":16}],63:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactEventListener + * @typechecks static-only + */ + +'use strict'; + +var EventListener = _dereq_(146); +var ExecutionEnvironment = _dereq_(147); +var PooledClass = _dereq_(25); +var ReactInstanceHandles = _dereq_(67); +var ReactMount = _dereq_(72); +var ReactUpdates = _dereq_(96); + +var assign = _dereq_(24); +var getEventTarget = _dereq_(128); +var getUnboundedScrollPosition = _dereq_(158); + +var DOCUMENT_FRAGMENT_NODE_TYPE = 11; + +/** + * Finds the parent React component of `node`. + * + * @param {*} node + * @return {?DOMEventTarget} Parent container, or `null` if the specified node + * is not nested. + */ +function findParent(node) { + // TODO: It may be a good idea to cache this to prevent unnecessary DOM + // traversal, but caching is difficult to do correctly without using a + // mutation observer to listen for all DOM changes. + var nodeID = ReactMount.getID(node); + var rootID = ReactInstanceHandles.getReactRootIDFromNodeID(nodeID); + var container = ReactMount.findReactContainerForID(rootID); + var parent = ReactMount.getFirstReactDOM(container); + return parent; +} + +// Used to store ancestor hierarchy in top level callback +function TopLevelCallbackBookKeeping(topLevelType, nativeEvent) { + this.topLevelType = topLevelType; + this.nativeEvent = nativeEvent; + this.ancestors = []; +} +assign(TopLevelCallbackBookKeeping.prototype, { + destructor: function () { + this.topLevelType = null; + this.nativeEvent = null; + this.ancestors.length = 0; + } +}); +PooledClass.addPoolingTo(TopLevelCallbackBookKeeping, PooledClass.twoArgumentPooler); + +function handleTopLevelImpl(bookKeeping) { + // TODO: Re-enable event.path handling + // + // if (bookKeeping.nativeEvent.path && bookKeeping.nativeEvent.path.length > 1) { + // // New browsers have a path attribute on native events + // handleTopLevelWithPath(bookKeeping); + // } else { + // // Legacy browsers don't have a path attribute on native events + // handleTopLevelWithoutPath(bookKeeping); + // } + + void handleTopLevelWithPath; // temporarily unused + handleTopLevelWithoutPath(bookKeeping); +} + +// Legacy browsers don't have a path attribute on native events +function handleTopLevelWithoutPath(bookKeeping) { + var topLevelTarget = ReactMount.getFirstReactDOM(getEventTarget(bookKeeping.nativeEvent)) || window; + + // Loop through the hierarchy, in case there's any nested components. + // It's important that we build the array of ancestors before calling any + // event handlers, because event handlers can modify the DOM, leading to + // inconsistencies with ReactMount's node cache. See #1105. + var ancestor = topLevelTarget; + while (ancestor) { + bookKeeping.ancestors.push(ancestor); + ancestor = findParent(ancestor); + } + + for (var i = 0; i < bookKeeping.ancestors.length; i++) { + topLevelTarget = bookKeeping.ancestors[i]; + var topLevelTargetID = ReactMount.getID(topLevelTarget) || ''; + ReactEventListener._handleTopLevel(bookKeeping.topLevelType, topLevelTarget, topLevelTargetID, bookKeeping.nativeEvent, getEventTarget(bookKeeping.nativeEvent)); + } +} + +// New browsers have a path attribute on native events +function handleTopLevelWithPath(bookKeeping) { + var path = bookKeeping.nativeEvent.path; + var currentNativeTarget = path[0]; + var eventsFired = 0; + for (var i = 0; i < path.length; i++) { + var currentPathElement = path[i]; + if (currentPathElement.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE) { + currentNativeTarget = path[i + 1]; + } + // TODO: slow + var reactParent = ReactMount.getFirstReactDOM(currentPathElement); + if (reactParent === currentPathElement) { + var currentPathElementID = ReactMount.getID(currentPathElement); + var newRootID = ReactInstanceHandles.getReactRootIDFromNodeID(currentPathElementID); + bookKeeping.ancestors.push(currentPathElement); + + var topLevelTargetID = ReactMount.getID(currentPathElement) || ''; + eventsFired++; + ReactEventListener._handleTopLevel(bookKeeping.topLevelType, currentPathElement, topLevelTargetID, bookKeeping.nativeEvent, currentNativeTarget); + + // Jump to the root of this React render tree + while (currentPathElementID !== newRootID) { + i++; + currentPathElement = path[i]; + currentPathElementID = ReactMount.getID(currentPathElement); + } + } + } + if (eventsFired === 0) { + ReactEventListener._handleTopLevel(bookKeeping.topLevelType, window, '', bookKeeping.nativeEvent, getEventTarget(bookKeeping.nativeEvent)); + } +} + +function scrollValueMonitor(cb) { + var scrollPosition = getUnboundedScrollPosition(window); + cb(scrollPosition); +} + +var ReactEventListener = { + _enabled: true, + _handleTopLevel: null, + + WINDOW_HANDLE: ExecutionEnvironment.canUseDOM ? window : null, + + setHandleTopLevel: function (handleTopLevel) { + ReactEventListener._handleTopLevel = handleTopLevel; + }, + + setEnabled: function (enabled) { + ReactEventListener._enabled = !!enabled; + }, + + isEnabled: function () { + return ReactEventListener._enabled; + }, + + /** + * Traps top-level events by using event bubbling. + * + * @param {string} topLevelType Record from `EventConstants`. + * @param {string} handlerBaseName Event name (e.g. "click"). + * @param {object} handle Element on which to attach listener. + * @return {?object} An object with a remove function which will forcefully + * remove the listener. + * @internal + */ + trapBubbledEvent: function (topLevelType, handlerBaseName, handle) { + var element = handle; + if (!element) { + return null; + } + return EventListener.listen(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType)); + }, + + /** + * Traps a top-level event by using event capturing. + * + * @param {string} topLevelType Record from `EventConstants`. + * @param {string} handlerBaseName Event name (e.g. "click"). + * @param {object} handle Element on which to attach listener. + * @return {?object} An object with a remove function which will forcefully + * remove the listener. + * @internal + */ + trapCapturedEvent: function (topLevelType, handlerBaseName, handle) { + var element = handle; + if (!element) { + return null; + } + return EventListener.capture(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType)); + }, + + monitorScrollValue: function (refresh) { + var callback = scrollValueMonitor.bind(null, refresh); + EventListener.listen(window, 'scroll', callback); + }, + + dispatchEvent: function (topLevelType, nativeEvent) { + if (!ReactEventListener._enabled) { + return; + } + + var bookKeeping = TopLevelCallbackBookKeeping.getPooled(topLevelType, nativeEvent); + try { + // Event queue being processed in the same cycle allows + // `preventDefault`. + ReactUpdates.batchedUpdates(handleTopLevelImpl, bookKeeping); + } finally { + TopLevelCallbackBookKeeping.release(bookKeeping); + } + } +}; + +module.exports = ReactEventListener; +},{"128":128,"146":146,"147":147,"158":158,"24":24,"25":25,"67":67,"72":72,"96":96}],64:[function(_dereq_,module,exports){ +/** + * Copyright 2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactFragment + */ + +'use strict'; + +var ReactChildren = _dereq_(32); +var ReactElement = _dereq_(57); + +var emptyFunction = _dereq_(153); +var invariant = _dereq_(161); +var warning = _dereq_(173); + +/** + * We used to allow keyed objects to serve as a collection of ReactElements, + * or nested sets. This allowed us a way to explicitly key a set a fragment of + * components. This is now being replaced with an opaque data structure. + * The upgrade path is to call React.addons.createFragment({ key: value }) to + * create a keyed fragment. The resulting data structure is an array. + */ + +var numericPropertyRegex = /^\d+$/; + +var warnedAboutNumeric = false; + +var ReactFragment = { + // Wrap a keyed object in an opaque proxy that warns you if you access any + // of its properties. + create: function (object) { + if (typeof object !== 'object' || !object || Array.isArray(object)) { + "development" !== 'production' ? warning(false, 'React.addons.createFragment only accepts a single object. Got: %s', object) : undefined; + return object; + } + if (ReactElement.isValidElement(object)) { + "development" !== 'production' ? warning(false, 'React.addons.createFragment does not accept a ReactElement ' + 'without a wrapper object.') : undefined; + return object; + } + + !(object.nodeType !== 1) ? "development" !== 'production' ? invariant(false, 'React.addons.createFragment(...): Encountered an invalid child; DOM ' + 'elements are not valid children of React components.') : invariant(false) : undefined; + + var result = []; + + for (var key in object) { + if ("development" !== 'production') { + if (!warnedAboutNumeric && numericPropertyRegex.test(key)) { + "development" !== 'production' ? warning(false, 'React.addons.createFragment(...): Child objects should have ' + 'non-numeric keys so ordering is preserved.') : undefined; + warnedAboutNumeric = true; + } + } + ReactChildren.mapIntoWithKeyPrefixInternal(object[key], result, key, emptyFunction.thatReturnsArgument); + } + + return result; + } +}; + +module.exports = ReactFragment; +},{"153":153,"161":161,"173":173,"32":32,"57":57}],65:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactInjection + */ + +'use strict'; + +var DOMProperty = _dereq_(10); +var EventPluginHub = _dereq_(16); +var ReactComponentEnvironment = _dereq_(36); +var ReactClass = _dereq_(33); +var ReactEmptyComponent = _dereq_(59); +var ReactBrowserEventEmitter = _dereq_(28); +var ReactNativeComponent = _dereq_(75); +var ReactPerf = _dereq_(78); +var ReactRootIndex = _dereq_(86); +var ReactUpdates = _dereq_(96); + +var ReactInjection = { + Component: ReactComponentEnvironment.injection, + Class: ReactClass.injection, + DOMProperty: DOMProperty.injection, + EmptyComponent: ReactEmptyComponent.injection, + EventPluginHub: EventPluginHub.injection, + EventEmitter: ReactBrowserEventEmitter.injection, + NativeComponent: ReactNativeComponent.injection, + Perf: ReactPerf.injection, + RootIndex: ReactRootIndex.injection, + Updates: ReactUpdates.injection +}; + +module.exports = ReactInjection; +},{"10":10,"16":16,"28":28,"33":33,"36":36,"59":59,"75":75,"78":78,"86":86,"96":96}],66:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactInputSelection + */ + +'use strict'; + +var ReactDOMSelection = _dereq_(49); + +var containsNode = _dereq_(150); +var focusNode = _dereq_(155); +var getActiveElement = _dereq_(156); + +function isInDocument(node) { + return containsNode(document.documentElement, node); +} + +/** + * @ReactInputSelection: React input selection module. Based on Selection.js, + * but modified to be suitable for react and has a couple of bug fixes (doesn't + * assume buttons have range selections allowed). + * Input selection module for React. + */ +var ReactInputSelection = { + + hasSelectionCapabilities: function (elem) { + var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); + return nodeName && (nodeName === 'input' && elem.type === 'text' || nodeName === 'textarea' || elem.contentEditable === 'true'); + }, + + getSelectionInformation: function () { + var focusedElem = getActiveElement(); + return { + focusedElem: focusedElem, + selectionRange: ReactInputSelection.hasSelectionCapabilities(focusedElem) ? ReactInputSelection.getSelection(focusedElem) : null + }; + }, + + /** + * @restoreSelection: If any selection information was potentially lost, + * restore it. This is useful when performing operations that could remove dom + * nodes and place them back in, resulting in focus being lost. + */ + restoreSelection: function (priorSelectionInformation) { + var curFocusedElem = getActiveElement(); + var priorFocusedElem = priorSelectionInformation.focusedElem; + var priorSelectionRange = priorSelectionInformation.selectionRange; + if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) { + if (ReactInputSelection.hasSelectionCapabilities(priorFocusedElem)) { + ReactInputSelection.setSelection(priorFocusedElem, priorSelectionRange); + } + focusNode(priorFocusedElem); + } + }, + + /** + * @getSelection: Gets the selection bounds of a focused textarea, input or + * contentEditable node. + * -@input: Look up selection bounds of this input + * -@return {start: selectionStart, end: selectionEnd} + */ + getSelection: function (input) { + var selection; + + if ('selectionStart' in input) { + // Modern browser with input or textarea. + selection = { + start: input.selectionStart, + end: input.selectionEnd + }; + } else if (document.selection && (input.nodeName && input.nodeName.toLowerCase() === 'input')) { + // IE8 input. + var range = document.selection.createRange(); + // There can only be one selection per document in IE, so it must + // be in our element. + if (range.parentElement() === input) { + selection = { + start: -range.moveStart('character', -input.value.length), + end: -range.moveEnd('character', -input.value.length) + }; + } + } else { + // Content editable or old IE textarea. + selection = ReactDOMSelection.getOffsets(input); + } + + return selection || { start: 0, end: 0 }; + }, + + /** + * @setSelection: Sets the selection bounds of a textarea or input and focuses + * the input. + * -@input Set selection bounds of this input or textarea + * -@offsets Object of same form that is returned from get* + */ + setSelection: function (input, offsets) { + var start = offsets.start; + var end = offsets.end; + if (typeof end === 'undefined') { + end = start; + } + + if ('selectionStart' in input) { + input.selectionStart = start; + input.selectionEnd = Math.min(end, input.value.length); + } else if (document.selection && (input.nodeName && input.nodeName.toLowerCase() === 'input')) { + var range = input.createTextRange(); + range.collapse(true); + range.moveStart('character', start); + range.moveEnd('character', end - start); + range.select(); + } else { + ReactDOMSelection.setOffsets(input, offsets); + } + } +}; + +module.exports = ReactInputSelection; +},{"150":150,"155":155,"156":156,"49":49}],67:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactInstanceHandles + * @typechecks static-only + */ + +'use strict'; + +var ReactRootIndex = _dereq_(86); + +var invariant = _dereq_(161); + +var SEPARATOR = '.'; +var SEPARATOR_LENGTH = SEPARATOR.length; + +/** + * Maximum depth of traversals before we consider the possibility of a bad ID. + */ +var MAX_TREE_DEPTH = 10000; + +/** + * Creates a DOM ID prefix to use when mounting React components. + * + * @param {number} index A unique integer + * @return {string} React root ID. + * @internal + */ +function getReactRootIDString(index) { + return SEPARATOR + index.toString(36); +} + +/** + * Checks if a character in the supplied ID is a separator or the end. + * + * @param {string} id A React DOM ID. + * @param {number} index Index of the character to check. + * @return {boolean} True if the character is a separator or end of the ID. + * @private + */ +function isBoundary(id, index) { + return id.charAt(index) === SEPARATOR || index === id.length; +} + +/** + * Checks if the supplied string is a valid React DOM ID. + * + * @param {string} id A React DOM ID, maybe. + * @return {boolean} True if the string is a valid React DOM ID. + * @private + */ +function isValidID(id) { + return id === '' || id.charAt(0) === SEPARATOR && id.charAt(id.length - 1) !== SEPARATOR; +} + +/** + * Checks if the first ID is an ancestor of or equal to the second ID. + * + * @param {string} ancestorID + * @param {string} descendantID + * @return {boolean} True if `ancestorID` is an ancestor of `descendantID`. + * @internal + */ +function isAncestorIDOf(ancestorID, descendantID) { + return descendantID.indexOf(ancestorID) === 0 && isBoundary(descendantID, ancestorID.length); +} + +/** + * Gets the parent ID of the supplied React DOM ID, `id`. + * + * @param {string} id ID of a component. + * @return {string} ID of the parent, or an empty string. + * @private + */ +function getParentID(id) { + return id ? id.substr(0, id.lastIndexOf(SEPARATOR)) : ''; +} + +/** + * Gets the next DOM ID on the tree path from the supplied `ancestorID` to the + * supplied `destinationID`. If they are equal, the ID is returned. + * + * @param {string} ancestorID ID of an ancestor node of `destinationID`. + * @param {string} destinationID ID of the destination node. + * @return {string} Next ID on the path from `ancestorID` to `destinationID`. + * @private + */ +function getNextDescendantID(ancestorID, destinationID) { + !(isValidID(ancestorID) && isValidID(destinationID)) ? "development" !== 'production' ? invariant(false, 'getNextDescendantID(%s, %s): Received an invalid React DOM ID.', ancestorID, destinationID) : invariant(false) : undefined; + !isAncestorIDOf(ancestorID, destinationID) ? "development" !== 'production' ? invariant(false, 'getNextDescendantID(...): React has made an invalid assumption about ' + 'the DOM hierarchy. Expected `%s` to be an ancestor of `%s`.', ancestorID, destinationID) : invariant(false) : undefined; + if (ancestorID === destinationID) { + return ancestorID; + } + // Skip over the ancestor and the immediate separator. Traverse until we hit + // another separator or we reach the end of `destinationID`. + var start = ancestorID.length + SEPARATOR_LENGTH; + var i; + for (i = start; i < destinationID.length; i++) { + if (isBoundary(destinationID, i)) { + break; + } + } + return destinationID.substr(0, i); +} + +/** + * Gets the nearest common ancestor ID of two IDs. + * + * Using this ID scheme, the nearest common ancestor ID is the longest common + * prefix of the two IDs that immediately preceded a "marker" in both strings. + * + * @param {string} oneID + * @param {string} twoID + * @return {string} Nearest common ancestor ID, or the empty string if none. + * @private + */ +function getFirstCommonAncestorID(oneID, twoID) { + var minLength = Math.min(oneID.length, twoID.length); + if (minLength === 0) { + return ''; + } + var lastCommonMarkerIndex = 0; + // Use `<=` to traverse until the "EOL" of the shorter string. + for (var i = 0; i <= minLength; i++) { + if (isBoundary(oneID, i) && isBoundary(twoID, i)) { + lastCommonMarkerIndex = i; + } else if (oneID.charAt(i) !== twoID.charAt(i)) { + break; + } + } + var longestCommonID = oneID.substr(0, lastCommonMarkerIndex); + !isValidID(longestCommonID) ? "development" !== 'production' ? invariant(false, 'getFirstCommonAncestorID(%s, %s): Expected a valid React DOM ID: %s', oneID, twoID, longestCommonID) : invariant(false) : undefined; + return longestCommonID; +} + +/** + * Traverses the parent path between two IDs (either up or down). The IDs must + * not be the same, and there must exist a parent path between them. If the + * callback returns `false`, traversal is stopped. + * + * @param {?string} start ID at which to start traversal. + * @param {?string} stop ID at which to end traversal. + * @param {function} cb Callback to invoke each ID with. + * @param {*} arg Argument to invoke the callback with. + * @param {?boolean} skipFirst Whether or not to skip the first node. + * @param {?boolean} skipLast Whether or not to skip the last node. + * @private + */ +function traverseParentPath(start, stop, cb, arg, skipFirst, skipLast) { + start = start || ''; + stop = stop || ''; + !(start !== stop) ? "development" !== 'production' ? invariant(false, 'traverseParentPath(...): Cannot traverse from and to the same ID, `%s`.', start) : invariant(false) : undefined; + var traverseUp = isAncestorIDOf(stop, start); + !(traverseUp || isAncestorIDOf(start, stop)) ? "development" !== 'production' ? invariant(false, 'traverseParentPath(%s, %s, ...): Cannot traverse from two IDs that do ' + 'not have a parent path.', start, stop) : invariant(false) : undefined; + // Traverse from `start` to `stop` one depth at a time. + var depth = 0; + var traverse = traverseUp ? getParentID : getNextDescendantID; + for (var id = start;; /* until break */id = traverse(id, stop)) { + var ret; + if ((!skipFirst || id !== start) && (!skipLast || id !== stop)) { + ret = cb(id, traverseUp, arg); + } + if (ret === false || id === stop) { + // Only break //after// visiting `stop`. + break; + } + !(depth++ < MAX_TREE_DEPTH) ? "development" !== 'production' ? invariant(false, 'traverseParentPath(%s, %s, ...): Detected an infinite loop while ' + 'traversing the React DOM ID tree. This may be due to malformed IDs: %s', start, stop, id) : invariant(false) : undefined; + } +} + +/** + * Manages the IDs assigned to DOM representations of React components. This + * uses a specific scheme in order to traverse the DOM efficiently (e.g. in + * order to simulate events). + * + * @internal + */ +var ReactInstanceHandles = { + + /** + * Constructs a React root ID + * @return {string} A React root ID. + */ + createReactRootID: function () { + return getReactRootIDString(ReactRootIndex.createReactRootIndex()); + }, + + /** + * Constructs a React ID by joining a root ID with a name. + * + * @param {string} rootID Root ID of a parent component. + * @param {string} name A component's name (as flattened children). + * @return {string} A React ID. + * @internal + */ + createReactID: function (rootID, name) { + return rootID + name; + }, + + /** + * Gets the DOM ID of the React component that is the root of the tree that + * contains the React component with the supplied DOM ID. + * + * @param {string} id DOM ID of a React component. + * @return {?string} DOM ID of the React component that is the root. + * @internal + */ + getReactRootIDFromNodeID: function (id) { + if (id && id.charAt(0) === SEPARATOR && id.length > 1) { + var index = id.indexOf(SEPARATOR, 1); + return index > -1 ? id.substr(0, index) : id; + } + return null; + }, + + /** + * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that + * should would receive a `mouseEnter` or `mouseLeave` event. + * + * NOTE: Does not invoke the callback on the nearest common ancestor because + * nothing "entered" or "left" that element. + * + * @param {string} leaveID ID being left. + * @param {string} enterID ID being entered. + * @param {function} cb Callback to invoke on each entered/left ID. + * @param {*} upArg Argument to invoke the callback with on left IDs. + * @param {*} downArg Argument to invoke the callback with on entered IDs. + * @internal + */ + traverseEnterLeave: function (leaveID, enterID, cb, upArg, downArg) { + var ancestorID = getFirstCommonAncestorID(leaveID, enterID); + if (ancestorID !== leaveID) { + traverseParentPath(leaveID, ancestorID, cb, upArg, false, true); + } + if (ancestorID !== enterID) { + traverseParentPath(ancestorID, enterID, cb, downArg, true, false); + } + }, + + /** + * Simulates the traversal of a two-phase, capture/bubble event dispatch. + * + * NOTE: This traversal happens on IDs without touching the DOM. + * + * @param {string} targetID ID of the target node. + * @param {function} cb Callback to invoke. + * @param {*} arg Argument to invoke the callback with. + * @internal + */ + traverseTwoPhase: function (targetID, cb, arg) { + if (targetID) { + traverseParentPath('', targetID, cb, arg, true, false); + traverseParentPath(targetID, '', cb, arg, false, true); + } + }, + + /** + * Same as `traverseTwoPhase` but skips the `targetID`. + */ + traverseTwoPhaseSkipTarget: function (targetID, cb, arg) { + if (targetID) { + traverseParentPath('', targetID, cb, arg, true, true); + traverseParentPath(targetID, '', cb, arg, true, true); + } + }, + + /** + * Traverse a node ID, calling the supplied `cb` for each ancestor ID. For + * example, passing `.0.$row-0.1` would result in `cb` getting called + * with `.0`, `.0.$row-0`, and `.0.$row-0.1`. + * + * NOTE: This traversal happens on IDs without touching the DOM. + * + * @param {string} targetID ID of the target node. + * @param {function} cb Callback to invoke. + * @param {*} arg Argument to invoke the callback with. + * @internal + */ + traverseAncestors: function (targetID, cb, arg) { + traverseParentPath('', targetID, cb, arg, true, false); + }, + + getFirstCommonAncestorID: getFirstCommonAncestorID, + + /** + * Exposed for unit testing. + * @private + */ + _getNextDescendantID: getNextDescendantID, + + isAncestorIDOf: isAncestorIDOf, + + SEPARATOR: SEPARATOR + +}; + +module.exports = ReactInstanceHandles; +},{"161":161,"86":86}],68:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactInstanceMap + */ + +'use strict'; + +/** + * `ReactInstanceMap` maintains a mapping from a public facing stateful + * instance (key) and the internal representation (value). This allows public + * methods to accept the user facing instance as an argument and map them back + * to internal methods. + */ + +// TODO: Replace this with ES6: var ReactInstanceMap = new Map(); +var ReactInstanceMap = { + + /** + * This API should be called `delete` but we'd have to make sure to always + * transform these to strings for IE support. When this transform is fully + * supported we can rename it. + */ + remove: function (key) { + key._reactInternalInstance = undefined; + }, + + get: function (key) { + return key._reactInternalInstance; + }, + + has: function (key) { + return key._reactInternalInstance !== undefined; + }, + + set: function (key, value) { + key._reactInternalInstance = value; + } + +}; + +module.exports = ReactInstanceMap; +},{}],69:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactIsomorphic + */ + +'use strict'; + +var ReactChildren = _dereq_(32); +var ReactComponent = _dereq_(34); +var ReactClass = _dereq_(33); +var ReactDOMFactories = _dereq_(43); +var ReactElement = _dereq_(57); +var ReactElementValidator = _dereq_(58); +var ReactPropTypes = _dereq_(82); +var ReactVersion = _dereq_(97); + +var assign = _dereq_(24); +var onlyChild = _dereq_(135); + +var createElement = ReactElement.createElement; +var createFactory = ReactElement.createFactory; +var cloneElement = ReactElement.cloneElement; + +if ("development" !== 'production') { + createElement = ReactElementValidator.createElement; + createFactory = ReactElementValidator.createFactory; + cloneElement = ReactElementValidator.cloneElement; +} + +var React = { + + // Modern + + Children: { + map: ReactChildren.map, + forEach: ReactChildren.forEach, + count: ReactChildren.count, + toArray: ReactChildren.toArray, + only: onlyChild + }, + + Component: ReactComponent, + + createElement: createElement, + cloneElement: cloneElement, + isValidElement: ReactElement.isValidElement, + + // Classic + + PropTypes: ReactPropTypes, + createClass: ReactClass.createClass, + createFactory: createFactory, + createMixin: function (mixin) { + // Currently a noop. Will be used to validate and trace mixins. + return mixin; + }, + + // This looks DOM specific but these are actually isomorphic helpers + // since they are just generating DOM strings. + DOM: ReactDOMFactories, + + version: ReactVersion, + + // Hook for JSX spread, don't use this for anything else. + __spread: assign +}; + +module.exports = React; +},{"135":135,"24":24,"32":32,"33":33,"34":34,"43":43,"57":57,"58":58,"82":82,"97":97}],70:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactLink + * @typechecks static-only + */ + +'use strict'; + +/** + * ReactLink encapsulates a common pattern in which a component wants to modify + * a prop received from its parent. ReactLink allows the parent to pass down a + * value coupled with a callback that, when invoked, expresses an intent to + * modify that value. For example: + * + * React.createClass({ + * getInitialState: function() { + * return {value: ''}; + * }, + * render: function() { + * var valueLink = new ReactLink(this.state.value, this._handleValueChange); + * return <input valueLink={valueLink} />; + * }, + * _handleValueChange: function(newValue) { + * this.setState({value: newValue}); + * } + * }); + * + * We have provided some sugary mixins to make the creation and + * consumption of ReactLink easier; see LinkedValueUtils and LinkedStateMixin. + */ + +var React = _dereq_(26); + +/** + * @param {*} value current value of the link + * @param {function} requestChange callback to request a change + */ +function ReactLink(value, requestChange) { + this.value = value; + this.requestChange = requestChange; +} + +/** + * Creates a PropType that enforces the ReactLink API and optionally checks the + * type of the value being passed inside the link. Example: + * + * MyComponent.propTypes = { + * tabIndexLink: ReactLink.PropTypes.link(React.PropTypes.number) + * } + */ +function createLinkTypeChecker(linkType) { + var shapes = { + value: typeof linkType === 'undefined' ? React.PropTypes.any.isRequired : linkType.isRequired, + requestChange: React.PropTypes.func.isRequired + }; + return React.PropTypes.shape(shapes); +} + +ReactLink.PropTypes = { + link: createLinkTypeChecker +}; + +module.exports = ReactLink; +},{"26":26}],71:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactMarkupChecksum + */ + +'use strict'; + +var adler32 = _dereq_(116); + +var TAG_END = /\/?>/; + +var ReactMarkupChecksum = { + CHECKSUM_ATTR_NAME: 'data-react-checksum', + + /** + * @param {string} markup Markup string + * @return {string} Markup string with checksum attribute attached + */ + addChecksumToMarkup: function (markup) { + var checksum = adler32(markup); + + // Add checksum (handle both parent tags and self-closing tags) + return markup.replace(TAG_END, ' ' + ReactMarkupChecksum.CHECKSUM_ATTR_NAME + '="' + checksum + '"$&'); + }, + + /** + * @param {string} markup to use + * @param {DOMElement} element root React element + * @returns {boolean} whether or not the markup is the same + */ + canReuseMarkup: function (markup, element) { + var existingChecksum = element.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME); + existingChecksum = existingChecksum && parseInt(existingChecksum, 10); + var markupChecksum = adler32(markup); + return markupChecksum === existingChecksum; + } +}; + +module.exports = ReactMarkupChecksum; +},{"116":116}],72:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactMount + */ + +'use strict'; + +var DOMProperty = _dereq_(10); +var ReactBrowserEventEmitter = _dereq_(28); +var ReactCurrentOwner = _dereq_(39); +var ReactDOMFeatureFlags = _dereq_(44); +var ReactElement = _dereq_(57); +var ReactEmptyComponentRegistry = _dereq_(60); +var ReactInstanceHandles = _dereq_(67); +var ReactInstanceMap = _dereq_(68); +var ReactMarkupChecksum = _dereq_(71); +var ReactPerf = _dereq_(78); +var ReactReconciler = _dereq_(84); +var ReactUpdateQueue = _dereq_(95); +var ReactUpdates = _dereq_(96); + +var assign = _dereq_(24); +var emptyObject = _dereq_(154); +var containsNode = _dereq_(150); +var instantiateReactComponent = _dereq_(132); +var invariant = _dereq_(161); +var setInnerHTML = _dereq_(138); +var shouldUpdateReactComponent = _dereq_(141); +var validateDOMNesting = _dereq_(144); +var warning = _dereq_(173); + +var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME; +var nodeCache = {}; + +var ELEMENT_NODE_TYPE = 1; +var DOC_NODE_TYPE = 9; +var DOCUMENT_FRAGMENT_NODE_TYPE = 11; + +var ownerDocumentContextKey = '__ReactMount_ownerDocument$' + Math.random().toString(36).slice(2); + +/** Mapping from reactRootID to React component instance. */ +var instancesByReactRootID = {}; + +/** Mapping from reactRootID to `container` nodes. */ +var containersByReactRootID = {}; + +if ("development" !== 'production') { + /** __DEV__-only mapping from reactRootID to root elements. */ + var rootElementsByReactRootID = {}; +} + +// Used to store breadth-first search state in findComponentRoot. +var findComponentRootReusableArray = []; + +/** + * Finds the index of the first character + * that's not common between the two given strings. + * + * @return {number} the index of the character where the strings diverge + */ +function firstDifferenceIndex(string1, string2) { + var minLen = Math.min(string1.length, string2.length); + for (var i = 0; i < minLen; i++) { + if (string1.charAt(i) !== string2.charAt(i)) { + return i; + } + } + return string1.length === string2.length ? -1 : minLen; +} + +/** + * @param {DOMElement|DOMDocument} container DOM element that may contain + * a React component + * @return {?*} DOM element that may have the reactRoot ID, or null. + */ +function getReactRootElementInContainer(container) { + if (!container) { + return null; + } + + if (container.nodeType === DOC_NODE_TYPE) { + return container.documentElement; + } else { + return container.firstChild; + } +} + +/** + * @param {DOMElement} container DOM element that may contain a React component. + * @return {?string} A "reactRoot" ID, if a React component is rendered. + */ +function getReactRootID(container) { + var rootElement = getReactRootElementInContainer(container); + return rootElement && ReactMount.getID(rootElement); +} + +/** + * Accessing node[ATTR_NAME] or calling getAttribute(ATTR_NAME) on a form + * element can return its control whose name or ID equals ATTR_NAME. All + * DOM nodes support `getAttributeNode` but this can also get called on + * other objects so just return '' if we're given something other than a + * DOM node (such as window). + * + * @param {?DOMElement|DOMWindow|DOMDocument|DOMTextNode} node DOM node. + * @return {string} ID of the supplied `domNode`. + */ +function getID(node) { + var id = internalGetID(node); + if (id) { + if (nodeCache.hasOwnProperty(id)) { + var cached = nodeCache[id]; + if (cached !== node) { + !!isValid(cached, id) ? "development" !== 'production' ? invariant(false, 'ReactMount: Two valid but unequal nodes with the same `%s`: %s', ATTR_NAME, id) : invariant(false) : undefined; + + nodeCache[id] = node; + } + } else { + nodeCache[id] = node; + } + } + + return id; +} + +function internalGetID(node) { + // If node is something like a window, document, or text node, none of + // which support attributes or a .getAttribute method, gracefully return + // the empty string, as if the attribute were missing. + return node && node.getAttribute && node.getAttribute(ATTR_NAME) || ''; +} + +/** + * Sets the React-specific ID of the given node. + * + * @param {DOMElement} node The DOM node whose ID will be set. + * @param {string} id The value of the ID attribute. + */ +function setID(node, id) { + var oldID = internalGetID(node); + if (oldID !== id) { + delete nodeCache[oldID]; + } + node.setAttribute(ATTR_NAME, id); + nodeCache[id] = node; +} + +/** + * Finds the node with the supplied React-generated DOM ID. + * + * @param {string} id A React-generated DOM ID. + * @return {DOMElement} DOM node with the suppled `id`. + * @internal + */ +function getNode(id) { + if (!nodeCache.hasOwnProperty(id) || !isValid(nodeCache[id], id)) { + nodeCache[id] = ReactMount.findReactNodeByID(id); + } + return nodeCache[id]; +} + +/** + * Finds the node with the supplied public React instance. + * + * @param {*} instance A public React instance. + * @return {?DOMElement} DOM node with the suppled `id`. + * @internal + */ +function getNodeFromInstance(instance) { + var id = ReactInstanceMap.get(instance)._rootNodeID; + if (ReactEmptyComponentRegistry.isNullComponentID(id)) { + return null; + } + if (!nodeCache.hasOwnProperty(id) || !isValid(nodeCache[id], id)) { + nodeCache[id] = ReactMount.findReactNodeByID(id); + } + return nodeCache[id]; +} + +/** + * A node is "valid" if it is contained by a currently mounted container. + * + * This means that the node does not have to be contained by a document in + * order to be considered valid. + * + * @param {?DOMElement} node The candidate DOM node. + * @param {string} id The expected ID of the node. + * @return {boolean} Whether the node is contained by a mounted container. + */ +function isValid(node, id) { + if (node) { + !(internalGetID(node) === id) ? "development" !== 'production' ? invariant(false, 'ReactMount: Unexpected modification of `%s`', ATTR_NAME) : invariant(false) : undefined; + + var container = ReactMount.findReactContainerForID(id); + if (container && containsNode(container, node)) { + return true; + } + } + + return false; +} + +/** + * Causes the cache to forget about one React-specific ID. + * + * @param {string} id The ID to forget. + */ +function purgeID(id) { + delete nodeCache[id]; +} + +var deepestNodeSoFar = null; +function findDeepestCachedAncestorImpl(ancestorID) { + var ancestor = nodeCache[ancestorID]; + if (ancestor && isValid(ancestor, ancestorID)) { + deepestNodeSoFar = ancestor; + } else { + // This node isn't populated in the cache, so presumably none of its + // descendants are. Break out of the loop. + return false; + } +} + +/** + * Return the deepest cached node whose ID is a prefix of `targetID`. + */ +function findDeepestCachedAncestor(targetID) { + deepestNodeSoFar = null; + ReactInstanceHandles.traverseAncestors(targetID, findDeepestCachedAncestorImpl); + + var foundNode = deepestNodeSoFar; + deepestNodeSoFar = null; + return foundNode; +} + +/** + * Mounts this component and inserts it into the DOM. + * + * @param {ReactComponent} componentInstance The instance to mount. + * @param {string} rootID DOM ID of the root node. + * @param {DOMElement} container DOM element to mount into. + * @param {ReactReconcileTransaction} transaction + * @param {boolean} shouldReuseMarkup If true, do not insert markup + */ +function mountComponentIntoNode(componentInstance, rootID, container, transaction, shouldReuseMarkup, context) { + if (ReactDOMFeatureFlags.useCreateElement) { + context = assign({}, context); + if (container.nodeType === DOC_NODE_TYPE) { + context[ownerDocumentContextKey] = container; + } else { + context[ownerDocumentContextKey] = container.ownerDocument; + } + } + if ("development" !== 'production') { + if (context === emptyObject) { + context = {}; + } + var tag = container.nodeName.toLowerCase(); + context[validateDOMNesting.ancestorInfoContextKey] = validateDOMNesting.updatedAncestorInfo(null, tag, null); + } + var markup = ReactReconciler.mountComponent(componentInstance, rootID, transaction, context); + componentInstance._renderedComponent._topLevelWrapper = componentInstance; + ReactMount._mountImageIntoNode(markup, container, shouldReuseMarkup, transaction); +} + +/** + * Batched mount. + * + * @param {ReactComponent} componentInstance The instance to mount. + * @param {string} rootID DOM ID of the root node. + * @param {DOMElement} container DOM element to mount into. + * @param {boolean} shouldReuseMarkup If true, do not insert markup + */ +function batchedMountComponentIntoNode(componentInstance, rootID, container, shouldReuseMarkup, context) { + var transaction = ReactUpdates.ReactReconcileTransaction.getPooled( + /* forceHTML */shouldReuseMarkup); + transaction.perform(mountComponentIntoNode, null, componentInstance, rootID, container, transaction, shouldReuseMarkup, context); + ReactUpdates.ReactReconcileTransaction.release(transaction); +} + +/** + * Unmounts a component and removes it from the DOM. + * + * @param {ReactComponent} instance React component instance. + * @param {DOMElement} container DOM element to unmount from. + * @final + * @internal + * @see {ReactMount.unmountComponentAtNode} + */ +function unmountComponentFromNode(instance, container) { + ReactReconciler.unmountComponent(instance); + + if (container.nodeType === DOC_NODE_TYPE) { + container = container.documentElement; + } + + // http://jsperf.com/emptying-a-node + while (container.lastChild) { + container.removeChild(container.lastChild); + } +} + +/** + * True if the supplied DOM node has a direct React-rendered child that is + * not a React root element. Useful for warning in `render`, + * `unmountComponentAtNode`, etc. + * + * @param {?DOMElement} node The candidate DOM node. + * @return {boolean} True if the DOM element contains a direct child that was + * rendered by React but is not a root element. + * @internal + */ +function hasNonRootReactChild(node) { + var reactRootID = getReactRootID(node); + return reactRootID ? reactRootID !== ReactInstanceHandles.getReactRootIDFromNodeID(reactRootID) : false; +} + +/** + * Returns the first (deepest) ancestor of a node which is rendered by this copy + * of React. + */ +function findFirstReactDOMImpl(node) { + // This node might be from another React instance, so we make sure not to + // examine the node cache here + for (; node && node.parentNode !== node; node = node.parentNode) { + if (node.nodeType !== 1) { + // Not a DOMElement, therefore not a React component + continue; + } + var nodeID = internalGetID(node); + if (!nodeID) { + continue; + } + var reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(nodeID); + + // If containersByReactRootID contains the container we find by crawling up + // the tree, we know that this instance of React rendered the node. + // nb. isValid's strategy (with containsNode) does not work because render + // trees may be nested and we don't want a false positive in that case. + var current = node; + var lastID; + do { + lastID = internalGetID(current); + current = current.parentNode; + if (current == null) { + // The passed-in node has been detached from the container it was + // originally rendered into. + return null; + } + } while (lastID !== reactRootID); + + if (current === containersByReactRootID[reactRootID]) { + return node; + } + } + return null; +} + +/** + * Temporary (?) hack so that we can store all top-level pending updates on + * composites instead of having to worry about different types of components + * here. + */ +var TopLevelWrapper = function () {}; +TopLevelWrapper.prototype.isReactComponent = {}; +if ("development" !== 'production') { + TopLevelWrapper.displayName = 'TopLevelWrapper'; +} +TopLevelWrapper.prototype.render = function () { + // this.props is actually a ReactElement + return this.props; +}; + +/** + * Mounting is the process of initializing a React component by creating its + * representative DOM elements and inserting them into a supplied `container`. + * Any prior content inside `container` is destroyed in the process. + * + * ReactMount.render( + * component, + * document.getElementById('container') + * ); + * + * <div id="container"> <-- Supplied `container`. + * <div data-reactid=".3"> <-- Rendered reactRoot of React + * // ... component. + * </div> + * </div> + * + * Inside of `container`, the first element rendered is the "reactRoot". + */ +var ReactMount = { + + TopLevelWrapper: TopLevelWrapper, + + /** Exposed for debugging purposes **/ + _instancesByReactRootID: instancesByReactRootID, + + /** + * This is a hook provided to support rendering React components while + * ensuring that the apparent scroll position of its `container` does not + * change. + * + * @param {DOMElement} container The `container` being rendered into. + * @param {function} renderCallback This must be called once to do the render. + */ + scrollMonitor: function (container, renderCallback) { + renderCallback(); + }, + + /** + * Take a component that's already mounted into the DOM and replace its props + * @param {ReactComponent} prevComponent component instance already in the DOM + * @param {ReactElement} nextElement component instance to render + * @param {DOMElement} container container to render into + * @param {?function} callback function triggered on completion + */ + _updateRootComponent: function (prevComponent, nextElement, container, callback) { + ReactMount.scrollMonitor(container, function () { + ReactUpdateQueue.enqueueElementInternal(prevComponent, nextElement); + if (callback) { + ReactUpdateQueue.enqueueCallbackInternal(prevComponent, callback); + } + }); + + if ("development" !== 'production') { + // Record the root element in case it later gets transplanted. + rootElementsByReactRootID[getReactRootID(container)] = getReactRootElementInContainer(container); + } + + return prevComponent; + }, + + /** + * Register a component into the instance map and starts scroll value + * monitoring + * @param {ReactComponent} nextComponent component instance to render + * @param {DOMElement} container container to render into + * @return {string} reactRoot ID prefix + */ + _registerComponent: function (nextComponent, container) { + !(container && (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE || container.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)) ? "development" !== 'production' ? invariant(false, '_registerComponent(...): Target container is not a DOM element.') : invariant(false) : undefined; + + ReactBrowserEventEmitter.ensureScrollValueMonitoring(); + + var reactRootID = ReactMount.registerContainer(container); + instancesByReactRootID[reactRootID] = nextComponent; + return reactRootID; + }, + + /** + * Render a new component into the DOM. + * @param {ReactElement} nextElement element to render + * @param {DOMElement} container container to render into + * @param {boolean} shouldReuseMarkup if we should skip the markup insertion + * @return {ReactComponent} nextComponent + */ + _renderNewRootComponent: function (nextElement, container, shouldReuseMarkup, context) { + // Various parts of our code (such as ReactCompositeComponent's + // _renderValidatedComponent) assume that calls to render aren't nested; + // verify that that's the case. + "development" !== 'production' ? warning(ReactCurrentOwner.current == null, '_renderNewRootComponent(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from ' + 'render is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : undefined; + + var componentInstance = instantiateReactComponent(nextElement, null); + var reactRootID = ReactMount._registerComponent(componentInstance, container); + + // The initial render is synchronous but any updates that happen during + // rendering, in componentWillMount or componentDidMount, will be batched + // according to the current batching strategy. + + ReactUpdates.batchedUpdates(batchedMountComponentIntoNode, componentInstance, reactRootID, container, shouldReuseMarkup, context); + + if ("development" !== 'production') { + // Record the root element in case it later gets transplanted. + rootElementsByReactRootID[reactRootID] = getReactRootElementInContainer(container); + } + + return componentInstance; + }, + + /** + * Renders a React component into the DOM in the supplied `container`. + * + * If the React component was previously rendered into `container`, this will + * perform an update on it and only mutate the DOM as necessary to reflect the + * latest React component. + * + * @param {ReactComponent} parentComponent The conceptual parent of this render tree. + * @param {ReactElement} nextElement Component element to render. + * @param {DOMElement} container DOM element to render into. + * @param {?function} callback function triggered on completion + * @return {ReactComponent} Component instance rendered in `container`. + */ + renderSubtreeIntoContainer: function (parentComponent, nextElement, container, callback) { + !(parentComponent != null && parentComponent._reactInternalInstance != null) ? "development" !== 'production' ? invariant(false, 'parentComponent must be a valid React Component') : invariant(false) : undefined; + return ReactMount._renderSubtreeIntoContainer(parentComponent, nextElement, container, callback); + }, + + _renderSubtreeIntoContainer: function (parentComponent, nextElement, container, callback) { + !ReactElement.isValidElement(nextElement) ? "development" !== 'production' ? invariant(false, 'ReactDOM.render(): Invalid component element.%s', typeof nextElement === 'string' ? ' Instead of passing an element string, make sure to instantiate ' + 'it by passing it to React.createElement.' : typeof nextElement === 'function' ? ' Instead of passing a component class, make sure to instantiate ' + 'it by passing it to React.createElement.' : + // Check if it quacks like an element + nextElement != null && nextElement.props !== undefined ? ' This may be caused by unintentionally loading two independent ' + 'copies of React.' : '') : invariant(false) : undefined; + + "development" !== 'production' ? warning(!container || !container.tagName || container.tagName.toUpperCase() !== 'BODY', 'render(): Rendering components directly into document.body is ' + 'discouraged, since its children are often manipulated by third-party ' + 'scripts and browser extensions. This may lead to subtle ' + 'reconciliation issues. Try rendering into a container element created ' + 'for your app.') : undefined; + + var nextWrappedElement = new ReactElement(TopLevelWrapper, null, null, null, null, null, nextElement); + + var prevComponent = instancesByReactRootID[getReactRootID(container)]; + + if (prevComponent) { + var prevWrappedElement = prevComponent._currentElement; + var prevElement = prevWrappedElement.props; + if (shouldUpdateReactComponent(prevElement, nextElement)) { + var publicInst = prevComponent._renderedComponent.getPublicInstance(); + var updatedCallback = callback && function () { + callback.call(publicInst); + }; + ReactMount._updateRootComponent(prevComponent, nextWrappedElement, container, updatedCallback); + return publicInst; + } else { + ReactMount.unmountComponentAtNode(container); + } + } + + var reactRootElement = getReactRootElementInContainer(container); + var containerHasReactMarkup = reactRootElement && !!internalGetID(reactRootElement); + var containerHasNonRootReactChild = hasNonRootReactChild(container); + + if ("development" !== 'production') { + "development" !== 'production' ? warning(!containerHasNonRootReactChild, 'render(...): Replacing React-rendered children with a new root ' + 'component. If you intended to update the children of this node, ' + 'you should instead have the existing children update their state ' + 'and render the new components instead of calling ReactDOM.render.') : undefined; + + if (!containerHasReactMarkup || reactRootElement.nextSibling) { + var rootElementSibling = reactRootElement; + while (rootElementSibling) { + if (internalGetID(rootElementSibling)) { + "development" !== 'production' ? warning(false, 'render(): Target node has markup rendered by React, but there ' + 'are unrelated nodes as well. This is most commonly caused by ' + 'white-space inserted around server-rendered markup.') : undefined; + break; + } + rootElementSibling = rootElementSibling.nextSibling; + } + } + } + + var shouldReuseMarkup = containerHasReactMarkup && !prevComponent && !containerHasNonRootReactChild; + var component = ReactMount._renderNewRootComponent(nextWrappedElement, container, shouldReuseMarkup, parentComponent != null ? parentComponent._reactInternalInstance._processChildContext(parentComponent._reactInternalInstance._context) : emptyObject)._renderedComponent.getPublicInstance(); + if (callback) { + callback.call(component); + } + return component; + }, + + /** + * Renders a React component into the DOM in the supplied `container`. + * + * If the React component was previously rendered into `container`, this will + * perform an update on it and only mutate the DOM as necessary to reflect the + * latest React component. + * + * @param {ReactElement} nextElement Component element to render. + * @param {DOMElement} container DOM element to render into. + * @param {?function} callback function triggered on completion + * @return {ReactComponent} Component instance rendered in `container`. + */ + render: function (nextElement, container, callback) { + return ReactMount._renderSubtreeIntoContainer(null, nextElement, container, callback); + }, + + /** + * Registers a container node into which React components will be rendered. + * This also creates the "reactRoot" ID that will be assigned to the element + * rendered within. + * + * @param {DOMElement} container DOM element to register as a container. + * @return {string} The "reactRoot" ID of elements rendered within. + */ + registerContainer: function (container) { + var reactRootID = getReactRootID(container); + if (reactRootID) { + // If one exists, make sure it is a valid "reactRoot" ID. + reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(reactRootID); + } + if (!reactRootID) { + // No valid "reactRoot" ID found, create one. + reactRootID = ReactInstanceHandles.createReactRootID(); + } + containersByReactRootID[reactRootID] = container; + return reactRootID; + }, + + /** + * Unmounts and destroys the React component rendered in the `container`. + * + * @param {DOMElement} container DOM element containing a React component. + * @return {boolean} True if a component was found in and unmounted from + * `container` + */ + unmountComponentAtNode: function (container) { + // Various parts of our code (such as ReactCompositeComponent's + // _renderValidatedComponent) assume that calls to render aren't nested; + // verify that that's the case. (Strictly speaking, unmounting won't cause a + // render but we still don't expect to be in a render call here.) + "development" !== 'production' ? warning(ReactCurrentOwner.current == null, 'unmountComponentAtNode(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from render ' + 'is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : undefined; + + !(container && (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE || container.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)) ? "development" !== 'production' ? invariant(false, 'unmountComponentAtNode(...): Target container is not a DOM element.') : invariant(false) : undefined; + + var reactRootID = getReactRootID(container); + var component = instancesByReactRootID[reactRootID]; + if (!component) { + // Check if the node being unmounted was rendered by React, but isn't a + // root node. + var containerHasNonRootReactChild = hasNonRootReactChild(container); + + // Check if the container itself is a React root node. + var containerID = internalGetID(container); + var isContainerReactRoot = containerID && containerID === ReactInstanceHandles.getReactRootIDFromNodeID(containerID); + + if ("development" !== 'production') { + "development" !== 'production' ? warning(!containerHasNonRootReactChild, 'unmountComponentAtNode(): The node you\'re attempting to unmount ' + 'was rendered by React and is not a top-level container. %s', isContainerReactRoot ? 'You may have accidentally passed in a React root node instead ' + 'of its container.' : 'Instead, have the parent component update its state and ' + 'rerender in order to remove this component.') : undefined; + } + + return false; + } + ReactUpdates.batchedUpdates(unmountComponentFromNode, component, container); + delete instancesByReactRootID[reactRootID]; + delete containersByReactRootID[reactRootID]; + if ("development" !== 'production') { + delete rootElementsByReactRootID[reactRootID]; + } + return true; + }, + + /** + * Finds the container DOM element that contains React component to which the + * supplied DOM `id` belongs. + * + * @param {string} id The ID of an element rendered by a React component. + * @return {?DOMElement} DOM element that contains the `id`. + */ + findReactContainerForID: function (id) { + var reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(id); + var container = containersByReactRootID[reactRootID]; + + if ("development" !== 'production') { + var rootElement = rootElementsByReactRootID[reactRootID]; + if (rootElement && rootElement.parentNode !== container) { + "development" !== 'production' ? warning( + // Call internalGetID here because getID calls isValid which calls + // findReactContainerForID (this function). + internalGetID(rootElement) === reactRootID, 'ReactMount: Root element ID differed from reactRootID.') : undefined; + var containerChild = container.firstChild; + if (containerChild && reactRootID === internalGetID(containerChild)) { + // If the container has a new child with the same ID as the old + // root element, then rootElementsByReactRootID[reactRootID] is + // just stale and needs to be updated. The case that deserves a + // warning is when the container is empty. + rootElementsByReactRootID[reactRootID] = containerChild; + } else { + "development" !== 'production' ? warning(false, 'ReactMount: Root element has been removed from its original ' + 'container. New container: %s', rootElement.parentNode) : undefined; + } + } + } + + return container; + }, + + /** + * Finds an element rendered by React with the supplied ID. + * + * @param {string} id ID of a DOM node in the React component. + * @return {DOMElement} Root DOM node of the React component. + */ + findReactNodeByID: function (id) { + var reactRoot = ReactMount.findReactContainerForID(id); + return ReactMount.findComponentRoot(reactRoot, id); + }, + + /** + * Traverses up the ancestors of the supplied node to find a node that is a + * DOM representation of a React component rendered by this copy of React. + * + * @param {*} node + * @return {?DOMEventTarget} + * @internal + */ + getFirstReactDOM: function (node) { + return findFirstReactDOMImpl(node); + }, + + /** + * Finds a node with the supplied `targetID` inside of the supplied + * `ancestorNode`. Exploits the ID naming scheme to perform the search + * quickly. + * + * @param {DOMEventTarget} ancestorNode Search from this root. + * @pararm {string} targetID ID of the DOM representation of the component. + * @return {DOMEventTarget} DOM node with the supplied `targetID`. + * @internal + */ + findComponentRoot: function (ancestorNode, targetID) { + var firstChildren = findComponentRootReusableArray; + var childIndex = 0; + + var deepestAncestor = findDeepestCachedAncestor(targetID) || ancestorNode; + + if ("development" !== 'production') { + // This will throw on the next line; give an early warning + "development" !== 'production' ? warning(deepestAncestor != null, 'React can\'t find the root component node for data-reactid value ' + '`%s`. If you\'re seeing this message, it probably means that ' + 'you\'ve loaded two copies of React on the page. At this time, only ' + 'a single copy of React can be loaded at a time.', targetID) : undefined; + } + + firstChildren[0] = deepestAncestor.firstChild; + firstChildren.length = 1; + + while (childIndex < firstChildren.length) { + var child = firstChildren[childIndex++]; + var targetChild; + + while (child) { + var childID = ReactMount.getID(child); + if (childID) { + // Even if we find the node we're looking for, we finish looping + // through its siblings to ensure they're cached so that we don't have + // to revisit this node again. Otherwise, we make n^2 calls to getID + // when visiting the many children of a single node in order. + + if (targetID === childID) { + targetChild = child; + } else if (ReactInstanceHandles.isAncestorIDOf(childID, targetID)) { + // If we find a child whose ID is an ancestor of the given ID, + // then we can be sure that we only want to search the subtree + // rooted at this child, so we can throw out the rest of the + // search state. + firstChildren.length = childIndex = 0; + firstChildren.push(child.firstChild); + } + } else { + // If this child had no ID, then there's a chance that it was + // injected automatically by the browser, as when a `<table>` + // element sprouts an extra `<tbody>` child as a side effect of + // `.innerHTML` parsing. Optimistically continue down this + // branch, but not before examining the other siblings. + firstChildren.push(child.firstChild); + } + + child = child.nextSibling; + } + + if (targetChild) { + // Emptying firstChildren/findComponentRootReusableArray is + // not necessary for correctness, but it helps the GC reclaim + // any nodes that were left at the end of the search. + firstChildren.length = 0; + + return targetChild; + } + } + + firstChildren.length = 0; + + !false ? "development" !== 'production' ? invariant(false, 'findComponentRoot(..., %s): Unable to find element. This probably ' + 'means the DOM was unexpectedly mutated (e.g., by the browser), ' + 'usually due to forgetting a <tbody> when using tables, nesting tags ' + 'like <form>, <p>, or <a>, or using non-SVG elements in an <svg> ' + 'parent. ' + 'Try inspecting the child nodes of the element with React ID `%s`.', targetID, ReactMount.getID(ancestorNode)) : invariant(false) : undefined; + }, + + _mountImageIntoNode: function (markup, container, shouldReuseMarkup, transaction) { + !(container && (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE || container.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)) ? "development" !== 'production' ? invariant(false, 'mountComponentIntoNode(...): Target container is not valid.') : invariant(false) : undefined; + + if (shouldReuseMarkup) { + var rootElement = getReactRootElementInContainer(container); + if (ReactMarkupChecksum.canReuseMarkup(markup, rootElement)) { + return; + } else { + var checksum = rootElement.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME); + rootElement.removeAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME); + + var rootMarkup = rootElement.outerHTML; + rootElement.setAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME, checksum); + + var normalizedMarkup = markup; + if ("development" !== 'production') { + // because rootMarkup is retrieved from the DOM, various normalizations + // will have occurred which will not be present in `markup`. Here, + // insert markup into a <div> or <iframe> depending on the container + // type to perform the same normalizations before comparing. + var normalizer; + if (container.nodeType === ELEMENT_NODE_TYPE) { + normalizer = document.createElementNS('http://www.w3.org/1999/xhtml', 'div'); + normalizer.innerHTML = markup; + normalizedMarkup = normalizer.innerHTML; + } else { + normalizer = document.createElementNS('http://www.w3.org/1999/xhtml', 'iframe'); + document.body.appendChild(normalizer); + normalizer.contentDocument.write(markup); + normalizedMarkup = normalizer.contentDocument.documentElement.outerHTML; + document.body.removeChild(normalizer); + } + } + + var diffIndex = firstDifferenceIndex(normalizedMarkup, rootMarkup); + var difference = ' (client) ' + normalizedMarkup.substring(diffIndex - 20, diffIndex + 20) + '\n (server) ' + rootMarkup.substring(diffIndex - 20, diffIndex + 20); + + !(container.nodeType !== DOC_NODE_TYPE) ? "development" !== 'production' ? invariant(false, 'You\'re trying to render a component to the document using ' + 'server rendering but the checksum was invalid. This usually ' + 'means you rendered a different component type or props on ' + 'the client from the one on the server, or your render() ' + 'methods are impure. React cannot handle this case due to ' + 'cross-browser quirks by rendering at the document root. You ' + 'should look for environment dependent code in your components ' + 'and ensure the props are the same client and server side:\n%s', difference) : invariant(false) : undefined; + + if ("development" !== 'production') { + "development" !== 'production' ? warning(false, 'React attempted to reuse markup in a container but the ' + 'checksum was invalid. This generally means that you are ' + 'using server rendering and the markup generated on the ' + 'server was not what the client was expecting. React injected ' + 'new markup to compensate which works but you have lost many ' + 'of the benefits of server rendering. Instead, figure out ' + 'why the markup being generated is different on the client ' + 'or server:\n%s', difference) : undefined; + } + } + } + + !(container.nodeType !== DOC_NODE_TYPE) ? "development" !== 'production' ? invariant(false, 'You\'re trying to render a component to the document but ' + 'you didn\'t use server rendering. We can\'t do this ' + 'without using server rendering due to cross-browser quirks. ' + 'See ReactDOMServer.renderToString() for server rendering.') : invariant(false) : undefined; + + if (transaction.useCreateElement) { + while (container.lastChild) { + container.removeChild(container.lastChild); + } + container.appendChild(markup); + } else { + setInnerHTML(container, markup); + } + }, + + ownerDocumentContextKey: ownerDocumentContextKey, + + /** + * React ID utilities. + */ + + getReactRootID: getReactRootID, + + getID: getID, + + setID: setID, + + getNode: getNode, + + getNodeFromInstance: getNodeFromInstance, + + isValid: isValid, + + purgeID: purgeID +}; + +ReactPerf.measureMethods(ReactMount, 'ReactMount', { + _renderNewRootComponent: '_renderNewRootComponent', + _mountImageIntoNode: '_mountImageIntoNode' +}); + +module.exports = ReactMount; +},{"10":10,"132":132,"138":138,"141":141,"144":144,"150":150,"154":154,"161":161,"173":173,"24":24,"28":28,"39":39,"44":44,"57":57,"60":60,"67":67,"68":68,"71":71,"78":78,"84":84,"95":95,"96":96}],73:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactMultiChild + * @typechecks static-only + */ + +'use strict'; + +var ReactComponentEnvironment = _dereq_(36); +var ReactMultiChildUpdateTypes = _dereq_(74); + +var ReactCurrentOwner = _dereq_(39); +var ReactReconciler = _dereq_(84); +var ReactChildReconciler = _dereq_(31); + +var flattenChildren = _dereq_(123); + +/** + * Updating children of a component may trigger recursive updates. The depth is + * used to batch recursive updates to render markup more efficiently. + * + * @type {number} + * @private + */ +var updateDepth = 0; + +/** + * Queue of update configuration objects. + * + * Each object has a `type` property that is in `ReactMultiChildUpdateTypes`. + * + * @type {array<object>} + * @private + */ +var updateQueue = []; + +/** + * Queue of markup to be rendered. + * + * @type {array<string>} + * @private + */ +var markupQueue = []; + +/** + * Enqueues markup to be rendered and inserted at a supplied index. + * + * @param {string} parentID ID of the parent component. + * @param {string} markup Markup that renders into an element. + * @param {number} toIndex Destination index. + * @private + */ +function enqueueInsertMarkup(parentID, markup, toIndex) { + // NOTE: Null values reduce hidden classes. + updateQueue.push({ + parentID: parentID, + parentNode: null, + type: ReactMultiChildUpdateTypes.INSERT_MARKUP, + markupIndex: markupQueue.push(markup) - 1, + content: null, + fromIndex: null, + toIndex: toIndex + }); +} + +/** + * Enqueues moving an existing element to another index. + * + * @param {string} parentID ID of the parent component. + * @param {number} fromIndex Source index of the existing element. + * @param {number} toIndex Destination index of the element. + * @private + */ +function enqueueMove(parentID, fromIndex, toIndex) { + // NOTE: Null values reduce hidden classes. + updateQueue.push({ + parentID: parentID, + parentNode: null, + type: ReactMultiChildUpdateTypes.MOVE_EXISTING, + markupIndex: null, + content: null, + fromIndex: fromIndex, + toIndex: toIndex + }); +} + +/** + * Enqueues removing an element at an index. + * + * @param {string} parentID ID of the parent component. + * @param {number} fromIndex Index of the element to remove. + * @private + */ +function enqueueRemove(parentID, fromIndex) { + // NOTE: Null values reduce hidden classes. + updateQueue.push({ + parentID: parentID, + parentNode: null, + type: ReactMultiChildUpdateTypes.REMOVE_NODE, + markupIndex: null, + content: null, + fromIndex: fromIndex, + toIndex: null + }); +} + +/** + * Enqueues setting the markup of a node. + * + * @param {string} parentID ID of the parent component. + * @param {string} markup Markup that renders into an element. + * @private + */ +function enqueueSetMarkup(parentID, markup) { + // NOTE: Null values reduce hidden classes. + updateQueue.push({ + parentID: parentID, + parentNode: null, + type: ReactMultiChildUpdateTypes.SET_MARKUP, + markupIndex: null, + content: markup, + fromIndex: null, + toIndex: null + }); +} + +/** + * Enqueues setting the text content. + * + * @param {string} parentID ID of the parent component. + * @param {string} textContent Text content to set. + * @private + */ +function enqueueTextContent(parentID, textContent) { + // NOTE: Null values reduce hidden classes. + updateQueue.push({ + parentID: parentID, + parentNode: null, + type: ReactMultiChildUpdateTypes.TEXT_CONTENT, + markupIndex: null, + content: textContent, + fromIndex: null, + toIndex: null + }); +} + +/** + * Processes any enqueued updates. + * + * @private + */ +function processQueue() { + if (updateQueue.length) { + ReactComponentEnvironment.processChildrenUpdates(updateQueue, markupQueue); + clearQueue(); + } +} + +/** + * Clears any enqueued updates. + * + * @private + */ +function clearQueue() { + updateQueue.length = 0; + markupQueue.length = 0; +} + +/** + * ReactMultiChild are capable of reconciling multiple children. + * + * @class ReactMultiChild + * @internal + */ +var ReactMultiChild = { + + /** + * Provides common functionality for components that must reconcile multiple + * children. This is used by `ReactDOMComponent` to mount, update, and + * unmount child components. + * + * @lends {ReactMultiChild.prototype} + */ + Mixin: { + + _reconcilerInstantiateChildren: function (nestedChildren, transaction, context) { + if ("development" !== 'production') { + if (this._currentElement) { + try { + ReactCurrentOwner.current = this._currentElement._owner; + return ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context); + } finally { + ReactCurrentOwner.current = null; + } + } + } + return ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context); + }, + + _reconcilerUpdateChildren: function (prevChildren, nextNestedChildrenElements, transaction, context) { + var nextChildren; + if ("development" !== 'production') { + if (this._currentElement) { + try { + ReactCurrentOwner.current = this._currentElement._owner; + nextChildren = flattenChildren(nextNestedChildrenElements); + } finally { + ReactCurrentOwner.current = null; + } + return ReactChildReconciler.updateChildren(prevChildren, nextChildren, transaction, context); + } + } + nextChildren = flattenChildren(nextNestedChildrenElements); + return ReactChildReconciler.updateChildren(prevChildren, nextChildren, transaction, context); + }, + + /** + * Generates a "mount image" for each of the supplied children. In the case + * of `ReactDOMComponent`, a mount image is a string of markup. + * + * @param {?object} nestedChildren Nested child maps. + * @return {array} An array of mounted representations. + * @internal + */ + mountChildren: function (nestedChildren, transaction, context) { + var children = this._reconcilerInstantiateChildren(nestedChildren, transaction, context); + this._renderedChildren = children; + var mountImages = []; + var index = 0; + for (var name in children) { + if (children.hasOwnProperty(name)) { + var child = children[name]; + // Inlined for performance, see `ReactInstanceHandles.createReactID`. + var rootID = this._rootNodeID + name; + var mountImage = ReactReconciler.mountComponent(child, rootID, transaction, context); + child._mountIndex = index++; + mountImages.push(mountImage); + } + } + return mountImages; + }, + + /** + * Replaces any rendered children with a text content string. + * + * @param {string} nextContent String of content. + * @internal + */ + updateTextContent: function (nextContent) { + updateDepth++; + var errorThrown = true; + try { + var prevChildren = this._renderedChildren; + // Remove any rendered children. + ReactChildReconciler.unmountChildren(prevChildren); + // TODO: The setTextContent operation should be enough + for (var name in prevChildren) { + if (prevChildren.hasOwnProperty(name)) { + this._unmountChild(prevChildren[name]); + } + } + // Set new text content. + this.setTextContent(nextContent); + errorThrown = false; + } finally { + updateDepth--; + if (!updateDepth) { + if (errorThrown) { + clearQueue(); + } else { + processQueue(); + } + } + } + }, + + /** + * Replaces any rendered children with a markup string. + * + * @param {string} nextMarkup String of markup. + * @internal + */ + updateMarkup: function (nextMarkup) { + updateDepth++; + var errorThrown = true; + try { + var prevChildren = this._renderedChildren; + // Remove any rendered children. + ReactChildReconciler.unmountChildren(prevChildren); + for (var name in prevChildren) { + if (prevChildren.hasOwnProperty(name)) { + this._unmountChildByName(prevChildren[name], name); + } + } + this.setMarkup(nextMarkup); + errorThrown = false; + } finally { + updateDepth--; + if (!updateDepth) { + if (errorThrown) { + clearQueue(); + } else { + processQueue(); + } + } + } + }, + + /** + * Updates the rendered children with new children. + * + * @param {?object} nextNestedChildrenElements Nested child element maps. + * @param {ReactReconcileTransaction} transaction + * @internal + */ + updateChildren: function (nextNestedChildrenElements, transaction, context) { + updateDepth++; + var errorThrown = true; + try { + this._updateChildren(nextNestedChildrenElements, transaction, context); + errorThrown = false; + } finally { + updateDepth--; + if (!updateDepth) { + if (errorThrown) { + clearQueue(); + } else { + processQueue(); + } + } + } + }, + + /** + * Improve performance by isolating this hot code path from the try/catch + * block in `updateChildren`. + * + * @param {?object} nextNestedChildrenElements Nested child element maps. + * @param {ReactReconcileTransaction} transaction + * @final + * @protected + */ + _updateChildren: function (nextNestedChildrenElements, transaction, context) { + var prevChildren = this._renderedChildren; + var nextChildren = this._reconcilerUpdateChildren(prevChildren, nextNestedChildrenElements, transaction, context); + this._renderedChildren = nextChildren; + if (!nextChildren && !prevChildren) { + return; + } + var name; + // `nextIndex` will increment for each child in `nextChildren`, but + // `lastIndex` will be the last index visited in `prevChildren`. + var lastIndex = 0; + var nextIndex = 0; + for (name in nextChildren) { + if (!nextChildren.hasOwnProperty(name)) { + continue; + } + var prevChild = prevChildren && prevChildren[name]; + var nextChild = nextChildren[name]; + if (prevChild === nextChild) { + this.moveChild(prevChild, nextIndex, lastIndex); + lastIndex = Math.max(prevChild._mountIndex, lastIndex); + prevChild._mountIndex = nextIndex; + } else { + if (prevChild) { + // Update `lastIndex` before `_mountIndex` gets unset by unmounting. + lastIndex = Math.max(prevChild._mountIndex, lastIndex); + this._unmountChild(prevChild); + } + // The child must be instantiated before it's mounted. + this._mountChildByNameAtIndex(nextChild, name, nextIndex, transaction, context); + } + nextIndex++; + } + // Remove children that are no longer present. + for (name in prevChildren) { + if (prevChildren.hasOwnProperty(name) && !(nextChildren && nextChildren.hasOwnProperty(name))) { + this._unmountChild(prevChildren[name]); + } + } + }, + + /** + * Unmounts all rendered children. This should be used to clean up children + * when this component is unmounted. + * + * @internal + */ + unmountChildren: function () { + var renderedChildren = this._renderedChildren; + ReactChildReconciler.unmountChildren(renderedChildren); + this._renderedChildren = null; + }, + + /** + * Moves a child component to the supplied index. + * + * @param {ReactComponent} child Component to move. + * @param {number} toIndex Destination index of the element. + * @param {number} lastIndex Last index visited of the siblings of `child`. + * @protected + */ + moveChild: function (child, toIndex, lastIndex) { + // If the index of `child` is less than `lastIndex`, then it needs to + // be moved. Otherwise, we do not need to move it because a child will be + // inserted or moved before `child`. + if (child._mountIndex < lastIndex) { + enqueueMove(this._rootNodeID, child._mountIndex, toIndex); + } + }, + + /** + * Creates a child component. + * + * @param {ReactComponent} child Component to create. + * @param {string} mountImage Markup to insert. + * @protected + */ + createChild: function (child, mountImage) { + enqueueInsertMarkup(this._rootNodeID, mountImage, child._mountIndex); + }, + + /** + * Removes a child component. + * + * @param {ReactComponent} child Child to remove. + * @protected + */ + removeChild: function (child) { + enqueueRemove(this._rootNodeID, child._mountIndex); + }, + + /** + * Sets this text content string. + * + * @param {string} textContent Text content to set. + * @protected + */ + setTextContent: function (textContent) { + enqueueTextContent(this._rootNodeID, textContent); + }, + + /** + * Sets this markup string. + * + * @param {string} markup Markup to set. + * @protected + */ + setMarkup: function (markup) { + enqueueSetMarkup(this._rootNodeID, markup); + }, + + /** + * Mounts a child with the supplied name. + * + * NOTE: This is part of `updateChildren` and is here for readability. + * + * @param {ReactComponent} child Component to mount. + * @param {string} name Name of the child. + * @param {number} index Index at which to insert the child. + * @param {ReactReconcileTransaction} transaction + * @private + */ + _mountChildByNameAtIndex: function (child, name, index, transaction, context) { + // Inlined for performance, see `ReactInstanceHandles.createReactID`. + var rootID = this._rootNodeID + name; + var mountImage = ReactReconciler.mountComponent(child, rootID, transaction, context); + child._mountIndex = index; + this.createChild(child, mountImage); + }, + + /** + * Unmounts a rendered child. + * + * NOTE: This is part of `updateChildren` and is here for readability. + * + * @param {ReactComponent} child Component to unmount. + * @private + */ + _unmountChild: function (child) { + this.removeChild(child); + child._mountIndex = null; + } + + } + +}; + +module.exports = ReactMultiChild; +},{"123":123,"31":31,"36":36,"39":39,"74":74,"84":84}],74:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactMultiChildUpdateTypes + */ + +'use strict'; + +var keyMirror = _dereq_(165); + +/** + * When a component's children are updated, a series of update configuration + * objects are created in order to batch and serialize the required changes. + * + * Enumerates all the possible types of update configurations. + * + * @internal + */ +var ReactMultiChildUpdateTypes = keyMirror({ + INSERT_MARKUP: null, + MOVE_EXISTING: null, + REMOVE_NODE: null, + SET_MARKUP: null, + TEXT_CONTENT: null +}); + +module.exports = ReactMultiChildUpdateTypes; +},{"165":165}],75:[function(_dereq_,module,exports){ +/** + * Copyright 2014-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactNativeComponent + */ + +'use strict'; + +var assign = _dereq_(24); +var invariant = _dereq_(161); + +var autoGenerateWrapperClass = null; +var genericComponentClass = null; +// This registry keeps track of wrapper classes around native tags. +var tagToComponentClass = {}; +var textComponentClass = null; + +var ReactNativeComponentInjection = { + // This accepts a class that receives the tag string. This is a catch all + // that can render any kind of tag. + injectGenericComponentClass: function (componentClass) { + genericComponentClass = componentClass; + }, + // This accepts a text component class that takes the text string to be + // rendered as props. + injectTextComponentClass: function (componentClass) { + textComponentClass = componentClass; + }, + // This accepts a keyed object with classes as values. Each key represents a + // tag. That particular tag will use this class instead of the generic one. + injectComponentClasses: function (componentClasses) { + assign(tagToComponentClass, componentClasses); + } +}; + +/** + * Get a composite component wrapper class for a specific tag. + * + * @param {ReactElement} element The tag for which to get the class. + * @return {function} The React class constructor function. + */ +function getComponentClassForElement(element) { + if (typeof element.type === 'function') { + return element.type; + } + var tag = element.type; + var componentClass = tagToComponentClass[tag]; + if (componentClass == null) { + tagToComponentClass[tag] = componentClass = autoGenerateWrapperClass(tag); + } + return componentClass; +} + +/** + * Get a native internal component class for a specific tag. + * + * @param {ReactElement} element The element to create. + * @return {function} The internal class constructor function. + */ +function createInternalComponent(element) { + !genericComponentClass ? "development" !== 'production' ? invariant(false, 'There is no registered component for the tag %s', element.type) : invariant(false) : undefined; + return new genericComponentClass(element.type, element.props); +} + +/** + * @param {ReactText} text + * @return {ReactComponent} + */ +function createInstanceForText(text) { + return new textComponentClass(text); +} + +/** + * @param {ReactComponent} component + * @return {boolean} + */ +function isTextComponent(component) { + return component instanceof textComponentClass; +} + +var ReactNativeComponent = { + getComponentClassForElement: getComponentClassForElement, + createInternalComponent: createInternalComponent, + createInstanceForText: createInstanceForText, + isTextComponent: isTextComponent, + injection: ReactNativeComponentInjection +}; + +module.exports = ReactNativeComponent; +},{"161":161,"24":24}],76:[function(_dereq_,module,exports){ +/** + * Copyright 2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactNoopUpdateQueue + */ + +'use strict'; + +var warning = _dereq_(173); + +function warnTDZ(publicInstance, callerName) { + if ("development" !== 'production') { + "development" !== 'production' ? warning(false, '%s(...): Can only update a mounted or mounting component. ' + 'This usually means you called %s() on an unmounted component. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, publicInstance.constructor && publicInstance.constructor.displayName || '') : undefined; + } +} + +/** + * This is the abstract API for an update queue. + */ +var ReactNoopUpdateQueue = { + + /** + * Checks whether or not this composite component is mounted. + * @param {ReactClass} publicInstance The instance we want to test. + * @return {boolean} True if mounted, false otherwise. + * @protected + * @final + */ + isMounted: function (publicInstance) { + return false; + }, + + /** + * Enqueue a callback that will be executed after all the pending updates + * have processed. + * + * @param {ReactClass} publicInstance The instance to use as `this` context. + * @param {?function} callback Called after state is updated. + * @internal + */ + enqueueCallback: function (publicInstance, callback) {}, + + /** + * Forces an update. This should only be invoked when it is known with + * certainty that we are **not** in a DOM transaction. + * + * You may want to call this when you know that some deeper aspect of the + * component's state has changed but `setState` was not called. + * + * This will not invoke `shouldComponentUpdate`, but it will invoke + * `componentWillUpdate` and `componentDidUpdate`. + * + * @param {ReactClass} publicInstance The instance that should rerender. + * @internal + */ + enqueueForceUpdate: function (publicInstance) { + warnTDZ(publicInstance, 'forceUpdate'); + }, + + /** + * Replaces all of the state. Always use this or `setState` to mutate state. + * You should treat `this.state` as immutable. + * + * There is no guarantee that `this.state` will be immediately updated, so + * accessing `this.state` after calling this method may return the old value. + * + * @param {ReactClass} publicInstance The instance that should rerender. + * @param {object} completeState Next state. + * @internal + */ + enqueueReplaceState: function (publicInstance, completeState) { + warnTDZ(publicInstance, 'replaceState'); + }, + + /** + * Sets a subset of the state. This only exists because _pendingState is + * internal. This provides a merging strategy that is not available to deep + * properties which is confusing. TODO: Expose pendingState or don't use it + * during the merge. + * + * @param {ReactClass} publicInstance The instance that should rerender. + * @param {object} partialState Next partial state to be merged with state. + * @internal + */ + enqueueSetState: function (publicInstance, partialState) { + warnTDZ(publicInstance, 'setState'); + }, + + /** + * Sets a subset of the props. + * + * @param {ReactClass} publicInstance The instance that should rerender. + * @param {object} partialProps Subset of the next props. + * @internal + */ + enqueueSetProps: function (publicInstance, partialProps) { + warnTDZ(publicInstance, 'setProps'); + }, + + /** + * Replaces all of the props. + * + * @param {ReactClass} publicInstance The instance that should rerender. + * @param {object} props New props. + * @internal + */ + enqueueReplaceProps: function (publicInstance, props) { + warnTDZ(publicInstance, 'replaceProps'); + } + +}; + +module.exports = ReactNoopUpdateQueue; +},{"173":173}],77:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactOwner + */ + +'use strict'; + +var invariant = _dereq_(161); + +/** + * ReactOwners are capable of storing references to owned components. + * + * All components are capable of //being// referenced by owner components, but + * only ReactOwner components are capable of //referencing// owned components. + * The named reference is known as a "ref". + * + * Refs are available when mounted and updated during reconciliation. + * + * var MyComponent = React.createClass({ + * render: function() { + * return ( + * <div onClick={this.handleClick}> + * <CustomComponent ref="custom" /> + * </div> + * ); + * }, + * handleClick: function() { + * this.refs.custom.handleClick(); + * }, + * componentDidMount: function() { + * this.refs.custom.initialize(); + * } + * }); + * + * Refs should rarely be used. When refs are used, they should only be done to + * control data that is not handled by React's data flow. + * + * @class ReactOwner + */ +var ReactOwner = { + + /** + * @param {?object} object + * @return {boolean} True if `object` is a valid owner. + * @final + */ + isValidOwner: function (object) { + return !!(object && typeof object.attachRef === 'function' && typeof object.detachRef === 'function'); + }, + + /** + * Adds a component by ref to an owner component. + * + * @param {ReactComponent} component Component to reference. + * @param {string} ref Name by which to refer to the component. + * @param {ReactOwner} owner Component on which to record the ref. + * @final + * @internal + */ + addComponentAsRefTo: function (component, ref, owner) { + !ReactOwner.isValidOwner(owner) ? "development" !== 'production' ? invariant(false, 'addComponentAsRefTo(...): Only a ReactOwner can have refs. You might ' + 'be adding a ref to a component that was not created inside a component\'s ' + '`render` method, or you have multiple copies of React loaded ' + '(details: https://fb.me/react-refs-must-have-owner).') : invariant(false) : undefined; + owner.attachRef(ref, component); + }, + + /** + * Removes a component by ref from an owner component. + * + * @param {ReactComponent} component Component to dereference. + * @param {string} ref Name of the ref to remove. + * @param {ReactOwner} owner Component on which the ref is recorded. + * @final + * @internal + */ + removeComponentAsRefFrom: function (component, ref, owner) { + !ReactOwner.isValidOwner(owner) ? "development" !== 'production' ? invariant(false, 'removeComponentAsRefFrom(...): Only a ReactOwner can have refs. You might ' + 'be removing a ref to a component that was not created inside a component\'s ' + '`render` method, or you have multiple copies of React loaded ' + '(details: https://fb.me/react-refs-must-have-owner).') : invariant(false) : undefined; + // Check that `component` is still the current ref because we do not want to + // detach the ref if another component stole it. + if (owner.getPublicInstance().refs[ref] === component.getPublicInstance()) { + owner.detachRef(ref); + } + } + +}; + +module.exports = ReactOwner; +},{"161":161}],78:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactPerf + * @typechecks static-only + */ + +'use strict'; + +/** + * ReactPerf is a general AOP system designed to measure performance. This + * module only has the hooks: see ReactDefaultPerf for the analysis tool. + */ +var ReactPerf = { + /** + * Boolean to enable/disable measurement. Set to false by default to prevent + * accidental logging and perf loss. + */ + enableMeasure: false, + + /** + * Holds onto the measure function in use. By default, don't measure + * anything, but we'll override this if we inject a measure function. + */ + storedMeasure: _noMeasure, + + /** + * @param {object} object + * @param {string} objectName + * @param {object<string>} methodNames + */ + measureMethods: function (object, objectName, methodNames) { + if ("development" !== 'production') { + for (var key in methodNames) { + if (!methodNames.hasOwnProperty(key)) { + continue; + } + object[key] = ReactPerf.measure(objectName, methodNames[key], object[key]); + } + } + }, + + /** + * Use this to wrap methods you want to measure. Zero overhead in production. + * + * @param {string} objName + * @param {string} fnName + * @param {function} func + * @return {function} + */ + measure: function (objName, fnName, func) { + if ("development" !== 'production') { + var measuredFunc = null; + var wrapper = function () { + if (ReactPerf.enableMeasure) { + if (!measuredFunc) { + measuredFunc = ReactPerf.storedMeasure(objName, fnName, func); + } + return measuredFunc.apply(this, arguments); + } + return func.apply(this, arguments); + }; + wrapper.displayName = objName + '_' + fnName; + return wrapper; + } + return func; + }, + + injection: { + /** + * @param {function} measure + */ + injectMeasure: function (measure) { + ReactPerf.storedMeasure = measure; + } + } +}; + +/** + * Simply passes through the measured function, without measuring it. + * + * @param {string} objName + * @param {string} fnName + * @param {function} func + * @return {function} + */ +function _noMeasure(objName, fnName, func) { + return func; +} + +module.exports = ReactPerf; +},{}],79:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactPropTransferer + */ + +'use strict'; + +var assign = _dereq_(24); +var emptyFunction = _dereq_(153); +var joinClasses = _dereq_(164); + +/** + * Creates a transfer strategy that will merge prop values using the supplied + * `mergeStrategy`. If a prop was previously unset, this just sets it. + * + * @param {function} mergeStrategy + * @return {function} + */ +function createTransferStrategy(mergeStrategy) { + return function (props, key, value) { + if (!props.hasOwnProperty(key)) { + props[key] = value; + } else { + props[key] = mergeStrategy(props[key], value); + } + }; +} + +var transferStrategyMerge = createTransferStrategy(function (a, b) { + // `merge` overrides the first object's (`props[key]` above) keys using the + // second object's (`value`) keys. An object's style's existing `propA` would + // get overridden. Flip the order here. + return assign({}, b, a); +}); + +/** + * Transfer strategies dictate how props are transferred by `transferPropsTo`. + * NOTE: if you add any more exceptions to this list you should be sure to + * update `cloneWithProps()` accordingly. + */ +var TransferStrategies = { + /** + * Never transfer `children`. + */ + children: emptyFunction, + /** + * Transfer the `className` prop by merging them. + */ + className: createTransferStrategy(joinClasses), + /** + * Transfer the `style` prop (which is an object) by merging them. + */ + style: transferStrategyMerge +}; + +/** + * Mutates the first argument by transferring the properties from the second + * argument. + * + * @param {object} props + * @param {object} newProps + * @return {object} + */ +function transferInto(props, newProps) { + for (var thisKey in newProps) { + if (!newProps.hasOwnProperty(thisKey)) { + continue; + } + + var transferStrategy = TransferStrategies[thisKey]; + + if (transferStrategy && TransferStrategies.hasOwnProperty(thisKey)) { + transferStrategy(props, thisKey, newProps[thisKey]); + } else if (!props.hasOwnProperty(thisKey)) { + props[thisKey] = newProps[thisKey]; + } + } + return props; +} + +/** + * ReactPropTransferer are capable of transferring props to another component + * using a `transferPropsTo` method. + * + * @class ReactPropTransferer + */ +var ReactPropTransferer = { + + /** + * Merge two props objects using TransferStrategies. + * + * @param {object} oldProps original props (they take precedence) + * @param {object} newProps new props to merge in + * @return {object} a new object containing both sets of props merged. + */ + mergeProps: function (oldProps, newProps) { + return transferInto(assign({}, oldProps), newProps); + } + +}; + +module.exports = ReactPropTransferer; +},{"153":153,"164":164,"24":24}],80:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactPropTypeLocationNames + */ + +'use strict'; + +var ReactPropTypeLocationNames = {}; + +if ("development" !== 'production') { + ReactPropTypeLocationNames = { + prop: 'prop', + context: 'context', + childContext: 'child context' + }; +} + +module.exports = ReactPropTypeLocationNames; +},{}],81:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactPropTypeLocations + */ + +'use strict'; + +var keyMirror = _dereq_(165); + +var ReactPropTypeLocations = keyMirror({ + prop: null, + context: null, + childContext: null +}); + +module.exports = ReactPropTypeLocations; +},{"165":165}],82:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactPropTypes + */ + +'use strict'; + +var ReactElement = _dereq_(57); +var ReactPropTypeLocationNames = _dereq_(80); + +var emptyFunction = _dereq_(153); +var getIteratorFn = _dereq_(129); + +/** + * Collection of methods that allow declaration and validation of props that are + * supplied to React components. Example usage: + * + * var Props = require('ReactPropTypes'); + * var MyArticle = React.createClass({ + * propTypes: { + * // An optional string prop named "description". + * description: Props.string, + * + * // A required enum prop named "category". + * category: Props.oneOf(['News','Photos']).isRequired, + * + * // A prop named "dialog" that requires an instance of Dialog. + * dialog: Props.instanceOf(Dialog).isRequired + * }, + * render: function() { ... } + * }); + * + * A more formal specification of how these methods are used: + * + * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) + * decl := ReactPropTypes.{type}(.isRequired)? + * + * Each and every declaration produces a function with the same signature. This + * allows the creation of custom validation functions. For example: + * + * var MyLink = React.createClass({ + * propTypes: { + * // An optional string or URI prop named "href". + * href: function(props, propName, componentName) { + * var propValue = props[propName]; + * if (propValue != null && typeof propValue !== 'string' && + * !(propValue instanceof URI)) { + * return new Error( + * 'Expected a string or an URI for ' + propName + ' in ' + + * componentName + * ); + * } + * } + * }, + * render: function() {...} + * }); + * + * @internal + */ + +var ANONYMOUS = '<<anonymous>>'; + +var ReactPropTypes = { + array: createPrimitiveTypeChecker('array'), + bool: createPrimitiveTypeChecker('boolean'), + func: createPrimitiveTypeChecker('function'), + number: createPrimitiveTypeChecker('number'), + object: createPrimitiveTypeChecker('object'), + string: createPrimitiveTypeChecker('string'), + + any: createAnyTypeChecker(), + arrayOf: createArrayOfTypeChecker, + element: createElementTypeChecker(), + instanceOf: createInstanceTypeChecker, + node: createNodeChecker(), + objectOf: createObjectOfTypeChecker, + oneOf: createEnumTypeChecker, + oneOfType: createUnionTypeChecker, + shape: createShapeTypeChecker +}; + +function createChainableTypeChecker(validate) { + function checkType(isRequired, props, propName, componentName, location, propFullName) { + componentName = componentName || ANONYMOUS; + propFullName = propFullName || propName; + if (props[propName] == null) { + var locationName = ReactPropTypeLocationNames[location]; + if (isRequired) { + return new Error('Required ' + locationName + ' `' + propFullName + '` was not specified in ' + ('`' + componentName + '`.')); + } + return null; + } else { + return validate(props, propName, componentName, location, propFullName); + } + } + + var chainedCheckType = checkType.bind(null, false); + chainedCheckType.isRequired = checkType.bind(null, true); + + return chainedCheckType; +} + +function createPrimitiveTypeChecker(expectedType) { + function validate(props, propName, componentName, location, propFullName) { + var propValue = props[propName]; + var propType = getPropType(propValue); + if (propType !== expectedType) { + var locationName = ReactPropTypeLocationNames[location]; + // `propValue` being instance of, say, date/regexp, pass the 'object' + // check, but we can offer a more precise error message here rather than + // 'of type `object`'. + var preciseType = getPreciseType(propValue); + + return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.')); + } + return null; + } + return createChainableTypeChecker(validate); +} + +function createAnyTypeChecker() { + return createChainableTypeChecker(emptyFunction.thatReturns(null)); +} + +function createArrayOfTypeChecker(typeChecker) { + function validate(props, propName, componentName, location, propFullName) { + var propValue = props[propName]; + if (!Array.isArray(propValue)) { + var locationName = ReactPropTypeLocationNames[location]; + var propType = getPropType(propValue); + return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.')); + } + for (var i = 0; i < propValue.length; i++) { + var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']'); + if (error instanceof Error) { + return error; + } + } + return null; + } + return createChainableTypeChecker(validate); +} + +function createElementTypeChecker() { + function validate(props, propName, componentName, location, propFullName) { + if (!ReactElement.isValidElement(props[propName])) { + var locationName = ReactPropTypeLocationNames[location]; + return new Error('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a single ReactElement.')); + } + return null; + } + return createChainableTypeChecker(validate); +} + +function createInstanceTypeChecker(expectedClass) { + function validate(props, propName, componentName, location, propFullName) { + if (!(props[propName] instanceof expectedClass)) { + var locationName = ReactPropTypeLocationNames[location]; + var expectedClassName = expectedClass.name || ANONYMOUS; + var actualClassName = getClassName(props[propName]); + return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.')); + } + return null; + } + return createChainableTypeChecker(validate); +} + +function createEnumTypeChecker(expectedValues) { + if (!Array.isArray(expectedValues)) { + return createChainableTypeChecker(function () { + return new Error('Invalid argument supplied to oneOf, expected an instance of array.'); + }); + } + + function validate(props, propName, componentName, location, propFullName) { + var propValue = props[propName]; + for (var i = 0; i < expectedValues.length; i++) { + if (propValue === expectedValues[i]) { + return null; + } + } + + var locationName = ReactPropTypeLocationNames[location]; + var valuesString = JSON.stringify(expectedValues); + return new Error('Invalid ' + locationName + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.')); + } + return createChainableTypeChecker(validate); +} + +function createObjectOfTypeChecker(typeChecker) { + function validate(props, propName, componentName, location, propFullName) { + var propValue = props[propName]; + var propType = getPropType(propValue); + if (propType !== 'object') { + var locationName = ReactPropTypeLocationNames[location]; + return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.')); + } + for (var key in propValue) { + if (propValue.hasOwnProperty(key)) { + var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key); + if (error instanceof Error) { + return error; + } + } + } + return null; + } + return createChainableTypeChecker(validate); +} + +function createUnionTypeChecker(arrayOfTypeCheckers) { + if (!Array.isArray(arrayOfTypeCheckers)) { + return createChainableTypeChecker(function () { + return new Error('Invalid argument supplied to oneOfType, expected an instance of array.'); + }); + } + + function validate(props, propName, componentName, location, propFullName) { + for (var i = 0; i < arrayOfTypeCheckers.length; i++) { + var checker = arrayOfTypeCheckers[i]; + if (checker(props, propName, componentName, location, propFullName) == null) { + return null; + } + } + + var locationName = ReactPropTypeLocationNames[location]; + return new Error('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.')); + } + return createChainableTypeChecker(validate); +} + +function createNodeChecker() { + function validate(props, propName, componentName, location, propFullName) { + if (!isNode(props[propName])) { + var locationName = ReactPropTypeLocationNames[location]; + return new Error('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.')); + } + return null; + } + return createChainableTypeChecker(validate); +} + +function createShapeTypeChecker(shapeTypes) { + function validate(props, propName, componentName, location, propFullName) { + var propValue = props[propName]; + var propType = getPropType(propValue); + if (propType !== 'object') { + var locationName = ReactPropTypeLocationNames[location]; + return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); + } + for (var key in shapeTypes) { + var checker = shapeTypes[key]; + if (!checker) { + continue; + } + var error = checker(propValue, key, componentName, location, propFullName + '.' + key); + if (error) { + return error; + } + } + return null; + } + return createChainableTypeChecker(validate); +} + +function isNode(propValue) { + switch (typeof propValue) { + case 'number': + case 'string': + case 'undefined': + return true; + case 'boolean': + return !propValue; + case 'object': + if (Array.isArray(propValue)) { + return propValue.every(isNode); + } + if (propValue === null || ReactElement.isValidElement(propValue)) { + return true; + } + + var iteratorFn = getIteratorFn(propValue); + if (iteratorFn) { + var iterator = iteratorFn.call(propValue); + var step; + if (iteratorFn !== propValue.entries) { + while (!(step = iterator.next()).done) { + if (!isNode(step.value)) { + return false; + } + } + } else { + // Iterator will provide entry [k,v] tuples rather than values. + while (!(step = iterator.next()).done) { + var entry = step.value; + if (entry) { + if (!isNode(entry[1])) { + return false; + } + } + } + } + } else { + return false; + } + + return true; + default: + return false; + } +} + +// Equivalent of `typeof` but with special handling for array and regexp. +function getPropType(propValue) { + var propType = typeof propValue; + if (Array.isArray(propValue)) { + return 'array'; + } + if (propValue instanceof RegExp) { + // Old webkits (at least until Android 4.0) return 'function' rather than + // 'object' for typeof a RegExp. We'll normalize this here so that /bla/ + // passes PropTypes.object. + return 'object'; + } + return propType; +} + +// This handles more types than `getPropType`. Only used for error messages. +// See `createPrimitiveTypeChecker`. +function getPreciseType(propValue) { + var propType = getPropType(propValue); + if (propType === 'object') { + if (propValue instanceof Date) { + return 'date'; + } else if (propValue instanceof RegExp) { + return 'regexp'; + } + } + return propType; +} + +// Returns class name of the object, if any. +function getClassName(propValue) { + if (!propValue.constructor || !propValue.constructor.name) { + return '<<anonymous>>'; + } + return propValue.constructor.name; +} + +module.exports = ReactPropTypes; +},{"129":129,"153":153,"57":57,"80":80}],83:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactReconcileTransaction + * @typechecks static-only + */ + +'use strict'; + +var CallbackQueue = _dereq_(6); +var PooledClass = _dereq_(25); +var ReactBrowserEventEmitter = _dereq_(28); +var ReactDOMFeatureFlags = _dereq_(44); +var ReactInputSelection = _dereq_(66); +var Transaction = _dereq_(113); + +var assign = _dereq_(24); + +/** + * Ensures that, when possible, the selection range (currently selected text + * input) is not disturbed by performing the transaction. + */ +var SELECTION_RESTORATION = { + /** + * @return {Selection} Selection information. + */ + initialize: ReactInputSelection.getSelectionInformation, + /** + * @param {Selection} sel Selection information returned from `initialize`. + */ + close: ReactInputSelection.restoreSelection +}; + +/** + * Suppresses events (blur/focus) that could be inadvertently dispatched due to + * high level DOM manipulations (like temporarily removing a text input from the + * DOM). + */ +var EVENT_SUPPRESSION = { + /** + * @return {boolean} The enabled status of `ReactBrowserEventEmitter` before + * the reconciliation. + */ + initialize: function () { + var currentlyEnabled = ReactBrowserEventEmitter.isEnabled(); + ReactBrowserEventEmitter.setEnabled(false); + return currentlyEnabled; + }, + + /** + * @param {boolean} previouslyEnabled Enabled status of + * `ReactBrowserEventEmitter` before the reconciliation occurred. `close` + * restores the previous value. + */ + close: function (previouslyEnabled) { + ReactBrowserEventEmitter.setEnabled(previouslyEnabled); + } +}; + +/** + * Provides a queue for collecting `componentDidMount` and + * `componentDidUpdate` callbacks during the the transaction. + */ +var ON_DOM_READY_QUEUEING = { + /** + * Initializes the internal `onDOMReady` queue. + */ + initialize: function () { + this.reactMountReady.reset(); + }, + + /** + * After DOM is flushed, invoke all registered `onDOMReady` callbacks. + */ + close: function () { + this.reactMountReady.notifyAll(); + } +}; + +/** + * Executed within the scope of the `Transaction` instance. Consider these as + * being member methods, but with an implied ordering while being isolated from + * each other. + */ +var TRANSACTION_WRAPPERS = [SELECTION_RESTORATION, EVENT_SUPPRESSION, ON_DOM_READY_QUEUEING]; + +/** + * Currently: + * - The order that these are listed in the transaction is critical: + * - Suppresses events. + * - Restores selection range. + * + * Future: + * - Restore document/overflow scroll positions that were unintentionally + * modified via DOM insertions above the top viewport boundary. + * - Implement/integrate with customized constraint based layout system and keep + * track of which dimensions must be remeasured. + * + * @class ReactReconcileTransaction + */ +function ReactReconcileTransaction(forceHTML) { + this.reinitializeTransaction(); + // Only server-side rendering really needs this option (see + // `ReactServerRendering`), but server-side uses + // `ReactServerRenderingTransaction` instead. This option is here so that it's + // accessible and defaults to false when `ReactDOMComponent` and + // `ReactTextComponent` checks it in `mountComponent`.` + this.renderToStaticMarkup = false; + this.reactMountReady = CallbackQueue.getPooled(null); + this.useCreateElement = !forceHTML && ReactDOMFeatureFlags.useCreateElement; +} + +var Mixin = { + /** + * @see Transaction + * @abstract + * @final + * @return {array<object>} List of operation wrap procedures. + * TODO: convert to array<TransactionWrapper> + */ + getTransactionWrappers: function () { + return TRANSACTION_WRAPPERS; + }, + + /** + * @return {object} The queue to collect `onDOMReady` callbacks with. + */ + getReactMountReady: function () { + return this.reactMountReady; + }, + + /** + * `PooledClass` looks for this, and will invoke this before allowing this + * instance to be reused. + */ + destructor: function () { + CallbackQueue.release(this.reactMountReady); + this.reactMountReady = null; + } +}; + +assign(ReactReconcileTransaction.prototype, Transaction.Mixin, Mixin); + +PooledClass.addPoolingTo(ReactReconcileTransaction); + +module.exports = ReactReconcileTransaction; +},{"113":113,"24":24,"25":25,"28":28,"44":44,"6":6,"66":66}],84:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactReconciler + */ + +'use strict'; + +var ReactRef = _dereq_(85); + +/** + * Helper to call ReactRef.attachRefs with this composite component, split out + * to avoid allocations in the transaction mount-ready queue. + */ +function attachRefs() { + ReactRef.attachRefs(this, this._currentElement); +} + +var ReactReconciler = { + + /** + * Initializes the component, renders markup, and registers event listeners. + * + * @param {ReactComponent} internalInstance + * @param {string} rootID DOM ID of the root node. + * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction + * @return {?string} Rendered markup to be inserted into the DOM. + * @final + * @internal + */ + mountComponent: function (internalInstance, rootID, transaction, context) { + var markup = internalInstance.mountComponent(rootID, transaction, context); + if (internalInstance._currentElement && internalInstance._currentElement.ref != null) { + transaction.getReactMountReady().enqueue(attachRefs, internalInstance); + } + return markup; + }, + + /** + * Releases any resources allocated by `mountComponent`. + * + * @final + * @internal + */ + unmountComponent: function (internalInstance) { + ReactRef.detachRefs(internalInstance, internalInstance._currentElement); + internalInstance.unmountComponent(); + }, + + /** + * Update a component using a new element. + * + * @param {ReactComponent} internalInstance + * @param {ReactElement} nextElement + * @param {ReactReconcileTransaction} transaction + * @param {object} context + * @internal + */ + receiveComponent: function (internalInstance, nextElement, transaction, context) { + var prevElement = internalInstance._currentElement; + + if (nextElement === prevElement && context === internalInstance._context) { + // Since elements are immutable after the owner is rendered, + // we can do a cheap identity compare here to determine if this is a + // superfluous reconcile. It's possible for state to be mutable but such + // change should trigger an update of the owner which would recreate + // the element. We explicitly check for the existence of an owner since + // it's possible for an element created outside a composite to be + // deeply mutated and reused. + + // TODO: Bailing out early is just a perf optimization right? + // TODO: Removing the return statement should affect correctness? + return; + } + + var refsChanged = ReactRef.shouldUpdateRefs(prevElement, nextElement); + + if (refsChanged) { + ReactRef.detachRefs(internalInstance, prevElement); + } + + internalInstance.receiveComponent(nextElement, transaction, context); + + if (refsChanged && internalInstance._currentElement && internalInstance._currentElement.ref != null) { + transaction.getReactMountReady().enqueue(attachRefs, internalInstance); + } + }, + + /** + * Flush any dirty changes in a component. + * + * @param {ReactComponent} internalInstance + * @param {ReactReconcileTransaction} transaction + * @internal + */ + performUpdateIfNecessary: function (internalInstance, transaction) { + internalInstance.performUpdateIfNecessary(transaction); + } + +}; + +module.exports = ReactReconciler; +},{"85":85}],85:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactRef + */ + +'use strict'; + +var ReactOwner = _dereq_(77); + +var ReactRef = {}; + +function attachRef(ref, component, owner) { + if (typeof ref === 'function') { + ref(component.getPublicInstance()); + } else { + // Legacy ref + ReactOwner.addComponentAsRefTo(component, ref, owner); + } +} + +function detachRef(ref, component, owner) { + if (typeof ref === 'function') { + ref(null); + } else { + // Legacy ref + ReactOwner.removeComponentAsRefFrom(component, ref, owner); + } +} + +ReactRef.attachRefs = function (instance, element) { + if (element === null || element === false) { + return; + } + var ref = element.ref; + if (ref != null) { + attachRef(ref, instance, element._owner); + } +}; + +ReactRef.shouldUpdateRefs = function (prevElement, nextElement) { + // If either the owner or a `ref` has changed, make sure the newest owner + // has stored a reference to `this`, and the previous owner (if different) + // has forgotten the reference to `this`. We use the element instead + // of the public this.props because the post processing cannot determine + // a ref. The ref conceptually lives on the element. + + // TODO: Should this even be possible? The owner cannot change because + // it's forbidden by shouldUpdateReactComponent. The ref can change + // if you swap the keys of but not the refs. Reconsider where this check + // is made. It probably belongs where the key checking and + // instantiateReactComponent is done. + + var prevEmpty = prevElement === null || prevElement === false; + var nextEmpty = nextElement === null || nextElement === false; + + return( + // This has a few false positives w/r/t empty components. + prevEmpty || nextEmpty || nextElement._owner !== prevElement._owner || nextElement.ref !== prevElement.ref + ); +}; + +ReactRef.detachRefs = function (instance, element) { + if (element === null || element === false) { + return; + } + var ref = element.ref; + if (ref != null) { + detachRef(ref, instance, element._owner); + } +}; + +module.exports = ReactRef; +},{"77":77}],86:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactRootIndex + * @typechecks + */ + +'use strict'; + +var ReactRootIndexInjection = { + /** + * @param {function} _createReactRootIndex + */ + injectCreateReactRootIndex: function (_createReactRootIndex) { + ReactRootIndex.createReactRootIndex = _createReactRootIndex; + } +}; + +var ReactRootIndex = { + createReactRootIndex: null, + injection: ReactRootIndexInjection +}; + +module.exports = ReactRootIndex; +},{}],87:[function(_dereq_,module,exports){ +/** + * Copyright 2014-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactServerBatchingStrategy + * @typechecks + */ + +'use strict'; + +var ReactServerBatchingStrategy = { + isBatchingUpdates: false, + batchedUpdates: function (callback) { + // Don't do anything here. During the server rendering we don't want to + // schedule any updates. We will simply ignore them. + } +}; + +module.exports = ReactServerBatchingStrategy; +},{}],88:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @typechecks static-only + * @providesModule ReactServerRendering + */ +'use strict'; + +var ReactDefaultBatchingStrategy = _dereq_(53); +var ReactElement = _dereq_(57); +var ReactInstanceHandles = _dereq_(67); +var ReactMarkupChecksum = _dereq_(71); +var ReactServerBatchingStrategy = _dereq_(87); +var ReactServerRenderingTransaction = _dereq_(89); +var ReactUpdates = _dereq_(96); + +var emptyObject = _dereq_(154); +var instantiateReactComponent = _dereq_(132); +var invariant = _dereq_(161); + +/** + * @param {ReactElement} element + * @return {string} the HTML markup + */ +function renderToString(element) { + !ReactElement.isValidElement(element) ? "development" !== 'production' ? invariant(false, 'renderToString(): You must pass a valid ReactElement.') : invariant(false) : undefined; + + var transaction; + try { + ReactUpdates.injection.injectBatchingStrategy(ReactServerBatchingStrategy); + + var id = ReactInstanceHandles.createReactRootID(); + transaction = ReactServerRenderingTransaction.getPooled(false); + + return transaction.perform(function () { + var componentInstance = instantiateReactComponent(element, null); + var markup = componentInstance.mountComponent(id, transaction, emptyObject); + return ReactMarkupChecksum.addChecksumToMarkup(markup); + }, null); + } finally { + ReactServerRenderingTransaction.release(transaction); + // Revert to the DOM batching strategy since these two renderers + // currently share these stateful modules. + ReactUpdates.injection.injectBatchingStrategy(ReactDefaultBatchingStrategy); + } +} + +/** + * @param {ReactElement} element + * @return {string} the HTML markup, without the extra React ID and checksum + * (for generating static pages) + */ +function renderToStaticMarkup(element) { + !ReactElement.isValidElement(element) ? "development" !== 'production' ? invariant(false, 'renderToStaticMarkup(): You must pass a valid ReactElement.') : invariant(false) : undefined; + + var transaction; + try { + ReactUpdates.injection.injectBatchingStrategy(ReactServerBatchingStrategy); + + var id = ReactInstanceHandles.createReactRootID(); + transaction = ReactServerRenderingTransaction.getPooled(true); + + return transaction.perform(function () { + var componentInstance = instantiateReactComponent(element, null); + return componentInstance.mountComponent(id, transaction, emptyObject); + }, null); + } finally { + ReactServerRenderingTransaction.release(transaction); + // Revert to the DOM batching strategy since these two renderers + // currently share these stateful modules. + ReactUpdates.injection.injectBatchingStrategy(ReactDefaultBatchingStrategy); + } +} + +module.exports = { + renderToString: renderToString, + renderToStaticMarkup: renderToStaticMarkup +}; +},{"132":132,"154":154,"161":161,"53":53,"57":57,"67":67,"71":71,"87":87,"89":89,"96":96}],89:[function(_dereq_,module,exports){ +/** + * Copyright 2014-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactServerRenderingTransaction + * @typechecks + */ + +'use strict'; + +var PooledClass = _dereq_(25); +var CallbackQueue = _dereq_(6); +var Transaction = _dereq_(113); + +var assign = _dereq_(24); +var emptyFunction = _dereq_(153); + +/** + * Provides a `CallbackQueue` queue for collecting `onDOMReady` callbacks + * during the performing of the transaction. + */ +var ON_DOM_READY_QUEUEING = { + /** + * Initializes the internal `onDOMReady` queue. + */ + initialize: function () { + this.reactMountReady.reset(); + }, + + close: emptyFunction +}; + +/** + * Executed within the scope of the `Transaction` instance. Consider these as + * being member methods, but with an implied ordering while being isolated from + * each other. + */ +var TRANSACTION_WRAPPERS = [ON_DOM_READY_QUEUEING]; + +/** + * @class ReactServerRenderingTransaction + * @param {boolean} renderToStaticMarkup + */ +function ReactServerRenderingTransaction(renderToStaticMarkup) { + this.reinitializeTransaction(); + this.renderToStaticMarkup = renderToStaticMarkup; + this.reactMountReady = CallbackQueue.getPooled(null); + this.useCreateElement = false; +} + +var Mixin = { + /** + * @see Transaction + * @abstract + * @final + * @return {array} Empty list of operation wrap procedures. + */ + getTransactionWrappers: function () { + return TRANSACTION_WRAPPERS; + }, + + /** + * @return {object} The queue to collect `onDOMReady` callbacks with. + */ + getReactMountReady: function () { + return this.reactMountReady; + }, + + /** + * `PooledClass` looks for this, and will invoke this before allowing this + * instance to be reused. + */ + destructor: function () { + CallbackQueue.release(this.reactMountReady); + this.reactMountReady = null; + } +}; + +assign(ReactServerRenderingTransaction.prototype, Transaction.Mixin, Mixin); + +PooledClass.addPoolingTo(ReactServerRenderingTransaction); + +module.exports = ReactServerRenderingTransaction; +},{"113":113,"153":153,"24":24,"25":25,"6":6}],90:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactStateSetters + */ + +'use strict'; + +var ReactStateSetters = { + /** + * Returns a function that calls the provided function, and uses the result + * of that to set the component's state. + * + * @param {ReactCompositeComponent} component + * @param {function} funcReturningState Returned callback uses this to + * determine how to update state. + * @return {function} callback that when invoked uses funcReturningState to + * determined the object literal to setState. + */ + createStateSetter: function (component, funcReturningState) { + return function (a, b, c, d, e, f) { + var partialState = funcReturningState.call(component, a, b, c, d, e, f); + if (partialState) { + component.setState(partialState); + } + }; + }, + + /** + * Returns a single-argument callback that can be used to update a single + * key in the component's state. + * + * Note: this is memoized function, which makes it inexpensive to call. + * + * @param {ReactCompositeComponent} component + * @param {string} key The key in the state that you should update. + * @return {function} callback of 1 argument which calls setState() with + * the provided keyName and callback argument. + */ + createStateKeySetter: function (component, key) { + // Memoize the setters. + var cache = component.__keySetters || (component.__keySetters = {}); + return cache[key] || (cache[key] = createStateKeySetter(component, key)); + } +}; + +function createStateKeySetter(component, key) { + // Partial state is allocated outside of the function closure so it can be + // reused with every call, avoiding memory allocation when this function + // is called. + var partialState = {}; + return function stateKeySetter(value) { + partialState[key] = value; + component.setState(partialState); + }; +} + +ReactStateSetters.Mixin = { + /** + * Returns a function that calls the provided function, and uses the result + * of that to set the component's state. + * + * For example, these statements are equivalent: + * + * this.setState({x: 1}); + * this.createStateSetter(function(xValue) { + * return {x: xValue}; + * })(1); + * + * @param {function} funcReturningState Returned callback uses this to + * determine how to update state. + * @return {function} callback that when invoked uses funcReturningState to + * determined the object literal to setState. + */ + createStateSetter: function (funcReturningState) { + return ReactStateSetters.createStateSetter(this, funcReturningState); + }, + + /** + * Returns a single-argument callback that can be used to update a single + * key in the component's state. + * + * For example, these statements are equivalent: + * + * this.setState({x: 1}); + * this.createStateKeySetter('x')(1); + * + * Note: this is memoized function, which makes it inexpensive to call. + * + * @param {string} key The key in the state that you should update. + * @return {function} callback of 1 argument which calls setState() with + * the provided keyName and callback argument. + */ + createStateKeySetter: function (key) { + return ReactStateSetters.createStateKeySetter(this, key); + } +}; + +module.exports = ReactStateSetters; +},{}],91:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactTestUtils + */ + +'use strict'; + +var EventConstants = _dereq_(15); +var EventPluginHub = _dereq_(16); +var EventPropagators = _dereq_(19); +var React = _dereq_(26); +var ReactDOM = _dereq_(40); +var ReactElement = _dereq_(57); +var ReactBrowserEventEmitter = _dereq_(28); +var ReactCompositeComponent = _dereq_(38); +var ReactInstanceHandles = _dereq_(67); +var ReactInstanceMap = _dereq_(68); +var ReactMount = _dereq_(72); +var ReactUpdates = _dereq_(96); +var SyntheticEvent = _dereq_(105); + +var assign = _dereq_(24); +var emptyObject = _dereq_(154); +var findDOMNode = _dereq_(122); +var invariant = _dereq_(161); + +var topLevelTypes = EventConstants.topLevelTypes; + +function Event(suffix) {} + +/** + * @class ReactTestUtils + */ + +function findAllInRenderedTreeInternal(inst, test) { + if (!inst || !inst.getPublicInstance) { + return []; + } + var publicInst = inst.getPublicInstance(); + var ret = test(publicInst) ? [publicInst] : []; + var currentElement = inst._currentElement; + if (ReactTestUtils.isDOMComponent(publicInst)) { + var renderedChildren = inst._renderedChildren; + var key; + for (key in renderedChildren) { + if (!renderedChildren.hasOwnProperty(key)) { + continue; + } + ret = ret.concat(findAllInRenderedTreeInternal(renderedChildren[key], test)); + } + } else if (ReactElement.isValidElement(currentElement) && typeof currentElement.type === 'function') { + ret = ret.concat(findAllInRenderedTreeInternal(inst._renderedComponent, test)); + } + return ret; +} + +/** + * Todo: Support the entire DOM.scry query syntax. For now, these simple + * utilities will suffice for testing purposes. + * @lends ReactTestUtils + */ +var ReactTestUtils = { + renderIntoDocument: function (instance) { + var div = document.createElementNS('http://www.w3.org/1999/xhtml', 'div'); + // None of our tests actually require attaching the container to the + // DOM, and doing so creates a mess that we rely on test isolation to + // clean up, so we're going to stop honoring the name of this method + // (and probably rename it eventually) if no problems arise. + // document.documentElement.appendChild(div); + return ReactDOM.render(instance, div); + }, + + isElement: function (element) { + return ReactElement.isValidElement(element); + }, + + isElementOfType: function (inst, convenienceConstructor) { + return ReactElement.isValidElement(inst) && inst.type === convenienceConstructor; + }, + + isDOMComponent: function (inst) { + return !!(inst && inst.nodeType === 1 && inst.tagName); + }, + + isDOMComponentElement: function (inst) { + return !!(inst && ReactElement.isValidElement(inst) && !!inst.tagName); + }, + + isCompositeComponent: function (inst) { + if (ReactTestUtils.isDOMComponent(inst)) { + // Accessing inst.setState warns; just return false as that'll be what + // this returns when we have DOM nodes as refs directly + return false; + } + return inst != null && typeof inst.render === 'function' && typeof inst.setState === 'function'; + }, + + isCompositeComponentWithType: function (inst, type) { + if (!ReactTestUtils.isCompositeComponent(inst)) { + return false; + } + var internalInstance = ReactInstanceMap.get(inst); + var constructor = internalInstance._currentElement.type; + + return constructor === type; + }, + + isCompositeComponentElement: function (inst) { + if (!ReactElement.isValidElement(inst)) { + return false; + } + // We check the prototype of the type that will get mounted, not the + // instance itself. This is a future proof way of duck typing. + var prototype = inst.type.prototype; + return typeof prototype.render === 'function' && typeof prototype.setState === 'function'; + }, + + isCompositeComponentElementWithType: function (inst, type) { + var internalInstance = ReactInstanceMap.get(inst); + var constructor = internalInstance._currentElement.type; + + return !!(ReactTestUtils.isCompositeComponentElement(inst) && constructor === type); + }, + + getRenderedChildOfCompositeComponent: function (inst) { + if (!ReactTestUtils.isCompositeComponent(inst)) { + return null; + } + var internalInstance = ReactInstanceMap.get(inst); + return internalInstance._renderedComponent.getPublicInstance(); + }, + + findAllInRenderedTree: function (inst, test) { + if (!inst) { + return []; + } + !ReactTestUtils.isCompositeComponent(inst) ? "development" !== 'production' ? invariant(false, 'findAllInRenderedTree(...): instance must be a composite component') : invariant(false) : undefined; + return findAllInRenderedTreeInternal(ReactInstanceMap.get(inst), test); + }, + + /** + * Finds all instance of components in the rendered tree that are DOM + * components with the class name matching `className`. + * @return {array} an array of all the matches. + */ + scryRenderedDOMComponentsWithClass: function (root, classNames) { + if (!Array.isArray(classNames)) { + classNames = classNames.split(/\s+/); + } + return ReactTestUtils.findAllInRenderedTree(root, function (inst) { + if (ReactTestUtils.isDOMComponent(inst)) { + var className = inst.className; + if (typeof className !== 'string') { + // SVG, probably. + className = inst.getAttribute('class') || ''; + } + var classList = className.split(/\s+/); + return classNames.every(function (name) { + return classList.indexOf(name) !== -1; + }); + } + return false; + }); + }, + + /** + * Like scryRenderedDOMComponentsWithClass but expects there to be one result, + * and returns that one result, or throws exception if there is any other + * number of matches besides one. + * @return {!ReactDOMComponent} The one match. + */ + findRenderedDOMComponentWithClass: function (root, className) { + var all = ReactTestUtils.scryRenderedDOMComponentsWithClass(root, className); + if (all.length !== 1) { + throw new Error('Did not find exactly one match ' + '(found: ' + all.length + ') for class:' + className); + } + return all[0]; + }, + + /** + * Finds all instance of components in the rendered tree that are DOM + * components with the tag name matching `tagName`. + * @return {array} an array of all the matches. + */ + scryRenderedDOMComponentsWithTag: function (root, tagName) { + return ReactTestUtils.findAllInRenderedTree(root, function (inst) { + return ReactTestUtils.isDOMComponent(inst) && inst.tagName.toUpperCase() === tagName.toUpperCase(); + }); + }, + + /** + * Like scryRenderedDOMComponentsWithTag but expects there to be one result, + * and returns that one result, or throws exception if there is any other + * number of matches besides one. + * @return {!ReactDOMComponent} The one match. + */ + findRenderedDOMComponentWithTag: function (root, tagName) { + var all = ReactTestUtils.scryRenderedDOMComponentsWithTag(root, tagName); + if (all.length !== 1) { + throw new Error('Did not find exactly one match for tag:' + tagName); + } + return all[0]; + }, + + /** + * Finds all instances of components with type equal to `componentType`. + * @return {array} an array of all the matches. + */ + scryRenderedComponentsWithType: function (root, componentType) { + return ReactTestUtils.findAllInRenderedTree(root, function (inst) { + return ReactTestUtils.isCompositeComponentWithType(inst, componentType); + }); + }, + + /** + * Same as `scryRenderedComponentsWithType` but expects there to be one result + * and returns that one result, or throws exception if there is any other + * number of matches besides one. + * @return {!ReactComponent} The one match. + */ + findRenderedComponentWithType: function (root, componentType) { + var all = ReactTestUtils.scryRenderedComponentsWithType(root, componentType); + if (all.length !== 1) { + throw new Error('Did not find exactly one match for componentType:' + componentType + ' (found ' + all.length + ')'); + } + return all[0]; + }, + + /** + * Pass a mocked component module to this method to augment it with + * useful methods that allow it to be used as a dummy React component. + * Instead of rendering as usual, the component will become a simple + * <div> containing any provided children. + * + * @param {object} module the mock function object exported from a + * module that defines the component to be mocked + * @param {?string} mockTagName optional dummy root tag name to return + * from render method (overrides + * module.mockTagName if provided) + * @return {object} the ReactTestUtils object (for chaining) + */ + mockComponent: function (module, mockTagName) { + mockTagName = mockTagName || module.mockTagName || 'div'; + + module.prototype.render.mockImplementation(function () { + return React.createElement(mockTagName, null, this.props.children); + }); + + return this; + }, + + /** + * Simulates a top level event being dispatched from a raw event that occurred + * on an `Element` node. + * @param {Object} topLevelType A type from `EventConstants.topLevelTypes` + * @param {!Element} node The dom to simulate an event occurring on. + * @param {?Event} fakeNativeEvent Fake native event to use in SyntheticEvent. + */ + simulateNativeEventOnNode: function (topLevelType, node, fakeNativeEvent) { + fakeNativeEvent.target = node; + ReactBrowserEventEmitter.ReactEventListener.dispatchEvent(topLevelType, fakeNativeEvent); + }, + + /** + * Simulates a top level event being dispatched from a raw event that occurred + * on the `ReactDOMComponent` `comp`. + * @param {Object} topLevelType A type from `EventConstants.topLevelTypes`. + * @param {!ReactDOMComponent} comp + * @param {?Event} fakeNativeEvent Fake native event to use in SyntheticEvent. + */ + simulateNativeEventOnDOMComponent: function (topLevelType, comp, fakeNativeEvent) { + ReactTestUtils.simulateNativeEventOnNode(topLevelType, findDOMNode(comp), fakeNativeEvent); + }, + + nativeTouchData: function (x, y) { + return { + touches: [{ pageX: x, pageY: y }] + }; + }, + + createRenderer: function () { + return new ReactShallowRenderer(); + }, + + Simulate: null, + SimulateNative: {} +}; + +/** + * @class ReactShallowRenderer + */ +var ReactShallowRenderer = function () { + this._instance = null; +}; + +ReactShallowRenderer.prototype.getRenderOutput = function () { + return this._instance && this._instance._renderedComponent && this._instance._renderedComponent._renderedOutput || null; +}; + +var NoopInternalComponent = function (element) { + this._renderedOutput = element; + this._currentElement = element; +}; + +NoopInternalComponent.prototype = { + + mountComponent: function () {}, + + receiveComponent: function (element) { + this._renderedOutput = element; + this._currentElement = element; + }, + + unmountComponent: function () {}, + + getPublicInstance: function () { + return null; + } +}; + +var ShallowComponentWrapper = function () {}; +assign(ShallowComponentWrapper.prototype, ReactCompositeComponent.Mixin, { + _instantiateReactComponent: function (element) { + return new NoopInternalComponent(element); + }, + _replaceNodeWithMarkupByID: function () {}, + _renderValidatedComponent: ReactCompositeComponent.Mixin._renderValidatedComponentWithoutOwnerOrContext +}); + +ReactShallowRenderer.prototype.render = function (element, context) { + !ReactElement.isValidElement(element) ? "development" !== 'production' ? invariant(false, 'ReactShallowRenderer render(): Invalid component element.%s', typeof element === 'function' ? ' Instead of passing a component class, make sure to instantiate ' + 'it by passing it to React.createElement.' : '') : invariant(false) : undefined; + !(typeof element.type !== 'string') ? "development" !== 'production' ? invariant(false, 'ReactShallowRenderer render(): Shallow rendering works only with custom ' + 'components, not primitives (%s). Instead of calling `.render(el)` and ' + 'inspecting the rendered output, look at `el.props` directly instead.', element.type) : invariant(false) : undefined; + + if (!context) { + context = emptyObject; + } + var transaction = ReactUpdates.ReactReconcileTransaction.getPooled(false); + this._render(element, transaction, context); + ReactUpdates.ReactReconcileTransaction.release(transaction); +}; + +ReactShallowRenderer.prototype.unmount = function () { + if (this._instance) { + this._instance.unmountComponent(); + } +}; + +ReactShallowRenderer.prototype._render = function (element, transaction, context) { + if (this._instance) { + this._instance.receiveComponent(element, transaction, context); + } else { + var rootID = ReactInstanceHandles.createReactRootID(); + var instance = new ShallowComponentWrapper(element.type); + instance.construct(element); + + instance.mountComponent(rootID, transaction, context); + + this._instance = instance; + } +}; + +/** + * Exports: + * + * - `ReactTestUtils.Simulate.click(Element/ReactDOMComponent)` + * - `ReactTestUtils.Simulate.mouseMove(Element/ReactDOMComponent)` + * - `ReactTestUtils.Simulate.change(Element/ReactDOMComponent)` + * - ... (All keys from event plugin `eventTypes` objects) + */ +function makeSimulator(eventType) { + return function (domComponentOrNode, eventData) { + var node; + if (ReactTestUtils.isDOMComponent(domComponentOrNode)) { + node = findDOMNode(domComponentOrNode); + } else if (domComponentOrNode.tagName) { + node = domComponentOrNode; + } + + var dispatchConfig = ReactBrowserEventEmitter.eventNameDispatchConfigs[eventType]; + + var fakeNativeEvent = new Event(); + fakeNativeEvent.target = node; + // We don't use SyntheticEvent.getPooled in order to not have to worry about + // properly destroying any properties assigned from `eventData` upon release + var event = new SyntheticEvent(dispatchConfig, ReactMount.getID(node), fakeNativeEvent, node); + assign(event, eventData); + + if (dispatchConfig.phasedRegistrationNames) { + EventPropagators.accumulateTwoPhaseDispatches(event); + } else { + EventPropagators.accumulateDirectDispatches(event); + } + + ReactUpdates.batchedUpdates(function () { + EventPluginHub.enqueueEvents(event); + EventPluginHub.processEventQueue(true); + }); + }; +} + +function buildSimulators() { + ReactTestUtils.Simulate = {}; + + var eventType; + for (eventType in ReactBrowserEventEmitter.eventNameDispatchConfigs) { + /** + * @param {!Element|ReactDOMComponent} domComponentOrNode + * @param {?object} eventData Fake event data to use in SyntheticEvent. + */ + ReactTestUtils.Simulate[eventType] = makeSimulator(eventType); + } +} + +// Rebuild ReactTestUtils.Simulate whenever event plugins are injected +var oldInjectEventPluginOrder = EventPluginHub.injection.injectEventPluginOrder; +EventPluginHub.injection.injectEventPluginOrder = function () { + oldInjectEventPluginOrder.apply(this, arguments); + buildSimulators(); +}; +var oldInjectEventPlugins = EventPluginHub.injection.injectEventPluginsByName; +EventPluginHub.injection.injectEventPluginsByName = function () { + oldInjectEventPlugins.apply(this, arguments); + buildSimulators(); +}; + +buildSimulators(); + +/** + * Exports: + * + * - `ReactTestUtils.SimulateNative.click(Element/ReactDOMComponent)` + * - `ReactTestUtils.SimulateNative.mouseMove(Element/ReactDOMComponent)` + * - `ReactTestUtils.SimulateNative.mouseIn/ReactDOMComponent)` + * - `ReactTestUtils.SimulateNative.mouseOut(Element/ReactDOMComponent)` + * - ... (All keys from `EventConstants.topLevelTypes`) + * + * Note: Top level event types are a subset of the entire set of handler types + * (which include a broader set of "synthetic" events). For example, onDragDone + * is a synthetic event. Except when testing an event plugin or React's event + * handling code specifically, you probably want to use ReactTestUtils.Simulate + * to dispatch synthetic events. + */ + +function makeNativeSimulator(eventType) { + return function (domComponentOrNode, nativeEventData) { + var fakeNativeEvent = new Event(eventType); + assign(fakeNativeEvent, nativeEventData); + if (ReactTestUtils.isDOMComponent(domComponentOrNode)) { + ReactTestUtils.simulateNativeEventOnDOMComponent(eventType, domComponentOrNode, fakeNativeEvent); + } else if (domComponentOrNode.tagName) { + // Will allow on actual dom nodes. + ReactTestUtils.simulateNativeEventOnNode(eventType, domComponentOrNode, fakeNativeEvent); + } + }; +} + +Object.keys(topLevelTypes).forEach(function (eventType) { + // Event type is stored as 'topClick' - we transform that to 'click' + var convenienceName = eventType.indexOf('top') === 0 ? eventType.charAt(3).toLowerCase() + eventType.substr(4) : eventType; + /** + * @param {!Element|ReactDOMComponent} domComponentOrNode + * @param {?Event} nativeEventData Fake native event to use in SyntheticEvent. + */ + ReactTestUtils.SimulateNative[convenienceName] = makeNativeSimulator(eventType); +}); + +module.exports = ReactTestUtils; +},{"105":105,"122":122,"15":15,"154":154,"16":16,"161":161,"19":19,"24":24,"26":26,"28":28,"38":38,"40":40,"57":57,"67":67,"68":68,"72":72,"96":96}],92:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @typechecks static-only + * @providesModule ReactTransitionChildMapping + */ + +'use strict'; + +var flattenChildren = _dereq_(123); + +var ReactTransitionChildMapping = { + /** + * Given `this.props.children`, return an object mapping key to child. Just + * simple syntactic sugar around flattenChildren(). + * + * @param {*} children `this.props.children` + * @return {object} Mapping of key to child + */ + getChildMapping: function (children) { + if (!children) { + return children; + } + return flattenChildren(children); + }, + + /** + * When you're adding or removing children some may be added or removed in the + * same render pass. We want to show *both* since we want to simultaneously + * animate elements in and out. This function takes a previous set of keys + * and a new set of keys and merges them with its best guess of the correct + * ordering. In the future we may expose some of the utilities in + * ReactMultiChild to make this easy, but for now React itself does not + * directly have this concept of the union of prevChildren and nextChildren + * so we implement it here. + * + * @param {object} prev prev children as returned from + * `ReactTransitionChildMapping.getChildMapping()`. + * @param {object} next next children as returned from + * `ReactTransitionChildMapping.getChildMapping()`. + * @return {object} a key set that contains all keys in `prev` and all keys + * in `next` in a reasonable order. + */ + mergeChildMappings: function (prev, next) { + prev = prev || {}; + next = next || {}; + + function getValueForKey(key) { + if (next.hasOwnProperty(key)) { + return next[key]; + } else { + return prev[key]; + } + } + + // For each key of `next`, the list of keys to insert before that key in + // the combined list + var nextKeysPending = {}; + + var pendingKeys = []; + for (var prevKey in prev) { + if (next.hasOwnProperty(prevKey)) { + if (pendingKeys.length) { + nextKeysPending[prevKey] = pendingKeys; + pendingKeys = []; + } + } else { + pendingKeys.push(prevKey); + } + } + + var i; + var childMapping = {}; + for (var nextKey in next) { + if (nextKeysPending.hasOwnProperty(nextKey)) { + for (i = 0; i < nextKeysPending[nextKey].length; i++) { + var pendingNextKey = nextKeysPending[nextKey][i]; + childMapping[nextKeysPending[nextKey][i]] = getValueForKey(pendingNextKey); + } + } + childMapping[nextKey] = getValueForKey(nextKey); + } + + // Finally, add the keys which didn't appear before any key in `next` + for (i = 0; i < pendingKeys.length; i++) { + childMapping[pendingKeys[i]] = getValueForKey(pendingKeys[i]); + } + + return childMapping; + } +}; + +module.exports = ReactTransitionChildMapping; +},{"123":123}],93:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactTransitionEvents + */ + +'use strict'; + +var ExecutionEnvironment = _dereq_(147); + +/** + * EVENT_NAME_MAP is used to determine which event fired when a + * transition/animation ends, based on the style property used to + * define that event. + */ +var EVENT_NAME_MAP = { + transitionend: { + 'transition': 'transitionend', + 'WebkitTransition': 'webkitTransitionEnd', + 'MozTransition': 'mozTransitionEnd', + 'OTransition': 'oTransitionEnd', + 'msTransition': 'MSTransitionEnd' + }, + + animationend: { + 'animation': 'animationend', + 'WebkitAnimation': 'webkitAnimationEnd', + 'MozAnimation': 'mozAnimationEnd', + 'OAnimation': 'oAnimationEnd', + 'msAnimation': 'MSAnimationEnd' + } +}; + +var endEvents = []; + +function detectEvents() { + var testEl = document.createElementNS('http://www.w3.org/1999/xhtml', 'div'); + var style = testEl.style; + + // On some platforms, in particular some releases of Android 4.x, + // the un-prefixed "animation" and "transition" properties are defined on the + // style object but the events that fire will still be prefixed, so we need + // to check if the un-prefixed events are useable, and if not remove them + // from the map + if (!('AnimationEvent' in window)) { + delete EVENT_NAME_MAP.animationend.animation; + } + + if (!('TransitionEvent' in window)) { + delete EVENT_NAME_MAP.transitionend.transition; + } + + for (var baseEventName in EVENT_NAME_MAP) { + var baseEvents = EVENT_NAME_MAP[baseEventName]; + for (var styleName in baseEvents) { + if (styleName in style) { + endEvents.push(baseEvents[styleName]); + break; + } + } + } +} + +if (ExecutionEnvironment.canUseDOM) { + detectEvents(); +} + +// We use the raw {add|remove}EventListener() call because EventListener +// does not know how to remove event listeners and we really should +// clean up. Also, these events are not triggered in older browsers +// so we should be A-OK here. + +function addEventListener(node, eventName, eventListener) { + node.addEventListener(eventName, eventListener, false); +} + +function removeEventListener(node, eventName, eventListener) { + node.removeEventListener(eventName, eventListener, false); +} + +var ReactTransitionEvents = { + addEndEventListener: function (node, eventListener) { + if (endEvents.length === 0) { + // If CSS transitions are not supported, trigger an "end animation" + // event immediately. + window.setTimeout(eventListener, 0); + return; + } + endEvents.forEach(function (endEvent) { + addEventListener(node, endEvent, eventListener); + }); + }, + + removeEndEventListener: function (node, eventListener) { + if (endEvents.length === 0) { + return; + } + endEvents.forEach(function (endEvent) { + removeEventListener(node, endEvent, eventListener); + }); + } +}; + +module.exports = ReactTransitionEvents; +},{"147":147}],94:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactTransitionGroup + */ + +'use strict'; + +var React = _dereq_(26); +var ReactTransitionChildMapping = _dereq_(92); + +var assign = _dereq_(24); +var emptyFunction = _dereq_(153); + +var ReactTransitionGroup = React.createClass({ + displayName: 'ReactTransitionGroup', + + propTypes: { + component: React.PropTypes.any, + childFactory: React.PropTypes.func + }, + + getDefaultProps: function () { + return { + component: 'span', + childFactory: emptyFunction.thatReturnsArgument + }; + }, + + getInitialState: function () { + return { + children: ReactTransitionChildMapping.getChildMapping(this.props.children) + }; + }, + + componentWillMount: function () { + this.currentlyTransitioningKeys = {}; + this.keysToEnter = []; + this.keysToLeave = []; + }, + + componentDidMount: function () { + var initialChildMapping = this.state.children; + for (var key in initialChildMapping) { + if (initialChildMapping[key]) { + this.performAppear(key); + } + } + }, + + componentWillReceiveProps: function (nextProps) { + var nextChildMapping = ReactTransitionChildMapping.getChildMapping(nextProps.children); + var prevChildMapping = this.state.children; + + this.setState({ + children: ReactTransitionChildMapping.mergeChildMappings(prevChildMapping, nextChildMapping) + }); + + var key; + + for (key in nextChildMapping) { + var hasPrev = prevChildMapping && prevChildMapping.hasOwnProperty(key); + if (nextChildMapping[key] && !hasPrev && !this.currentlyTransitioningKeys[key]) { + this.keysToEnter.push(key); + } + } + + for (key in prevChildMapping) { + var hasNext = nextChildMapping && nextChildMapping.hasOwnProperty(key); + if (prevChildMapping[key] && !hasNext && !this.currentlyTransitioningKeys[key]) { + this.keysToLeave.push(key); + } + } + + // If we want to someday check for reordering, we could do it here. + }, + + componentDidUpdate: function () { + var keysToEnter = this.keysToEnter; + this.keysToEnter = []; + keysToEnter.forEach(this.performEnter); + + var keysToLeave = this.keysToLeave; + this.keysToLeave = []; + keysToLeave.forEach(this.performLeave); + }, + + performAppear: function (key) { + this.currentlyTransitioningKeys[key] = true; + + var component = this.refs[key]; + + if (component.componentWillAppear) { + component.componentWillAppear(this._handleDoneAppearing.bind(this, key)); + } else { + this._handleDoneAppearing(key); + } + }, + + _handleDoneAppearing: function (key) { + var component = this.refs[key]; + if (component.componentDidAppear) { + component.componentDidAppear(); + } + + delete this.currentlyTransitioningKeys[key]; + + var currentChildMapping = ReactTransitionChildMapping.getChildMapping(this.props.children); + + if (!currentChildMapping || !currentChildMapping.hasOwnProperty(key)) { + // This was removed before it had fully appeared. Remove it. + this.performLeave(key); + } + }, + + performEnter: function (key) { + this.currentlyTransitioningKeys[key] = true; + + var component = this.refs[key]; + + if (component.componentWillEnter) { + component.componentWillEnter(this._handleDoneEntering.bind(this, key)); + } else { + this._handleDoneEntering(key); + } + }, + + _handleDoneEntering: function (key) { + var component = this.refs[key]; + if (component.componentDidEnter) { + component.componentDidEnter(); + } + + delete this.currentlyTransitioningKeys[key]; + + var currentChildMapping = ReactTransitionChildMapping.getChildMapping(this.props.children); + + if (!currentChildMapping || !currentChildMapping.hasOwnProperty(key)) { + // This was removed before it had fully entered. Remove it. + this.performLeave(key); + } + }, + + performLeave: function (key) { + this.currentlyTransitioningKeys[key] = true; + + var component = this.refs[key]; + if (component.componentWillLeave) { + component.componentWillLeave(this._handleDoneLeaving.bind(this, key)); + } else { + // Note that this is somewhat dangerous b/c it calls setState() + // again, effectively mutating the component before all the work + // is done. + this._handleDoneLeaving(key); + } + }, + + _handleDoneLeaving: function (key) { + var component = this.refs[key]; + + if (component.componentDidLeave) { + component.componentDidLeave(); + } + + delete this.currentlyTransitioningKeys[key]; + + var currentChildMapping = ReactTransitionChildMapping.getChildMapping(this.props.children); + + if (currentChildMapping && currentChildMapping.hasOwnProperty(key)) { + // This entered again before it fully left. Add it again. + this.performEnter(key); + } else { + this.setState(function (state) { + var newChildren = assign({}, state.children); + delete newChildren[key]; + return { children: newChildren }; + }); + } + }, + + render: function () { + // TODO: we could get rid of the need for the wrapper node + // by cloning a single child + var childrenToRender = []; + for (var key in this.state.children) { + var child = this.state.children[key]; + if (child) { + // You may need to apply reactive updates to a child as it is leaving. + // The normal React way to do it won't work since the child will have + // already been removed. In case you need this behavior you can provide + // a childFactory function to wrap every child, even the ones that are + // leaving. + childrenToRender.push(React.cloneElement(this.props.childFactory(child), { ref: key, key: key })); + } + } + return React.createElement(this.props.component, this.props, childrenToRender); + } +}); + +module.exports = ReactTransitionGroup; +},{"153":153,"24":24,"26":26,"92":92}],95:[function(_dereq_,module,exports){ +/** + * Copyright 2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactUpdateQueue + */ + +'use strict'; + +var ReactCurrentOwner = _dereq_(39); +var ReactElement = _dereq_(57); +var ReactInstanceMap = _dereq_(68); +var ReactUpdates = _dereq_(96); + +var assign = _dereq_(24); +var invariant = _dereq_(161); +var warning = _dereq_(173); + +function enqueueUpdate(internalInstance) { + ReactUpdates.enqueueUpdate(internalInstance); +} + +function getInternalInstanceReadyForUpdate(publicInstance, callerName) { + var internalInstance = ReactInstanceMap.get(publicInstance); + if (!internalInstance) { + if ("development" !== 'production') { + // Only warn when we have a callerName. Otherwise we should be silent. + // We're probably calling from enqueueCallback. We don't want to warn + // there because we already warned for the corresponding lifecycle method. + "development" !== 'production' ? warning(!callerName, '%s(...): Can only update a mounted or mounting component. ' + 'This usually means you called %s() on an unmounted component. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, publicInstance.constructor.displayName) : undefined; + } + return null; + } + + if ("development" !== 'production') { + "development" !== 'production' ? warning(ReactCurrentOwner.current == null, '%s(...): Cannot update during an existing state transition ' + '(such as within `render`). Render methods should be a pure function ' + 'of props and state.', callerName) : undefined; + } + + return internalInstance; +} + +/** + * ReactUpdateQueue allows for state updates to be scheduled into a later + * reconciliation step. + */ +var ReactUpdateQueue = { + + /** + * Checks whether or not this composite component is mounted. + * @param {ReactClass} publicInstance The instance we want to test. + * @return {boolean} True if mounted, false otherwise. + * @protected + * @final + */ + isMounted: function (publicInstance) { + if ("development" !== 'production') { + var owner = ReactCurrentOwner.current; + if (owner !== null) { + "development" !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing isMounted inside its render() function. ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component') : undefined; + owner._warnedAboutRefsInRender = true; + } + } + var internalInstance = ReactInstanceMap.get(publicInstance); + if (internalInstance) { + // During componentWillMount and render this will still be null but after + // that will always render to something. At least for now. So we can use + // this hack. + return !!internalInstance._renderedComponent; + } else { + return false; + } + }, + + /** + * Enqueue a callback that will be executed after all the pending updates + * have processed. + * + * @param {ReactClass} publicInstance The instance to use as `this` context. + * @param {?function} callback Called after state is updated. + * @internal + */ + enqueueCallback: function (publicInstance, callback) { + !(typeof callback === 'function') ? "development" !== 'production' ? invariant(false, 'enqueueCallback(...): You called `setProps`, `replaceProps`, ' + '`setState`, `replaceState`, or `forceUpdate` with a callback that ' + 'isn\'t callable.') : invariant(false) : undefined; + var internalInstance = getInternalInstanceReadyForUpdate(publicInstance); + + // Previously we would throw an error if we didn't have an internal + // instance. Since we want to make it a no-op instead, we mirror the same + // behavior we have in other enqueue* methods. + // We also need to ignore callbacks in componentWillMount. See + // enqueueUpdates. + if (!internalInstance) { + return null; + } + + if (internalInstance._pendingCallbacks) { + internalInstance._pendingCallbacks.push(callback); + } else { + internalInstance._pendingCallbacks = [callback]; + } + // TODO: The callback here is ignored when setState is called from + // componentWillMount. Either fix it or disallow doing so completely in + // favor of getInitialState. Alternatively, we can disallow + // componentWillMount during server-side rendering. + enqueueUpdate(internalInstance); + }, + + enqueueCallbackInternal: function (internalInstance, callback) { + !(typeof callback === 'function') ? "development" !== 'production' ? invariant(false, 'enqueueCallback(...): You called `setProps`, `replaceProps`, ' + '`setState`, `replaceState`, or `forceUpdate` with a callback that ' + 'isn\'t callable.') : invariant(false) : undefined; + if (internalInstance._pendingCallbacks) { + internalInstance._pendingCallbacks.push(callback); + } else { + internalInstance._pendingCallbacks = [callback]; + } + enqueueUpdate(internalInstance); + }, + + /** + * Forces an update. This should only be invoked when it is known with + * certainty that we are **not** in a DOM transaction. + * + * You may want to call this when you know that some deeper aspect of the + * component's state has changed but `setState` was not called. + * + * This will not invoke `shouldComponentUpdate`, but it will invoke + * `componentWillUpdate` and `componentDidUpdate`. + * + * @param {ReactClass} publicInstance The instance that should rerender. + * @internal + */ + enqueueForceUpdate: function (publicInstance) { + var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'forceUpdate'); + + if (!internalInstance) { + return; + } + + internalInstance._pendingForceUpdate = true; + + enqueueUpdate(internalInstance); + }, + + /** + * Replaces all of the state. Always use this or `setState` to mutate state. + * You should treat `this.state` as immutable. + * + * There is no guarantee that `this.state` will be immediately updated, so + * accessing `this.state` after calling this method may return the old value. + * + * @param {ReactClass} publicInstance The instance that should rerender. + * @param {object} completeState Next state. + * @internal + */ + enqueueReplaceState: function (publicInstance, completeState) { + var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'replaceState'); + + if (!internalInstance) { + return; + } + + internalInstance._pendingStateQueue = [completeState]; + internalInstance._pendingReplaceState = true; + + enqueueUpdate(internalInstance); + }, + + /** + * Sets a subset of the state. This only exists because _pendingState is + * internal. This provides a merging strategy that is not available to deep + * properties which is confusing. TODO: Expose pendingState or don't use it + * during the merge. + * + * @param {ReactClass} publicInstance The instance that should rerender. + * @param {object} partialState Next partial state to be merged with state. + * @internal + */ + enqueueSetState: function (publicInstance, partialState) { + var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'setState'); + + if (!internalInstance) { + return; + } + + var queue = internalInstance._pendingStateQueue || (internalInstance._pendingStateQueue = []); + queue.push(partialState); + + enqueueUpdate(internalInstance); + }, + + /** + * Sets a subset of the props. + * + * @param {ReactClass} publicInstance The instance that should rerender. + * @param {object} partialProps Subset of the next props. + * @internal + */ + enqueueSetProps: function (publicInstance, partialProps) { + var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'setProps'); + if (!internalInstance) { + return; + } + ReactUpdateQueue.enqueueSetPropsInternal(internalInstance, partialProps); + }, + + enqueueSetPropsInternal: function (internalInstance, partialProps) { + var topLevelWrapper = internalInstance._topLevelWrapper; + !topLevelWrapper ? "development" !== 'production' ? invariant(false, 'setProps(...): You called `setProps` on a ' + 'component with a parent. This is an anti-pattern since props will ' + 'get reactively updated when rendered. Instead, change the owner\'s ' + '`render` method to pass the correct value as props to the component ' + 'where it is created.') : invariant(false) : undefined; + + // Merge with the pending element if it exists, otherwise with existing + // element props. + var wrapElement = topLevelWrapper._pendingElement || topLevelWrapper._currentElement; + var element = wrapElement.props; + var props = assign({}, element.props, partialProps); + topLevelWrapper._pendingElement = ReactElement.cloneAndReplaceProps(wrapElement, ReactElement.cloneAndReplaceProps(element, props)); + + enqueueUpdate(topLevelWrapper); + }, + + /** + * Replaces all of the props. + * + * @param {ReactClass} publicInstance The instance that should rerender. + * @param {object} props New props. + * @internal + */ + enqueueReplaceProps: function (publicInstance, props) { + var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'replaceProps'); + if (!internalInstance) { + return; + } + ReactUpdateQueue.enqueueReplacePropsInternal(internalInstance, props); + }, + + enqueueReplacePropsInternal: function (internalInstance, props) { + var topLevelWrapper = internalInstance._topLevelWrapper; + !topLevelWrapper ? "development" !== 'production' ? invariant(false, 'replaceProps(...): You called `replaceProps` on a ' + 'component with a parent. This is an anti-pattern since props will ' + 'get reactively updated when rendered. Instead, change the owner\'s ' + '`render` method to pass the correct value as props to the component ' + 'where it is created.') : invariant(false) : undefined; + + // Merge with the pending element if it exists, otherwise with existing + // element props. + var wrapElement = topLevelWrapper._pendingElement || topLevelWrapper._currentElement; + var element = wrapElement.props; + topLevelWrapper._pendingElement = ReactElement.cloneAndReplaceProps(wrapElement, ReactElement.cloneAndReplaceProps(element, props)); + + enqueueUpdate(topLevelWrapper); + }, + + enqueueElementInternal: function (internalInstance, newElement) { + internalInstance._pendingElement = newElement; + enqueueUpdate(internalInstance); + } + +}; + +module.exports = ReactUpdateQueue; +},{"161":161,"173":173,"24":24,"39":39,"57":57,"68":68,"96":96}],96:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactUpdates + */ + +'use strict'; + +var CallbackQueue = _dereq_(6); +var PooledClass = _dereq_(25); +var ReactPerf = _dereq_(78); +var ReactReconciler = _dereq_(84); +var Transaction = _dereq_(113); + +var assign = _dereq_(24); +var invariant = _dereq_(161); + +var dirtyComponents = []; +var asapCallbackQueue = CallbackQueue.getPooled(); +var asapEnqueued = false; + +var batchingStrategy = null; + +function ensureInjected() { + !(ReactUpdates.ReactReconcileTransaction && batchingStrategy) ? "development" !== 'production' ? invariant(false, 'ReactUpdates: must inject a reconcile transaction class and batching ' + 'strategy') : invariant(false) : undefined; +} + +var NESTED_UPDATES = { + initialize: function () { + this.dirtyComponentsLength = dirtyComponents.length; + }, + close: function () { + if (this.dirtyComponentsLength !== dirtyComponents.length) { + // Additional updates were enqueued by componentDidUpdate handlers or + // similar; before our own UPDATE_QUEUEING wrapper closes, we want to run + // these new updates so that if A's componentDidUpdate calls setState on + // B, B will update before the callback A's updater provided when calling + // setState. + dirtyComponents.splice(0, this.dirtyComponentsLength); + flushBatchedUpdates(); + } else { + dirtyComponents.length = 0; + } + } +}; + +var UPDATE_QUEUEING = { + initialize: function () { + this.callbackQueue.reset(); + }, + close: function () { + this.callbackQueue.notifyAll(); + } +}; + +var TRANSACTION_WRAPPERS = [NESTED_UPDATES, UPDATE_QUEUEING]; + +function ReactUpdatesFlushTransaction() { + this.reinitializeTransaction(); + this.dirtyComponentsLength = null; + this.callbackQueue = CallbackQueue.getPooled(); + this.reconcileTransaction = ReactUpdates.ReactReconcileTransaction.getPooled( /* forceHTML */false); +} + +assign(ReactUpdatesFlushTransaction.prototype, Transaction.Mixin, { + getTransactionWrappers: function () { + return TRANSACTION_WRAPPERS; + }, + + destructor: function () { + this.dirtyComponentsLength = null; + CallbackQueue.release(this.callbackQueue); + this.callbackQueue = null; + ReactUpdates.ReactReconcileTransaction.release(this.reconcileTransaction); + this.reconcileTransaction = null; + }, + + perform: function (method, scope, a) { + // Essentially calls `this.reconcileTransaction.perform(method, scope, a)` + // with this transaction's wrappers around it. + return Transaction.Mixin.perform.call(this, this.reconcileTransaction.perform, this.reconcileTransaction, method, scope, a); + } +}); + +PooledClass.addPoolingTo(ReactUpdatesFlushTransaction); + +function batchedUpdates(callback, a, b, c, d, e) { + ensureInjected(); + batchingStrategy.batchedUpdates(callback, a, b, c, d, e); +} + +/** + * Array comparator for ReactComponents by mount ordering. + * + * @param {ReactComponent} c1 first component you're comparing + * @param {ReactComponent} c2 second component you're comparing + * @return {number} Return value usable by Array.prototype.sort(). + */ +function mountOrderComparator(c1, c2) { + return c1._mountOrder - c2._mountOrder; +} + +function runBatchedUpdates(transaction) { + var len = transaction.dirtyComponentsLength; + !(len === dirtyComponents.length) ? "development" !== 'production' ? invariant(false, 'Expected flush transaction\'s stored dirty-components length (%s) to ' + 'match dirty-components array length (%s).', len, dirtyComponents.length) : invariant(false) : undefined; + + // Since reconciling a component higher in the owner hierarchy usually (not + // always -- see shouldComponentUpdate()) will reconcile children, reconcile + // them before their children by sorting the array. + dirtyComponents.sort(mountOrderComparator); + + for (var i = 0; i < len; i++) { + // If a component is unmounted before pending changes apply, it will still + // be here, but we assume that it has cleared its _pendingCallbacks and + // that performUpdateIfNecessary is a noop. + var component = dirtyComponents[i]; + + // If performUpdateIfNecessary happens to enqueue any new updates, we + // shouldn't execute the callbacks until the next render happens, so + // stash the callbacks first + var callbacks = component._pendingCallbacks; + component._pendingCallbacks = null; + + ReactReconciler.performUpdateIfNecessary(component, transaction.reconcileTransaction); + + if (callbacks) { + for (var j = 0; j < callbacks.length; j++) { + transaction.callbackQueue.enqueue(callbacks[j], component.getPublicInstance()); + } + } + } +} + +var flushBatchedUpdates = function () { + // ReactUpdatesFlushTransaction's wrappers will clear the dirtyComponents + // array and perform any updates enqueued by mount-ready handlers (i.e., + // componentDidUpdate) but we need to check here too in order to catch + // updates enqueued by setState callbacks and asap calls. + while (dirtyComponents.length || asapEnqueued) { + if (dirtyComponents.length) { + var transaction = ReactUpdatesFlushTransaction.getPooled(); + transaction.perform(runBatchedUpdates, null, transaction); + ReactUpdatesFlushTransaction.release(transaction); + } + + if (asapEnqueued) { + asapEnqueued = false; + var queue = asapCallbackQueue; + asapCallbackQueue = CallbackQueue.getPooled(); + queue.notifyAll(); + CallbackQueue.release(queue); + } + } +}; +flushBatchedUpdates = ReactPerf.measure('ReactUpdates', 'flushBatchedUpdates', flushBatchedUpdates); + +/** + * Mark a component as needing a rerender, adding an optional callback to a + * list of functions which will be executed once the rerender occurs. + */ +function enqueueUpdate(component) { + ensureInjected(); + + // Various parts of our code (such as ReactCompositeComponent's + // _renderValidatedComponent) assume that calls to render aren't nested; + // verify that that's the case. (This is called by each top-level update + // function, like setProps, setState, forceUpdate, etc.; creation and + // destruction of top-level components is guarded in ReactMount.) + + if (!batchingStrategy.isBatchingUpdates) { + batchingStrategy.batchedUpdates(enqueueUpdate, component); + return; + } + + dirtyComponents.push(component); +} + +/** + * Enqueue a callback to be run at the end of the current batching cycle. Throws + * if no updates are currently being performed. + */ +function asap(callback, context) { + !batchingStrategy.isBatchingUpdates ? "development" !== 'production' ? invariant(false, 'ReactUpdates.asap: Can\'t enqueue an asap callback in a context where' + 'updates are not being batched.') : invariant(false) : undefined; + asapCallbackQueue.enqueue(callback, context); + asapEnqueued = true; +} + +var ReactUpdatesInjection = { + injectReconcileTransaction: function (ReconcileTransaction) { + !ReconcileTransaction ? "development" !== 'production' ? invariant(false, 'ReactUpdates: must provide a reconcile transaction class') : invariant(false) : undefined; + ReactUpdates.ReactReconcileTransaction = ReconcileTransaction; + }, + + injectBatchingStrategy: function (_batchingStrategy) { + !_batchingStrategy ? "development" !== 'production' ? invariant(false, 'ReactUpdates: must provide a batching strategy') : invariant(false) : undefined; + !(typeof _batchingStrategy.batchedUpdates === 'function') ? "development" !== 'production' ? invariant(false, 'ReactUpdates: must provide a batchedUpdates() function') : invariant(false) : undefined; + !(typeof _batchingStrategy.isBatchingUpdates === 'boolean') ? "development" !== 'production' ? invariant(false, 'ReactUpdates: must provide an isBatchingUpdates boolean attribute') : invariant(false) : undefined; + batchingStrategy = _batchingStrategy; + } +}; + +var ReactUpdates = { + /** + * React references `ReactReconcileTransaction` using this property in order + * to allow dependency injection. + * + * @internal + */ + ReactReconcileTransaction: null, + + batchedUpdates: batchedUpdates, + enqueueUpdate: enqueueUpdate, + flushBatchedUpdates: flushBatchedUpdates, + injection: ReactUpdatesInjection, + asap: asap +}; + +module.exports = ReactUpdates; +},{"113":113,"161":161,"24":24,"25":25,"6":6,"78":78,"84":84}],97:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactVersion + */ + +'use strict'; + +module.exports = '0.14.6'; +},{}],98:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule SVGDOMPropertyConfig + */ + +'use strict'; + +var DOMProperty = _dereq_(10); + +var MUST_USE_ATTRIBUTE = DOMProperty.injection.MUST_USE_ATTRIBUTE; + +var NS = { + xlink: 'http://www.w3.org/1999/xlink', + xml: 'http://www.w3.org/XML/1998/namespace' +}; + +var SVGDOMPropertyConfig = { + Properties: { + clipPath: MUST_USE_ATTRIBUTE, + cx: MUST_USE_ATTRIBUTE, + cy: MUST_USE_ATTRIBUTE, + d: MUST_USE_ATTRIBUTE, + dx: MUST_USE_ATTRIBUTE, + dy: MUST_USE_ATTRIBUTE, + fill: MUST_USE_ATTRIBUTE, + fillOpacity: MUST_USE_ATTRIBUTE, + fontFamily: MUST_USE_ATTRIBUTE, + fontSize: MUST_USE_ATTRIBUTE, + fx: MUST_USE_ATTRIBUTE, + fy: MUST_USE_ATTRIBUTE, + gradientTransform: MUST_USE_ATTRIBUTE, + gradientUnits: MUST_USE_ATTRIBUTE, + markerEnd: MUST_USE_ATTRIBUTE, + markerMid: MUST_USE_ATTRIBUTE, + markerStart: MUST_USE_ATTRIBUTE, + offset: MUST_USE_ATTRIBUTE, + opacity: MUST_USE_ATTRIBUTE, + patternContentUnits: MUST_USE_ATTRIBUTE, + patternUnits: MUST_USE_ATTRIBUTE, + points: MUST_USE_ATTRIBUTE, + preserveAspectRatio: MUST_USE_ATTRIBUTE, + r: MUST_USE_ATTRIBUTE, + rx: MUST_USE_ATTRIBUTE, + ry: MUST_USE_ATTRIBUTE, + spreadMethod: MUST_USE_ATTRIBUTE, + stopColor: MUST_USE_ATTRIBUTE, + stopOpacity: MUST_USE_ATTRIBUTE, + stroke: MUST_USE_ATTRIBUTE, + strokeDasharray: MUST_USE_ATTRIBUTE, + strokeLinecap: MUST_USE_ATTRIBUTE, + strokeOpacity: MUST_USE_ATTRIBUTE, + strokeWidth: MUST_USE_ATTRIBUTE, + textAnchor: MUST_USE_ATTRIBUTE, + transform: MUST_USE_ATTRIBUTE, + version: MUST_USE_ATTRIBUTE, + viewBox: MUST_USE_ATTRIBUTE, + x1: MUST_USE_ATTRIBUTE, + x2: MUST_USE_ATTRIBUTE, + x: MUST_USE_ATTRIBUTE, + xlinkActuate: MUST_USE_ATTRIBUTE, + xlinkArcrole: MUST_USE_ATTRIBUTE, + xlinkHref: MUST_USE_ATTRIBUTE, + xlinkRole: MUST_USE_ATTRIBUTE, + xlinkShow: MUST_USE_ATTRIBUTE, + xlinkTitle: MUST_USE_ATTRIBUTE, + xlinkType: MUST_USE_ATTRIBUTE, + xmlBase: MUST_USE_ATTRIBUTE, + xmlLang: MUST_USE_ATTRIBUTE, + xmlSpace: MUST_USE_ATTRIBUTE, + y1: MUST_USE_ATTRIBUTE, + y2: MUST_USE_ATTRIBUTE, + y: MUST_USE_ATTRIBUTE + }, + DOMAttributeNamespaces: { + xlinkActuate: NS.xlink, + xlinkArcrole: NS.xlink, + xlinkHref: NS.xlink, + xlinkRole: NS.xlink, + xlinkShow: NS.xlink, + xlinkTitle: NS.xlink, + xlinkType: NS.xlink, + xmlBase: NS.xml, + xmlLang: NS.xml, + xmlSpace: NS.xml + }, + DOMAttributeNames: { + clipPath: 'clip-path', + fillOpacity: 'fill-opacity', + fontFamily: 'font-family', + fontSize: 'font-size', + gradientTransform: 'gradientTransform', + gradientUnits: 'gradientUnits', + markerEnd: 'marker-end', + markerMid: 'marker-mid', + markerStart: 'marker-start', + patternContentUnits: 'patternContentUnits', + patternUnits: 'patternUnits', + preserveAspectRatio: 'preserveAspectRatio', + spreadMethod: 'spreadMethod', + stopColor: 'stop-color', + stopOpacity: 'stop-opacity', + strokeDasharray: 'stroke-dasharray', + strokeLinecap: 'stroke-linecap', + strokeOpacity: 'stroke-opacity', + strokeWidth: 'stroke-width', + textAnchor: 'text-anchor', + viewBox: 'viewBox', + xlinkActuate: 'xlink:actuate', + xlinkArcrole: 'xlink:arcrole', + xlinkHref: 'xlink:href', + xlinkRole: 'xlink:role', + xlinkShow: 'xlink:show', + xlinkTitle: 'xlink:title', + xlinkType: 'xlink:type', + xmlBase: 'xml:base', + xmlLang: 'xml:lang', + xmlSpace: 'xml:space' + } +}; + +module.exports = SVGDOMPropertyConfig; +},{"10":10}],99:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule SelectEventPlugin + */ + +'use strict'; + +var EventConstants = _dereq_(15); +var EventPropagators = _dereq_(19); +var ExecutionEnvironment = _dereq_(147); +var ReactInputSelection = _dereq_(66); +var SyntheticEvent = _dereq_(105); + +var getActiveElement = _dereq_(156); +var isTextInputElement = _dereq_(134); +var keyOf = _dereq_(166); +var shallowEqual = _dereq_(171); + +var topLevelTypes = EventConstants.topLevelTypes; + +var skipSelectionChangeEvent = ExecutionEnvironment.canUseDOM && 'documentMode' in document && document.documentMode <= 11; + +var eventTypes = { + select: { + phasedRegistrationNames: { + bubbled: keyOf({ onSelect: null }), + captured: keyOf({ onSelectCapture: null }) + }, + dependencies: [topLevelTypes.topBlur, topLevelTypes.topContextMenu, topLevelTypes.topFocus, topLevelTypes.topKeyDown, topLevelTypes.topMouseDown, topLevelTypes.topMouseUp, topLevelTypes.topSelectionChange] + } +}; + +var activeElement = null; +var activeElementID = null; +var lastSelection = null; +var mouseDown = false; + +// Track whether a listener exists for this plugin. If none exist, we do +// not extract events. +var hasListener = false; +var ON_SELECT_KEY = keyOf({ onSelect: null }); + +/** + * Get an object which is a unique representation of the current selection. + * + * The return value will not be consistent across nodes or browsers, but + * two identical selections on the same node will return identical objects. + * + * @param {DOMElement} node + * @return {object} + */ +function getSelection(node) { + if ('selectionStart' in node && ReactInputSelection.hasSelectionCapabilities(node)) { + return { + start: node.selectionStart, + end: node.selectionEnd + }; + } else if (window.getSelection) { + var selection = window.getSelection(); + return { + anchorNode: selection.anchorNode, + anchorOffset: selection.anchorOffset, + focusNode: selection.focusNode, + focusOffset: selection.focusOffset + }; + } else if (document.selection) { + var range = document.selection.createRange(); + return { + parentElement: range.parentElement(), + text: range.text, + top: range.boundingTop, + left: range.boundingLeft + }; + } +} + +/** + * Poll selection to see whether it's changed. + * + * @param {object} nativeEvent + * @return {?SyntheticEvent} + */ +function constructSelectEvent(nativeEvent, nativeEventTarget) { + // Ensure we have the right element, and that the user is not dragging a + // selection (this matches native `select` event behavior). In HTML5, select + // fires only on input and textarea thus if there's no focused element we + // won't dispatch. + if (mouseDown || activeElement == null || activeElement !== getActiveElement()) { + return null; + } + + // Only fire when selection has actually changed. + var currentSelection = getSelection(activeElement); + if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) { + lastSelection = currentSelection; + + var syntheticEvent = SyntheticEvent.getPooled(eventTypes.select, activeElementID, nativeEvent, nativeEventTarget); + + syntheticEvent.type = 'select'; + syntheticEvent.target = activeElement; + + EventPropagators.accumulateTwoPhaseDispatches(syntheticEvent); + + return syntheticEvent; + } + + return null; +} + +/** + * This plugin creates an `onSelect` event that normalizes select events + * across form elements. + * + * Supported elements are: + * - input (see `isTextInputElement`) + * - textarea + * - contentEditable + * + * This differs from native browser implementations in the following ways: + * - Fires on contentEditable fields as well as inputs. + * - Fires for collapsed selection. + * - Fires after user input. + */ +var SelectEventPlugin = { + + eventTypes: eventTypes, + + /** + * @param {string} topLevelType Record from `EventConstants`. + * @param {DOMEventTarget} topLevelTarget The listening component root node. + * @param {string} topLevelTargetID ID of `topLevelTarget`. + * @param {object} nativeEvent Native browser event. + * @return {*} An accumulation of synthetic events. + * @see {EventPluginHub.extractEvents} + */ + extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) { + if (!hasListener) { + return null; + } + + switch (topLevelType) { + // Track the input node that has focus. + case topLevelTypes.topFocus: + if (isTextInputElement(topLevelTarget) || topLevelTarget.contentEditable === 'true') { + activeElement = topLevelTarget; + activeElementID = topLevelTargetID; + lastSelection = null; + } + break; + case topLevelTypes.topBlur: + activeElement = null; + activeElementID = null; + lastSelection = null; + break; + + // Don't fire the event while the user is dragging. This matches the + // semantics of the native select event. + case topLevelTypes.topMouseDown: + mouseDown = true; + break; + case topLevelTypes.topContextMenu: + case topLevelTypes.topMouseUp: + mouseDown = false; + return constructSelectEvent(nativeEvent, nativeEventTarget); + + // Chrome and IE fire non-standard event when selection is changed (and + // sometimes when it hasn't). IE's event fires out of order with respect + // to key and input events on deletion, so we discard it. + // + // Firefox doesn't support selectionchange, so check selection status + // after each key entry. The selection changes after keydown and before + // keyup, but we check on keydown as well in the case of holding down a + // key, when multiple keydown events are fired but only one keyup is. + // This is also our approach for IE handling, for the reason above. + case topLevelTypes.topSelectionChange: + if (skipSelectionChangeEvent) { + break; + } + // falls through + case topLevelTypes.topKeyDown: + case topLevelTypes.topKeyUp: + return constructSelectEvent(nativeEvent, nativeEventTarget); + } + + return null; + }, + + didPutListener: function (id, registrationName, listener) { + if (registrationName === ON_SELECT_KEY) { + hasListener = true; + } + } +}; + +module.exports = SelectEventPlugin; +},{"105":105,"134":134,"147":147,"15":15,"156":156,"166":166,"171":171,"19":19,"66":66}],100:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ServerReactRootIndex + * @typechecks + */ + +'use strict'; + +/** + * Size of the reactRoot ID space. We generate random numbers for React root + * IDs and if there's a collision the events and DOM update system will + * get confused. In the future we need a way to generate GUIDs but for + * now this will work on a smaller scale. + */ +var GLOBAL_MOUNT_POINT_MAX = Math.pow(2, 53); + +var ServerReactRootIndex = { + createReactRootIndex: function () { + return Math.ceil(Math.random() * GLOBAL_MOUNT_POINT_MAX); + } +}; + +module.exports = ServerReactRootIndex; +},{}],101:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule SimpleEventPlugin + */ + +'use strict'; + +var EventConstants = _dereq_(15); +var EventListener = _dereq_(146); +var EventPropagators = _dereq_(19); +var ReactMount = _dereq_(72); +var SyntheticClipboardEvent = _dereq_(102); +var SyntheticEvent = _dereq_(105); +var SyntheticFocusEvent = _dereq_(106); +var SyntheticKeyboardEvent = _dereq_(108); +var SyntheticMouseEvent = _dereq_(109); +var SyntheticDragEvent = _dereq_(104); +var SyntheticTouchEvent = _dereq_(110); +var SyntheticUIEvent = _dereq_(111); +var SyntheticWheelEvent = _dereq_(112); + +var emptyFunction = _dereq_(153); +var getEventCharCode = _dereq_(125); +var invariant = _dereq_(161); +var keyOf = _dereq_(166); + +var topLevelTypes = EventConstants.topLevelTypes; + +var eventTypes = { + abort: { + phasedRegistrationNames: { + bubbled: keyOf({ onAbort: true }), + captured: keyOf({ onAbortCapture: true }) + } + }, + blur: { + phasedRegistrationNames: { + bubbled: keyOf({ onBlur: true }), + captured: keyOf({ onBlurCapture: true }) + } + }, + canPlay: { + phasedRegistrationNames: { + bubbled: keyOf({ onCanPlay: true }), + captured: keyOf({ onCanPlayCapture: true }) + } + }, + canPlayThrough: { + phasedRegistrationNames: { + bubbled: keyOf({ onCanPlayThrough: true }), + captured: keyOf({ onCanPlayThroughCapture: true }) + } + }, + click: { + phasedRegistrationNames: { + bubbled: keyOf({ onClick: true }), + captured: keyOf({ onClickCapture: true }) + } + }, + contextMenu: { + phasedRegistrationNames: { + bubbled: keyOf({ onContextMenu: true }), + captured: keyOf({ onContextMenuCapture: true }) + } + }, + copy: { + phasedRegistrationNames: { + bubbled: keyOf({ onCopy: true }), + captured: keyOf({ onCopyCapture: true }) + } + }, + cut: { + phasedRegistrationNames: { + bubbled: keyOf({ onCut: true }), + captured: keyOf({ onCutCapture: true }) + } + }, + doubleClick: { + phasedRegistrationNames: { + bubbled: keyOf({ onDoubleClick: true }), + captured: keyOf({ onDoubleClickCapture: true }) + } + }, + drag: { + phasedRegistrationNames: { + bubbled: keyOf({ onDrag: true }), + captured: keyOf({ onDragCapture: true }) + } + }, + dragEnd: { + phasedRegistrationNames: { + bubbled: keyOf({ onDragEnd: true }), + captured: keyOf({ onDragEndCapture: true }) + } + }, + dragEnter: { + phasedRegistrationNames: { + bubbled: keyOf({ onDragEnter: true }), + captured: keyOf({ onDragEnterCapture: true }) + } + }, + dragExit: { + phasedRegistrationNames: { + bubbled: keyOf({ onDragExit: true }), + captured: keyOf({ onDragExitCapture: true }) + } + }, + dragLeave: { + phasedRegistrationNames: { + bubbled: keyOf({ onDragLeave: true }), + captured: keyOf({ onDragLeaveCapture: true }) + } + }, + dragOver: { + phasedRegistrationNames: { + bubbled: keyOf({ onDragOver: true }), + captured: keyOf({ onDragOverCapture: true }) + } + }, + dragStart: { + phasedRegistrationNames: { + bubbled: keyOf({ onDragStart: true }), + captured: keyOf({ onDragStartCapture: true }) + } + }, + drop: { + phasedRegistrationNames: { + bubbled: keyOf({ onDrop: true }), + captured: keyOf({ onDropCapture: true }) + } + }, + durationChange: { + phasedRegistrationNames: { + bubbled: keyOf({ onDurationChange: true }), + captured: keyOf({ onDurationChangeCapture: true }) + } + }, + emptied: { + phasedRegistrationNames: { + bubbled: keyOf({ onEmptied: true }), + captured: keyOf({ onEmptiedCapture: true }) + } + }, + encrypted: { + phasedRegistrationNames: { + bubbled: keyOf({ onEncrypted: true }), + captured: keyOf({ onEncryptedCapture: true }) + } + }, + ended: { + phasedRegistrationNames: { + bubbled: keyOf({ onEnded: true }), + captured: keyOf({ onEndedCapture: true }) + } + }, + error: { + phasedRegistrationNames: { + bubbled: keyOf({ onError: true }), + captured: keyOf({ onErrorCapture: true }) + } + }, + focus: { + phasedRegistrationNames: { + bubbled: keyOf({ onFocus: true }), + captured: keyOf({ onFocusCapture: true }) + } + }, + input: { + phasedRegistrationNames: { + bubbled: keyOf({ onInput: true }), + captured: keyOf({ onInputCapture: true }) + } + }, + keyDown: { + phasedRegistrationNames: { + bubbled: keyOf({ onKeyDown: true }), + captured: keyOf({ onKeyDownCapture: true }) + } + }, + keyPress: { + phasedRegistrationNames: { + bubbled: keyOf({ onKeyPress: true }), + captured: keyOf({ onKeyPressCapture: true }) + } + }, + keyUp: { + phasedRegistrationNames: { + bubbled: keyOf({ onKeyUp: true }), + captured: keyOf({ onKeyUpCapture: true }) + } + }, + load: { + phasedRegistrationNames: { + bubbled: keyOf({ onLoad: true }), + captured: keyOf({ onLoadCapture: true }) + } + }, + loadedData: { + phasedRegistrationNames: { + bubbled: keyOf({ onLoadedData: true }), + captured: keyOf({ onLoadedDataCapture: true }) + } + }, + loadedMetadata: { + phasedRegistrationNames: { + bubbled: keyOf({ onLoadedMetadata: true }), + captured: keyOf({ onLoadedMetadataCapture: true }) + } + }, + loadStart: { + phasedRegistrationNames: { + bubbled: keyOf({ onLoadStart: true }), + captured: keyOf({ onLoadStartCapture: true }) + } + }, + // Note: We do not allow listening to mouseOver events. Instead, use the + // onMouseEnter/onMouseLeave created by `EnterLeaveEventPlugin`. + mouseDown: { + phasedRegistrationNames: { + bubbled: keyOf({ onMouseDown: true }), + captured: keyOf({ onMouseDownCapture: true }) + } + }, + mouseMove: { + phasedRegistrationNames: { + bubbled: keyOf({ onMouseMove: true }), + captured: keyOf({ onMouseMoveCapture: true }) + } + }, + mouseOut: { + phasedRegistrationNames: { + bubbled: keyOf({ onMouseOut: true }), + captured: keyOf({ onMouseOutCapture: true }) + } + }, + mouseOver: { + phasedRegistrationNames: { + bubbled: keyOf({ onMouseOver: true }), + captured: keyOf({ onMouseOverCapture: true }) + } + }, + mouseUp: { + phasedRegistrationNames: { + bubbled: keyOf({ onMouseUp: true }), + captured: keyOf({ onMouseUpCapture: true }) + } + }, + paste: { + phasedRegistrationNames: { + bubbled: keyOf({ onPaste: true }), + captured: keyOf({ onPasteCapture: true }) + } + }, + pause: { + phasedRegistrationNames: { + bubbled: keyOf({ onPause: true }), + captured: keyOf({ onPauseCapture: true }) + } + }, + play: { + phasedRegistrationNames: { + bubbled: keyOf({ onPlay: true }), + captured: keyOf({ onPlayCapture: true }) + } + }, + playing: { + phasedRegistrationNames: { + bubbled: keyOf({ onPlaying: true }), + captured: keyOf({ onPlayingCapture: true }) + } + }, + progress: { + phasedRegistrationNames: { + bubbled: keyOf({ onProgress: true }), + captured: keyOf({ onProgressCapture: true }) + } + }, + rateChange: { + phasedRegistrationNames: { + bubbled: keyOf({ onRateChange: true }), + captured: keyOf({ onRateChangeCapture: true }) + } + }, + reset: { + phasedRegistrationNames: { + bubbled: keyOf({ onReset: true }), + captured: keyOf({ onResetCapture: true }) + } + }, + scroll: { + phasedRegistrationNames: { + bubbled: keyOf({ onScroll: true }), + captured: keyOf({ onScrollCapture: true }) + } + }, + seeked: { + phasedRegistrationNames: { + bubbled: keyOf({ onSeeked: true }), + captured: keyOf({ onSeekedCapture: true }) + } + }, + seeking: { + phasedRegistrationNames: { + bubbled: keyOf({ onSeeking: true }), + captured: keyOf({ onSeekingCapture: true }) + } + }, + stalled: { + phasedRegistrationNames: { + bubbled: keyOf({ onStalled: true }), + captured: keyOf({ onStalledCapture: true }) + } + }, + submit: { + phasedRegistrationNames: { + bubbled: keyOf({ onSubmit: true }), + captured: keyOf({ onSubmitCapture: true }) + } + }, + suspend: { + phasedRegistrationNames: { + bubbled: keyOf({ onSuspend: true }), + captured: keyOf({ onSuspendCapture: true }) + } + }, + timeUpdate: { + phasedRegistrationNames: { + bubbled: keyOf({ onTimeUpdate: true }), + captured: keyOf({ onTimeUpdateCapture: true }) + } + }, + touchCancel: { + phasedRegistrationNames: { + bubbled: keyOf({ onTouchCancel: true }), + captured: keyOf({ onTouchCancelCapture: true }) + } + }, + touchEnd: { + phasedRegistrationNames: { + bubbled: keyOf({ onTouchEnd: true }), + captured: keyOf({ onTouchEndCapture: true }) + } + }, + touchMove: { + phasedRegistrationNames: { + bubbled: keyOf({ onTouchMove: true }), + captured: keyOf({ onTouchMoveCapture: true }) + } + }, + touchStart: { + phasedRegistrationNames: { + bubbled: keyOf({ onTouchStart: true }), + captured: keyOf({ onTouchStartCapture: true }) + } + }, + volumeChange: { + phasedRegistrationNames: { + bubbled: keyOf({ onVolumeChange: true }), + captured: keyOf({ onVolumeChangeCapture: true }) + } + }, + waiting: { + phasedRegistrationNames: { + bubbled: keyOf({ onWaiting: true }), + captured: keyOf({ onWaitingCapture: true }) + } + }, + wheel: { + phasedRegistrationNames: { + bubbled: keyOf({ onWheel: true }), + captured: keyOf({ onWheelCapture: true }) + } + } +}; + +var topLevelEventsToDispatchConfig = { + topAbort: eventTypes.abort, + topBlur: eventTypes.blur, + topCanPlay: eventTypes.canPlay, + topCanPlayThrough: eventTypes.canPlayThrough, + topClick: eventTypes.click, + topContextMenu: eventTypes.contextMenu, + topCopy: eventTypes.copy, + topCut: eventTypes.cut, + topDoubleClick: eventTypes.doubleClick, + topDrag: eventTypes.drag, + topDragEnd: eventTypes.dragEnd, + topDragEnter: eventTypes.dragEnter, + topDragExit: eventTypes.dragExit, + topDragLeave: eventTypes.dragLeave, + topDragOver: eventTypes.dragOver, + topDragStart: eventTypes.dragStart, + topDrop: eventTypes.drop, + topDurationChange: eventTypes.durationChange, + topEmptied: eventTypes.emptied, + topEncrypted: eventTypes.encrypted, + topEnded: eventTypes.ended, + topError: eventTypes.error, + topFocus: eventTypes.focus, + topInput: eventTypes.input, + topKeyDown: eventTypes.keyDown, + topKeyPress: eventTypes.keyPress, + topKeyUp: eventTypes.keyUp, + topLoad: eventTypes.load, + topLoadedData: eventTypes.loadedData, + topLoadedMetadata: eventTypes.loadedMetadata, + topLoadStart: eventTypes.loadStart, + topMouseDown: eventTypes.mouseDown, + topMouseMove: eventTypes.mouseMove, + topMouseOut: eventTypes.mouseOut, + topMouseOver: eventTypes.mouseOver, + topMouseUp: eventTypes.mouseUp, + topPaste: eventTypes.paste, + topPause: eventTypes.pause, + topPlay: eventTypes.play, + topPlaying: eventTypes.playing, + topProgress: eventTypes.progress, + topRateChange: eventTypes.rateChange, + topReset: eventTypes.reset, + topScroll: eventTypes.scroll, + topSeeked: eventTypes.seeked, + topSeeking: eventTypes.seeking, + topStalled: eventTypes.stalled, + topSubmit: eventTypes.submit, + topSuspend: eventTypes.suspend, + topTimeUpdate: eventTypes.timeUpdate, + topTouchCancel: eventTypes.touchCancel, + topTouchEnd: eventTypes.touchEnd, + topTouchMove: eventTypes.touchMove, + topTouchStart: eventTypes.touchStart, + topVolumeChange: eventTypes.volumeChange, + topWaiting: eventTypes.waiting, + topWheel: eventTypes.wheel +}; + +for (var type in topLevelEventsToDispatchConfig) { + topLevelEventsToDispatchConfig[type].dependencies = [type]; +} + +var ON_CLICK_KEY = keyOf({ onClick: null }); +var onClickListeners = {}; + +var SimpleEventPlugin = { + + eventTypes: eventTypes, + + /** + * @param {string} topLevelType Record from `EventConstants`. + * @param {DOMEventTarget} topLevelTarget The listening component root node. + * @param {string} topLevelTargetID ID of `topLevelTarget`. + * @param {object} nativeEvent Native browser event. + * @return {*} An accumulation of synthetic events. + * @see {EventPluginHub.extractEvents} + */ + extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) { + var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType]; + if (!dispatchConfig) { + return null; + } + var EventConstructor; + switch (topLevelType) { + case topLevelTypes.topAbort: + case topLevelTypes.topCanPlay: + case topLevelTypes.topCanPlayThrough: + case topLevelTypes.topDurationChange: + case topLevelTypes.topEmptied: + case topLevelTypes.topEncrypted: + case topLevelTypes.topEnded: + case topLevelTypes.topError: + case topLevelTypes.topInput: + case topLevelTypes.topLoad: + case topLevelTypes.topLoadedData: + case topLevelTypes.topLoadedMetadata: + case topLevelTypes.topLoadStart: + case topLevelTypes.topPause: + case topLevelTypes.topPlay: + case topLevelTypes.topPlaying: + case topLevelTypes.topProgress: + case topLevelTypes.topRateChange: + case topLevelTypes.topReset: + case topLevelTypes.topSeeked: + case topLevelTypes.topSeeking: + case topLevelTypes.topStalled: + case topLevelTypes.topSubmit: + case topLevelTypes.topSuspend: + case topLevelTypes.topTimeUpdate: + case topLevelTypes.topVolumeChange: + case topLevelTypes.topWaiting: + // HTML Events + // @see http://www.w3.org/TR/html5/index.html#events-0 + EventConstructor = SyntheticEvent; + break; + case topLevelTypes.topKeyPress: + // FireFox creates a keypress event for function keys too. This removes + // the unwanted keypress events. Enter is however both printable and + // non-printable. One would expect Tab to be as well (but it isn't). + if (getEventCharCode(nativeEvent) === 0) { + return null; + } + /* falls through */ + case topLevelTypes.topKeyDown: + case topLevelTypes.topKeyUp: + EventConstructor = SyntheticKeyboardEvent; + break; + case topLevelTypes.topBlur: + case topLevelTypes.topFocus: + EventConstructor = SyntheticFocusEvent; + break; + case topLevelTypes.topClick: + // Firefox creates a click event on right mouse clicks. This removes the + // unwanted click events. + if (nativeEvent.button === 2) { + return null; + } + /* falls through */ + case topLevelTypes.topContextMenu: + case topLevelTypes.topDoubleClick: + case topLevelTypes.topMouseDown: + case topLevelTypes.topMouseMove: + case topLevelTypes.topMouseOut: + case topLevelTypes.topMouseOver: + case topLevelTypes.topMouseUp: + EventConstructor = SyntheticMouseEvent; + break; + case topLevelTypes.topDrag: + case topLevelTypes.topDragEnd: + case topLevelTypes.topDragEnter: + case topLevelTypes.topDragExit: + case topLevelTypes.topDragLeave: + case topLevelTypes.topDragOver: + case topLevelTypes.topDragStart: + case topLevelTypes.topDrop: + EventConstructor = SyntheticDragEvent; + break; + case topLevelTypes.topTouchCancel: + case topLevelTypes.topTouchEnd: + case topLevelTypes.topTouchMove: + case topLevelTypes.topTouchStart: + EventConstructor = SyntheticTouchEvent; + break; + case topLevelTypes.topScroll: + EventConstructor = SyntheticUIEvent; + break; + case topLevelTypes.topWheel: + EventConstructor = SyntheticWheelEvent; + break; + case topLevelTypes.topCopy: + case topLevelTypes.topCut: + case topLevelTypes.topPaste: + EventConstructor = SyntheticClipboardEvent; + break; + } + !EventConstructor ? "development" !== 'production' ? invariant(false, 'SimpleEventPlugin: Unhandled event type, `%s`.', topLevelType) : invariant(false) : undefined; + var event = EventConstructor.getPooled(dispatchConfig, topLevelTargetID, nativeEvent, nativeEventTarget); + EventPropagators.accumulateTwoPhaseDispatches(event); + return event; + }, + + didPutListener: function (id, registrationName, listener) { + // Mobile Safari does not fire properly bubble click events on + // non-interactive elements, which means delegated click listeners do not + // fire. The workaround for this bug involves attaching an empty click + // listener on the target node. + if (registrationName === ON_CLICK_KEY) { + var node = ReactMount.getNode(id); + if (!onClickListeners[id]) { + onClickListeners[id] = EventListener.listen(node, 'click', emptyFunction); + } + } + }, + + willDeleteListener: function (id, registrationName) { + if (registrationName === ON_CLICK_KEY) { + onClickListeners[id].remove(); + delete onClickListeners[id]; + } + } + +}; + +module.exports = SimpleEventPlugin; +},{"102":102,"104":104,"105":105,"106":106,"108":108,"109":109,"110":110,"111":111,"112":112,"125":125,"146":146,"15":15,"153":153,"161":161,"166":166,"19":19,"72":72}],102:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule SyntheticClipboardEvent + * @typechecks static-only + */ + +'use strict'; + +var SyntheticEvent = _dereq_(105); + +/** + * @interface Event + * @see http://www.w3.org/TR/clipboard-apis/ + */ +var ClipboardEventInterface = { + clipboardData: function (event) { + return 'clipboardData' in event ? event.clipboardData : window.clipboardData; + } +}; + +/** + * @param {object} dispatchConfig Configuration used to dispatch this event. + * @param {string} dispatchMarker Marker identifying the event target. + * @param {object} nativeEvent Native browser event. + * @extends {SyntheticUIEvent} + */ +function SyntheticClipboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { + SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); +} + +SyntheticEvent.augmentClass(SyntheticClipboardEvent, ClipboardEventInterface); + +module.exports = SyntheticClipboardEvent; +},{"105":105}],103:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule SyntheticCompositionEvent + * @typechecks static-only + */ + +'use strict'; + +var SyntheticEvent = _dereq_(105); + +/** + * @interface Event + * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents + */ +var CompositionEventInterface = { + data: null +}; + +/** + * @param {object} dispatchConfig Configuration used to dispatch this event. + * @param {string} dispatchMarker Marker identifying the event target. + * @param {object} nativeEvent Native browser event. + * @extends {SyntheticUIEvent} + */ +function SyntheticCompositionEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { + SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); +} + +SyntheticEvent.augmentClass(SyntheticCompositionEvent, CompositionEventInterface); + +module.exports = SyntheticCompositionEvent; +},{"105":105}],104:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule SyntheticDragEvent + * @typechecks static-only + */ + +'use strict'; + +var SyntheticMouseEvent = _dereq_(109); + +/** + * @interface DragEvent + * @see http://www.w3.org/TR/DOM-Level-3-Events/ + */ +var DragEventInterface = { + dataTransfer: null +}; + +/** + * @param {object} dispatchConfig Configuration used to dispatch this event. + * @param {string} dispatchMarker Marker identifying the event target. + * @param {object} nativeEvent Native browser event. + * @extends {SyntheticUIEvent} + */ +function SyntheticDragEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { + SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); +} + +SyntheticMouseEvent.augmentClass(SyntheticDragEvent, DragEventInterface); + +module.exports = SyntheticDragEvent; +},{"109":109}],105:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule SyntheticEvent + * @typechecks static-only + */ + +'use strict'; + +var PooledClass = _dereq_(25); + +var assign = _dereq_(24); +var emptyFunction = _dereq_(153); +var warning = _dereq_(173); + +/** + * @interface Event + * @see http://www.w3.org/TR/DOM-Level-3-Events/ + */ +var EventInterface = { + type: null, + // currentTarget is set when dispatching; no use in copying it here + currentTarget: emptyFunction.thatReturnsNull, + eventPhase: null, + bubbles: null, + cancelable: null, + timeStamp: function (event) { + return event.timeStamp || Date.now(); + }, + defaultPrevented: null, + isTrusted: null +}; + +/** + * Synthetic events are dispatched by event plugins, typically in response to a + * top-level event delegation handler. + * + * These systems should generally use pooling to reduce the frequency of garbage + * collection. The system should check `isPersistent` to determine whether the + * event should be released into the pool after being dispatched. Users that + * need a persisted event should invoke `persist`. + * + * Synthetic events (and subclasses) implement the DOM Level 3 Events API by + * normalizing browser quirks. Subclasses do not necessarily have to implement a + * DOM interface; custom application-specific events can also subclass this. + * + * @param {object} dispatchConfig Configuration used to dispatch this event. + * @param {string} dispatchMarker Marker identifying the event target. + * @param {object} nativeEvent Native browser event. + */ +function SyntheticEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { + this.dispatchConfig = dispatchConfig; + this.dispatchMarker = dispatchMarker; + this.nativeEvent = nativeEvent; + this.target = nativeEventTarget; + this.currentTarget = nativeEventTarget; + + var Interface = this.constructor.Interface; + for (var propName in Interface) { + if (!Interface.hasOwnProperty(propName)) { + continue; + } + var normalize = Interface[propName]; + if (normalize) { + this[propName] = normalize(nativeEvent); + } else { + this[propName] = nativeEvent[propName]; + } + } + + var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false; + if (defaultPrevented) { + this.isDefaultPrevented = emptyFunction.thatReturnsTrue; + } else { + this.isDefaultPrevented = emptyFunction.thatReturnsFalse; + } + this.isPropagationStopped = emptyFunction.thatReturnsFalse; +} + +assign(SyntheticEvent.prototype, { + + preventDefault: function () { + this.defaultPrevented = true; + var event = this.nativeEvent; + if ("development" !== 'production') { + "development" !== 'production' ? warning(event, 'This synthetic event is reused for performance reasons. If you\'re ' + 'seeing this, you\'re calling `preventDefault` on a ' + 'released/nullified synthetic event. This is a no-op. See ' + 'https://fb.me/react-event-pooling for more information.') : undefined; + } + if (!event) { + return; + } + + if (event.preventDefault) { + event.preventDefault(); + } else { + event.returnValue = false; + } + this.isDefaultPrevented = emptyFunction.thatReturnsTrue; + }, + + stopPropagation: function () { + var event = this.nativeEvent; + if ("development" !== 'production') { + "development" !== 'production' ? warning(event, 'This synthetic event is reused for performance reasons. If you\'re ' + 'seeing this, you\'re calling `stopPropagation` on a ' + 'released/nullified synthetic event. This is a no-op. See ' + 'https://fb.me/react-event-pooling for more information.') : undefined; + } + if (!event) { + return; + } + + if (event.stopPropagation) { + event.stopPropagation(); + } else { + event.cancelBubble = true; + } + this.isPropagationStopped = emptyFunction.thatReturnsTrue; + }, + + /** + * We release all dispatched `SyntheticEvent`s after each event loop, adding + * them back into the pool. This allows a way to hold onto a reference that + * won't be added back into the pool. + */ + persist: function () { + this.isPersistent = emptyFunction.thatReturnsTrue; + }, + + /** + * Checks if this event should be released back into the pool. + * + * @return {boolean} True if this should not be released, false otherwise. + */ + isPersistent: emptyFunction.thatReturnsFalse, + + /** + * `PooledClass` looks for `destructor` on each instance it releases. + */ + destructor: function () { + var Interface = this.constructor.Interface; + for (var propName in Interface) { + this[propName] = null; + } + this.dispatchConfig = null; + this.dispatchMarker = null; + this.nativeEvent = null; + } + +}); + +SyntheticEvent.Interface = EventInterface; + +/** + * Helper to reduce boilerplate when creating subclasses. + * + * @param {function} Class + * @param {?object} Interface + */ +SyntheticEvent.augmentClass = function (Class, Interface) { + var Super = this; + + var prototype = Object.create(Super.prototype); + assign(prototype, Class.prototype); + Class.prototype = prototype; + Class.prototype.constructor = Class; + + Class.Interface = assign({}, Super.Interface, Interface); + Class.augmentClass = Super.augmentClass; + + PooledClass.addPoolingTo(Class, PooledClass.fourArgumentPooler); +}; + +PooledClass.addPoolingTo(SyntheticEvent, PooledClass.fourArgumentPooler); + +module.exports = SyntheticEvent; +},{"153":153,"173":173,"24":24,"25":25}],106:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule SyntheticFocusEvent + * @typechecks static-only + */ + +'use strict'; + +var SyntheticUIEvent = _dereq_(111); + +/** + * @interface FocusEvent + * @see http://www.w3.org/TR/DOM-Level-3-Events/ + */ +var FocusEventInterface = { + relatedTarget: null +}; + +/** + * @param {object} dispatchConfig Configuration used to dispatch this event. + * @param {string} dispatchMarker Marker identifying the event target. + * @param {object} nativeEvent Native browser event. + * @extends {SyntheticUIEvent} + */ +function SyntheticFocusEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { + SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); +} + +SyntheticUIEvent.augmentClass(SyntheticFocusEvent, FocusEventInterface); + +module.exports = SyntheticFocusEvent; +},{"111":111}],107:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule SyntheticInputEvent + * @typechecks static-only + */ + +'use strict'; + +var SyntheticEvent = _dereq_(105); + +/** + * @interface Event + * @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105 + * /#events-inputevents + */ +var InputEventInterface = { + data: null +}; + +/** + * @param {object} dispatchConfig Configuration used to dispatch this event. + * @param {string} dispatchMarker Marker identifying the event target. + * @param {object} nativeEvent Native browser event. + * @extends {SyntheticUIEvent} + */ +function SyntheticInputEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { + SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); +} + +SyntheticEvent.augmentClass(SyntheticInputEvent, InputEventInterface); + +module.exports = SyntheticInputEvent; +},{"105":105}],108:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule SyntheticKeyboardEvent + * @typechecks static-only + */ + +'use strict'; + +var SyntheticUIEvent = _dereq_(111); + +var getEventCharCode = _dereq_(125); +var getEventKey = _dereq_(126); +var getEventModifierState = _dereq_(127); + +/** + * @interface KeyboardEvent + * @see http://www.w3.org/TR/DOM-Level-3-Events/ + */ +var KeyboardEventInterface = { + key: getEventKey, + location: null, + ctrlKey: null, + shiftKey: null, + altKey: null, + metaKey: null, + repeat: null, + locale: null, + getModifierState: getEventModifierState, + // Legacy Interface + charCode: function (event) { + // `charCode` is the result of a KeyPress event and represents the value of + // the actual printable character. + + // KeyPress is deprecated, but its replacement is not yet final and not + // implemented in any major browser. Only KeyPress has charCode. + if (event.type === 'keypress') { + return getEventCharCode(event); + } + return 0; + }, + keyCode: function (event) { + // `keyCode` is the result of a KeyDown/Up event and represents the value of + // physical keyboard key. + + // The actual meaning of the value depends on the users' keyboard layout + // which cannot be detected. Assuming that it is a US keyboard layout + // provides a surprisingly accurate mapping for US and European users. + // Due to this, it is left to the user to implement at this time. + if (event.type === 'keydown' || event.type === 'keyup') { + return event.keyCode; + } + return 0; + }, + which: function (event) { + // `which` is an alias for either `keyCode` or `charCode` depending on the + // type of the event. + if (event.type === 'keypress') { + return getEventCharCode(event); + } + if (event.type === 'keydown' || event.type === 'keyup') { + return event.keyCode; + } + return 0; + } +}; + +/** + * @param {object} dispatchConfig Configuration used to dispatch this event. + * @param {string} dispatchMarker Marker identifying the event target. + * @param {object} nativeEvent Native browser event. + * @extends {SyntheticUIEvent} + */ +function SyntheticKeyboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { + SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); +} + +SyntheticUIEvent.augmentClass(SyntheticKeyboardEvent, KeyboardEventInterface); + +module.exports = SyntheticKeyboardEvent; +},{"111":111,"125":125,"126":126,"127":127}],109:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule SyntheticMouseEvent + * @typechecks static-only + */ + +'use strict'; + +var SyntheticUIEvent = _dereq_(111); +var ViewportMetrics = _dereq_(114); + +var getEventModifierState = _dereq_(127); + +/** + * @interface MouseEvent + * @see http://www.w3.org/TR/DOM-Level-3-Events/ + */ +var MouseEventInterface = { + screenX: null, + screenY: null, + clientX: null, + clientY: null, + ctrlKey: null, + shiftKey: null, + altKey: null, + metaKey: null, + getModifierState: getEventModifierState, + button: function (event) { + // Webkit, Firefox, IE9+ + // which: 1 2 3 + // button: 0 1 2 (standard) + var button = event.button; + if ('which' in event) { + return button; + } + // IE<9 + // which: undefined + // button: 0 0 0 + // button: 1 4 2 (onmouseup) + return button === 2 ? 2 : button === 4 ? 1 : 0; + }, + buttons: null, + relatedTarget: function (event) { + return event.relatedTarget || (event.fromElement === event.srcElement ? event.toElement : event.fromElement); + }, + // "Proprietary" Interface. + pageX: function (event) { + return 'pageX' in event ? event.pageX : event.clientX + ViewportMetrics.currentScrollLeft; + }, + pageY: function (event) { + return 'pageY' in event ? event.pageY : event.clientY + ViewportMetrics.currentScrollTop; + } +}; + +/** + * @param {object} dispatchConfig Configuration used to dispatch this event. + * @param {string} dispatchMarker Marker identifying the event target. + * @param {object} nativeEvent Native browser event. + * @extends {SyntheticUIEvent} + */ +function SyntheticMouseEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { + SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); +} + +SyntheticUIEvent.augmentClass(SyntheticMouseEvent, MouseEventInterface); + +module.exports = SyntheticMouseEvent; +},{"111":111,"114":114,"127":127}],110:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule SyntheticTouchEvent + * @typechecks static-only + */ + +'use strict'; + +var SyntheticUIEvent = _dereq_(111); + +var getEventModifierState = _dereq_(127); + +/** + * @interface TouchEvent + * @see http://www.w3.org/TR/touch-events/ + */ +var TouchEventInterface = { + touches: null, + targetTouches: null, + changedTouches: null, + altKey: null, + metaKey: null, + ctrlKey: null, + shiftKey: null, + getModifierState: getEventModifierState +}; + +/** + * @param {object} dispatchConfig Configuration used to dispatch this event. + * @param {string} dispatchMarker Marker identifying the event target. + * @param {object} nativeEvent Native browser event. + * @extends {SyntheticUIEvent} + */ +function SyntheticTouchEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { + SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); +} + +SyntheticUIEvent.augmentClass(SyntheticTouchEvent, TouchEventInterface); + +module.exports = SyntheticTouchEvent; +},{"111":111,"127":127}],111:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule SyntheticUIEvent + * @typechecks static-only + */ + +'use strict'; + +var SyntheticEvent = _dereq_(105); + +var getEventTarget = _dereq_(128); + +/** + * @interface UIEvent + * @see http://www.w3.org/TR/DOM-Level-3-Events/ + */ +var UIEventInterface = { + view: function (event) { + if (event.view) { + return event.view; + } + + var target = getEventTarget(event); + if (target != null && target.window === target) { + // target is a window object + return target; + } + + var doc = target.ownerDocument; + // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. + if (doc) { + return doc.defaultView || doc.parentWindow; + } else { + return window; + } + }, + detail: function (event) { + return event.detail || 0; + } +}; + +/** + * @param {object} dispatchConfig Configuration used to dispatch this event. + * @param {string} dispatchMarker Marker identifying the event target. + * @param {object} nativeEvent Native browser event. + * @extends {SyntheticEvent} + */ +function SyntheticUIEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { + SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); +} + +SyntheticEvent.augmentClass(SyntheticUIEvent, UIEventInterface); + +module.exports = SyntheticUIEvent; +},{"105":105,"128":128}],112:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule SyntheticWheelEvent + * @typechecks static-only + */ + +'use strict'; + +var SyntheticMouseEvent = _dereq_(109); + +/** + * @interface WheelEvent + * @see http://www.w3.org/TR/DOM-Level-3-Events/ + */ +var WheelEventInterface = { + deltaX: function (event) { + return 'deltaX' in event ? event.deltaX : + // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive). + 'wheelDeltaX' in event ? -event.wheelDeltaX : 0; + }, + deltaY: function (event) { + return 'deltaY' in event ? event.deltaY : + // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive). + 'wheelDeltaY' in event ? -event.wheelDeltaY : + // Fallback to `wheelDelta` for IE<9 and normalize (down is positive). + 'wheelDelta' in event ? -event.wheelDelta : 0; + }, + deltaZ: null, + + // Browsers without "deltaMode" is reporting in raw wheel delta where one + // notch on the scroll is always +/- 120, roughly equivalent to pixels. + // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or + // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size. + deltaMode: null +}; + +/** + * @param {object} dispatchConfig Configuration used to dispatch this event. + * @param {string} dispatchMarker Marker identifying the event target. + * @param {object} nativeEvent Native browser event. + * @extends {SyntheticMouseEvent} + */ +function SyntheticWheelEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { + SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); +} + +SyntheticMouseEvent.augmentClass(SyntheticWheelEvent, WheelEventInterface); + +module.exports = SyntheticWheelEvent; +},{"109":109}],113:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule Transaction + */ + +'use strict'; + +var invariant = _dereq_(161); + +/** + * `Transaction` creates a black box that is able to wrap any method such that + * certain invariants are maintained before and after the method is invoked + * (Even if an exception is thrown while invoking the wrapped method). Whoever + * instantiates a transaction can provide enforcers of the invariants at + * creation time. The `Transaction` class itself will supply one additional + * automatic invariant for you - the invariant that any transaction instance + * should not be run while it is already being run. You would typically create a + * single instance of a `Transaction` for reuse multiple times, that potentially + * is used to wrap several different methods. Wrappers are extremely simple - + * they only require implementing two methods. + * + * <pre> + * wrappers (injected at creation time) + * + + + * | | + * +-----------------|--------|--------------+ + * | v | | + * | +---------------+ | | + * | +--| wrapper1 |---|----+ | + * | | +---------------+ v | | + * | | +-------------+ | | + * | | +----| wrapper2 |--------+ | + * | | | +-------------+ | | | + * | | | | | | + * | v v v v | wrapper + * | +---+ +---+ +---------+ +---+ +---+ | invariants + * perform(anyMethod) | | | | | | | | | | | | maintained + * +----------------->|-|---|-|---|-->|anyMethod|---|---|-|---|-|--------> + * | | | | | | | | | | | | + * | | | | | | | | | | | | + * | | | | | | | | | | | | + * | +---+ +---+ +---------+ +---+ +---+ | + * | initialize close | + * +-----------------------------------------+ + * </pre> + * + * Use cases: + * - Preserving the input selection ranges before/after reconciliation. + * Restoring selection even in the event of an unexpected error. + * - Deactivating events while rearranging the DOM, preventing blurs/focuses, + * while guaranteeing that afterwards, the event system is reactivated. + * - Flushing a queue of collected DOM mutations to the main UI thread after a + * reconciliation takes place in a worker thread. + * - Invoking any collected `componentDidUpdate` callbacks after rendering new + * content. + * - (Future use case): Wrapping particular flushes of the `ReactWorker` queue + * to preserve the `scrollTop` (an automatic scroll aware DOM). + * - (Future use case): Layout calculations before and after DOM updates. + * + * Transactional plugin API: + * - A module that has an `initialize` method that returns any precomputation. + * - and a `close` method that accepts the precomputation. `close` is invoked + * when the wrapped process is completed, or has failed. + * + * @param {Array<TransactionalWrapper>} transactionWrapper Wrapper modules + * that implement `initialize` and `close`. + * @return {Transaction} Single transaction for reuse in thread. + * + * @class Transaction + */ +var Mixin = { + /** + * Sets up this instance so that it is prepared for collecting metrics. Does + * so such that this setup method may be used on an instance that is already + * initialized, in a way that does not consume additional memory upon reuse. + * That can be useful if you decide to make your subclass of this mixin a + * "PooledClass". + */ + reinitializeTransaction: function () { + this.transactionWrappers = this.getTransactionWrappers(); + if (this.wrapperInitData) { + this.wrapperInitData.length = 0; + } else { + this.wrapperInitData = []; + } + this._isInTransaction = false; + }, + + _isInTransaction: false, + + /** + * @abstract + * @return {Array<TransactionWrapper>} Array of transaction wrappers. + */ + getTransactionWrappers: null, + + isInTransaction: function () { + return !!this._isInTransaction; + }, + + /** + * Executes the function within a safety window. Use this for the top level + * methods that result in large amounts of computation/mutations that would + * need to be safety checked. The optional arguments helps prevent the need + * to bind in many cases. + * + * @param {function} method Member of scope to call. + * @param {Object} scope Scope to invoke from. + * @param {Object?=} a Argument to pass to the method. + * @param {Object?=} b Argument to pass to the method. + * @param {Object?=} c Argument to pass to the method. + * @param {Object?=} d Argument to pass to the method. + * @param {Object?=} e Argument to pass to the method. + * @param {Object?=} f Argument to pass to the method. + * + * @return {*} Return value from `method`. + */ + perform: function (method, scope, a, b, c, d, e, f) { + !!this.isInTransaction() ? "development" !== 'production' ? invariant(false, 'Transaction.perform(...): Cannot initialize a transaction when there ' + 'is already an outstanding transaction.') : invariant(false) : undefined; + var errorThrown; + var ret; + try { + this._isInTransaction = true; + // Catching errors makes debugging more difficult, so we start with + // errorThrown set to true before setting it to false after calling + // close -- if it's still set to true in the finally block, it means + // one of these calls threw. + errorThrown = true; + this.initializeAll(0); + ret = method.call(scope, a, b, c, d, e, f); + errorThrown = false; + } finally { + try { + if (errorThrown) { + // If `method` throws, prefer to show that stack trace over any thrown + // by invoking `closeAll`. + try { + this.closeAll(0); + } catch (err) {} + } else { + // Since `method` didn't throw, we don't want to silence the exception + // here. + this.closeAll(0); + } + } finally { + this._isInTransaction = false; + } + } + return ret; + }, + + initializeAll: function (startIndex) { + var transactionWrappers = this.transactionWrappers; + for (var i = startIndex; i < transactionWrappers.length; i++) { + var wrapper = transactionWrappers[i]; + try { + // Catching errors makes debugging more difficult, so we start with the + // OBSERVED_ERROR state before overwriting it with the real return value + // of initialize -- if it's still set to OBSERVED_ERROR in the finally + // block, it means wrapper.initialize threw. + this.wrapperInitData[i] = Transaction.OBSERVED_ERROR; + this.wrapperInitData[i] = wrapper.initialize ? wrapper.initialize.call(this) : null; + } finally { + if (this.wrapperInitData[i] === Transaction.OBSERVED_ERROR) { + // The initializer for wrapper i threw an error; initialize the + // remaining wrappers but silence any exceptions from them to ensure + // that the first error is the one to bubble up. + try { + this.initializeAll(i + 1); + } catch (err) {} + } + } + } + }, + + /** + * Invokes each of `this.transactionWrappers.close[i]` functions, passing into + * them the respective return values of `this.transactionWrappers.init[i]` + * (`close`rs that correspond to initializers that failed will not be + * invoked). + */ + closeAll: function (startIndex) { + !this.isInTransaction() ? "development" !== 'production' ? invariant(false, 'Transaction.closeAll(): Cannot close transaction when none are open.') : invariant(false) : undefined; + var transactionWrappers = this.transactionWrappers; + for (var i = startIndex; i < transactionWrappers.length; i++) { + var wrapper = transactionWrappers[i]; + var initData = this.wrapperInitData[i]; + var errorThrown; + try { + // Catching errors makes debugging more difficult, so we start with + // errorThrown set to true before setting it to false after calling + // close -- if it's still set to true in the finally block, it means + // wrapper.close threw. + errorThrown = true; + if (initData !== Transaction.OBSERVED_ERROR && wrapper.close) { + wrapper.close.call(this, initData); + } + errorThrown = false; + } finally { + if (errorThrown) { + // The closer for wrapper i threw an error; close the remaining + // wrappers but silence any exceptions from them to ensure that the + // first error is the one to bubble up. + try { + this.closeAll(i + 1); + } catch (e) {} + } + } + } + this.wrapperInitData.length = 0; + } +}; + +var Transaction = { + + Mixin: Mixin, + + /** + * Token to look for to determine if an error occurred. + */ + OBSERVED_ERROR: {} + +}; + +module.exports = Transaction; +},{"161":161}],114:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ViewportMetrics + */ + +'use strict'; + +var ViewportMetrics = { + + currentScrollLeft: 0, + + currentScrollTop: 0, + + refreshScrollValues: function (scrollPosition) { + ViewportMetrics.currentScrollLeft = scrollPosition.x; + ViewportMetrics.currentScrollTop = scrollPosition.y; + } + +}; + +module.exports = ViewportMetrics; +},{}],115:[function(_dereq_,module,exports){ +/** + * Copyright 2014-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule accumulateInto + */ + +'use strict'; + +var invariant = _dereq_(161); + +/** + * + * Accumulates items that must not be null or undefined into the first one. This + * is used to conserve memory by avoiding array allocations, and thus sacrifices + * API cleanness. Since `current` can be null before being passed in and not + * null after this function, make sure to assign it back to `current`: + * + * `a = accumulateInto(a, b);` + * + * This API should be sparingly used. Try `accumulate` for something cleaner. + * + * @return {*|array<*>} An accumulation of items. + */ + +function accumulateInto(current, next) { + !(next != null) ? "development" !== 'production' ? invariant(false, 'accumulateInto(...): Accumulated items must not be null or undefined.') : invariant(false) : undefined; + if (current == null) { + return next; + } + + // Both are not empty. Warning: Never call x.concat(y) when you are not + // certain that x is an Array (x could be a string with concat method). + var currentIsArray = Array.isArray(current); + var nextIsArray = Array.isArray(next); + + if (currentIsArray && nextIsArray) { + current.push.apply(current, next); + return current; + } + + if (currentIsArray) { + current.push(next); + return current; + } + + if (nextIsArray) { + // A bit too dangerous to mutate `next`. + return [current].concat(next); + } + + return [current, next]; +} + +module.exports = accumulateInto; +},{"161":161}],116:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule adler32 + */ + +'use strict'; + +var MOD = 65521; + +// adler32 is not cryptographically strong, and is only used to sanity check that +// markup generated on the server matches the markup generated on the client. +// This implementation (a modified version of the SheetJS version) has been optimized +// for our use case, at the expense of conforming to the adler32 specification +// for non-ascii inputs. +function adler32(data) { + var a = 1; + var b = 0; + var i = 0; + var l = data.length; + var m = l & ~0x3; + while (i < m) { + for (; i < Math.min(i + 4096, m); i += 4) { + b += (a += data.charCodeAt(i)) + (a += data.charCodeAt(i + 1)) + (a += data.charCodeAt(i + 2)) + (a += data.charCodeAt(i + 3)); + } + a %= MOD; + b %= MOD; + } + for (; i < l; i++) { + b += a += data.charCodeAt(i); + } + a %= MOD; + b %= MOD; + return a | b << 16; +} + +module.exports = adler32; +},{}],117:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule canDefineProperty + */ + +'use strict'; + +var canDefineProperty = false; +if ("development" !== 'production') { + try { + Object.defineProperty({}, 'x', { get: function () {} }); + canDefineProperty = true; + } catch (x) { + // IE will fail on defineProperty + } +} + +module.exports = canDefineProperty; +},{}],118:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @typechecks static-only + * @providesModule cloneWithProps + */ + +'use strict'; + +var ReactElement = _dereq_(57); +var ReactPropTransferer = _dereq_(79); + +var keyOf = _dereq_(166); +var warning = _dereq_(173); + +var CHILDREN_PROP = keyOf({ children: null }); + +var didDeprecatedWarn = false; + +/** + * Sometimes you want to change the props of a child passed to you. Usually + * this is to add a CSS class. + * + * @param {ReactElement} child child element you'd like to clone + * @param {object} props props you'd like to modify. className and style will be + * merged automatically. + * @return {ReactElement} a clone of child with props merged in. + * @deprecated + */ +function cloneWithProps(child, props) { + if ("development" !== 'production') { + "development" !== 'production' ? warning(didDeprecatedWarn, 'cloneWithProps(...) is deprecated. ' + 'Please use React.cloneElement instead.') : undefined; + didDeprecatedWarn = true; + "development" !== 'production' ? warning(!child.ref, 'You are calling cloneWithProps() on a child with a ref. This is ' + 'dangerous because you\'re creating a new child which will not be ' + 'added as a ref to its parent.') : undefined; + } + + var newProps = ReactPropTransferer.mergeProps(props, child.props); + + // Use `child.props.children` if it is provided. + if (!newProps.hasOwnProperty(CHILDREN_PROP) && child.props.hasOwnProperty(CHILDREN_PROP)) { + newProps.children = child.props.children; + } + + // The current API doesn't retain _owner, which is why this + // doesn't use ReactElement.cloneAndReplaceProps. + return ReactElement.createElement(child.type, newProps); +} + +module.exports = cloneWithProps; +},{"166":166,"173":173,"57":57,"79":79}],119:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule dangerousStyleValue + * @typechecks static-only + */ + +'use strict'; + +var CSSProperty = _dereq_(4); + +var isUnitlessNumber = CSSProperty.isUnitlessNumber; + +/** + * Convert a value into the proper css writable value. The style name `name` + * should be logical (no hyphens), as specified + * in `CSSProperty.isUnitlessNumber`. + * + * @param {string} name CSS property name such as `topMargin`. + * @param {*} value CSS property value such as `10px`. + * @return {string} Normalized style value with dimensions applied. + */ +function dangerousStyleValue(name, value) { + // Note that we've removed escapeTextForBrowser() calls here since the + // whole string will be escaped when the attribute is injected into + // the markup. If you provide unsafe user data here they can inject + // arbitrary CSS which may be problematic (I couldn't repro this): + // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet + // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/ + // This is not an XSS hole but instead a potential CSS injection issue + // which has lead to a greater discussion about how we're going to + // trust URLs moving forward. See #2115901 + + var isEmpty = value == null || typeof value === 'boolean' || value === ''; + if (isEmpty) { + return ''; + } + + var isNonNumeric = isNaN(value); + if (isNonNumeric || value === 0 || isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name]) { + return '' + value; // cast to string + } + + if (typeof value === 'string') { + value = value.trim(); + } + return value + 'px'; +} + +module.exports = dangerousStyleValue; +},{"4":4}],120:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule deprecated + */ + +'use strict'; + +var assign = _dereq_(24); +var warning = _dereq_(173); + +/** + * This will log a single deprecation notice per function and forward the call + * on to the new API. + * + * @param {string} fnName The name of the function + * @param {string} newModule The module that fn will exist in + * @param {string} newPackage The module that fn will exist in + * @param {*} ctx The context this forwarded call should run in + * @param {function} fn The function to forward on to + * @return {function} The function that will warn once and then call fn + */ +function deprecated(fnName, newModule, newPackage, ctx, fn) { + var warned = false; + if ("development" !== 'production') { + var newFn = function () { + "development" !== 'production' ? warning(warned, + // Require examples in this string must be split to prevent React's + // build tools from mistaking them for real requires. + // Otherwise the build tools will attempt to build a '%s' module. + 'React.%s is deprecated. Please use %s.%s from require' + '(\'%s\') ' + 'instead.', fnName, newModule, fnName, newPackage) : undefined; + warned = true; + return fn.apply(ctx, arguments); + }; + // We need to make sure all properties of the original fn are copied over. + // In particular, this is needed to support PropTypes + return assign(newFn, fn); + } + + return fn; +} + +module.exports = deprecated; +},{"173":173,"24":24}],121:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule escapeTextContentForBrowser + */ + +'use strict'; + +var ESCAPE_LOOKUP = { + '&': '&', + '>': '>', + '<': '<', + '"': '"', + '\'': ''' +}; + +var ESCAPE_REGEX = /[&><"']/g; + +function escaper(match) { + return ESCAPE_LOOKUP[match]; +} + +/** + * Escapes text to prevent scripting attacks. + * + * @param {*} text Text value to escape. + * @return {string} An escaped string. + */ +function escapeTextContentForBrowser(text) { + return ('' + text).replace(ESCAPE_REGEX, escaper); +} + +module.exports = escapeTextContentForBrowser; +},{}],122:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule findDOMNode + * @typechecks static-only + */ + +'use strict'; + +var ReactCurrentOwner = _dereq_(39); +var ReactInstanceMap = _dereq_(68); +var ReactMount = _dereq_(72); + +var invariant = _dereq_(161); +var warning = _dereq_(173); + +/** + * Returns the DOM node rendered by this element. + * + * @param {ReactComponent|DOMElement} componentOrElement + * @return {?DOMElement} The root node of this element. + */ +function findDOMNode(componentOrElement) { + if ("development" !== 'production') { + var owner = ReactCurrentOwner.current; + if (owner !== null) { + "development" !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing getDOMNode or findDOMNode inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component') : undefined; + owner._warnedAboutRefsInRender = true; + } + } + if (componentOrElement == null) { + return null; + } + if (componentOrElement.nodeType === 1) { + return componentOrElement; + } + if (ReactInstanceMap.has(componentOrElement)) { + return ReactMount.getNodeFromInstance(componentOrElement); + } + !(componentOrElement.render == null || typeof componentOrElement.render !== 'function') ? "development" !== 'production' ? invariant(false, 'findDOMNode was called on an unmounted component.') : invariant(false) : undefined; + !false ? "development" !== 'production' ? invariant(false, 'Element appears to be neither ReactComponent nor DOMNode (keys: %s)', Object.keys(componentOrElement)) : invariant(false) : undefined; +} + +module.exports = findDOMNode; +},{"161":161,"173":173,"39":39,"68":68,"72":72}],123:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule flattenChildren + */ + +'use strict'; + +var traverseAllChildren = _dereq_(142); +var warning = _dereq_(173); + +/** + * @param {function} traverseContext Context passed through traversal. + * @param {?ReactComponent} child React child component. + * @param {!string} name String name of key path to child. + */ +function flattenSingleChildIntoContext(traverseContext, child, name) { + // We found a component instance. + var result = traverseContext; + var keyUnique = result[name] === undefined; + if ("development" !== 'production') { + "development" !== 'production' ? warning(keyUnique, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.', name) : undefined; + } + if (keyUnique && child != null) { + result[name] = child; + } +} + +/** + * Flattens children that are typically specified as `props.children`. Any null + * children will not be included in the resulting object. + * @return {!object} flattened children keyed by name. + */ +function flattenChildren(children) { + if (children == null) { + return children; + } + var result = {}; + traverseAllChildren(children, flattenSingleChildIntoContext, result); + return result; +} + +module.exports = flattenChildren; +},{"142":142,"173":173}],124:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule forEachAccumulated + */ + +'use strict'; + +/** + * @param {array} arr an "accumulation" of items which is either an Array or + * a single item. Useful when paired with the `accumulate` module. This is a + * simple utility that allows us to reason about a collection of items, but + * handling the case when there is exactly one item (and we do not need to + * allocate an array). + */ +var forEachAccumulated = function (arr, cb, scope) { + if (Array.isArray(arr)) { + arr.forEach(cb, scope); + } else if (arr) { + cb.call(scope, arr); + } +}; + +module.exports = forEachAccumulated; +},{}],125:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule getEventCharCode + * @typechecks static-only + */ + +'use strict'; + +/** + * `charCode` represents the actual "character code" and is safe to use with + * `String.fromCharCode`. As such, only keys that correspond to printable + * characters produce a valid `charCode`, the only exception to this is Enter. + * The Tab-key is considered non-printable and does not have a `charCode`, + * presumably because it does not produce a tab-character in browsers. + * + * @param {object} nativeEvent Native browser event. + * @return {number} Normalized `charCode` property. + */ +function getEventCharCode(nativeEvent) { + var charCode; + var keyCode = nativeEvent.keyCode; + + if ('charCode' in nativeEvent) { + charCode = nativeEvent.charCode; + + // FF does not set `charCode` for the Enter-key, check against `keyCode`. + if (charCode === 0 && keyCode === 13) { + charCode = 13; + } + } else { + // IE8 does not implement `charCode`, but `keyCode` has the correct value. + charCode = keyCode; + } + + // Some non-printable keys are reported in `charCode`/`keyCode`, discard them. + // Must not discard the (non-)printable Enter-key. + if (charCode >= 32 || charCode === 13) { + return charCode; + } + + return 0; +} + +module.exports = getEventCharCode; +},{}],126:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule getEventKey + * @typechecks static-only + */ + +'use strict'; + +var getEventCharCode = _dereq_(125); + +/** + * Normalization of deprecated HTML5 `key` values + * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names + */ +var normalizeKey = { + 'Esc': 'Escape', + 'Spacebar': ' ', + 'Left': 'ArrowLeft', + 'Up': 'ArrowUp', + 'Right': 'ArrowRight', + 'Down': 'ArrowDown', + 'Del': 'Delete', + 'Win': 'OS', + 'Menu': 'ContextMenu', + 'Apps': 'ContextMenu', + 'Scroll': 'ScrollLock', + 'MozPrintableKey': 'Unidentified' +}; + +/** + * Translation from legacy `keyCode` to HTML5 `key` + * Only special keys supported, all others depend on keyboard layout or browser + * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names + */ +var translateToKey = { + 8: 'Backspace', + 9: 'Tab', + 12: 'Clear', + 13: 'Enter', + 16: 'Shift', + 17: 'Control', + 18: 'Alt', + 19: 'Pause', + 20: 'CapsLock', + 27: 'Escape', + 32: ' ', + 33: 'PageUp', + 34: 'PageDown', + 35: 'End', + 36: 'Home', + 37: 'ArrowLeft', + 38: 'ArrowUp', + 39: 'ArrowRight', + 40: 'ArrowDown', + 45: 'Insert', + 46: 'Delete', + 112: 'F1', 113: 'F2', 114: 'F3', 115: 'F4', 116: 'F5', 117: 'F6', + 118: 'F7', 119: 'F8', 120: 'F9', 121: 'F10', 122: 'F11', 123: 'F12', + 144: 'NumLock', + 145: 'ScrollLock', + 224: 'Meta' +}; + +/** + * @param {object} nativeEvent Native browser event. + * @return {string} Normalized `key` property. + */ +function getEventKey(nativeEvent) { + if (nativeEvent.key) { + // Normalize inconsistent values reported by browsers due to + // implementations of a working draft specification. + + // FireFox implements `key` but returns `MozPrintableKey` for all + // printable characters (normalized to `Unidentified`), ignore it. + var key = normalizeKey[nativeEvent.key] || nativeEvent.key; + if (key !== 'Unidentified') { + return key; + } + } + + // Browser does not implement `key`, polyfill as much of it as we can. + if (nativeEvent.type === 'keypress') { + var charCode = getEventCharCode(nativeEvent); + + // The enter-key is technically both printable and non-printable and can + // thus be captured by `keypress`, no other non-printable key should. + return charCode === 13 ? 'Enter' : String.fromCharCode(charCode); + } + if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') { + // While user keyboard layout determines the actual meaning of each + // `keyCode` value, almost all function keys have a universal value. + return translateToKey[nativeEvent.keyCode] || 'Unidentified'; + } + return ''; +} + +module.exports = getEventKey; +},{"125":125}],127:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule getEventModifierState + * @typechecks static-only + */ + +'use strict'; + +/** + * Translation from modifier key to the associated property in the event. + * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers + */ + +var modifierKeyToProp = { + 'Alt': 'altKey', + 'Control': 'ctrlKey', + 'Meta': 'metaKey', + 'Shift': 'shiftKey' +}; + +// IE8 does not implement getModifierState so we simply map it to the only +// modifier keys exposed by the event itself, does not support Lock-keys. +// Currently, all major browsers except Chrome seems to support Lock-keys. +function modifierStateGetter(keyArg) { + var syntheticEvent = this; + var nativeEvent = syntheticEvent.nativeEvent; + if (nativeEvent.getModifierState) { + return nativeEvent.getModifierState(keyArg); + } + var keyProp = modifierKeyToProp[keyArg]; + return keyProp ? !!nativeEvent[keyProp] : false; +} + +function getEventModifierState(nativeEvent) { + return modifierStateGetter; +} + +module.exports = getEventModifierState; +},{}],128:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule getEventTarget + * @typechecks static-only + */ + +'use strict'; + +/** + * Gets the target node from a native browser event by accounting for + * inconsistencies in browser DOM APIs. + * + * @param {object} nativeEvent Native browser event. + * @return {DOMEventTarget} Target node. + */ +function getEventTarget(nativeEvent) { + var target = nativeEvent.target || nativeEvent.srcElement || window; + // Safari may fire events on text nodes (Node.TEXT_NODE is 3). + // @see http://www.quirksmode.org/js/events_properties.html + return target.nodeType === 3 ? target.parentNode : target; +} + +module.exports = getEventTarget; +},{}],129:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule getIteratorFn + * @typechecks static-only + */ + +'use strict'; + +/* global Symbol */ +var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; +var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec. + +/** + * Returns the iterator method function contained on the iterable object. + * + * Be sure to invoke the function with the iterable as context: + * + * var iteratorFn = getIteratorFn(myIterable); + * if (iteratorFn) { + * var iterator = iteratorFn.call(myIterable); + * ... + * } + * + * @param {?object} maybeIterable + * @return {?function} + */ +function getIteratorFn(maybeIterable) { + var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); + if (typeof iteratorFn === 'function') { + return iteratorFn; + } +} + +module.exports = getIteratorFn; +},{}],130:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule getNodeForCharacterOffset + */ + +'use strict'; + +/** + * Given any node return the first leaf node without children. + * + * @param {DOMElement|DOMTextNode} node + * @return {DOMElement|DOMTextNode} + */ +function getLeafNode(node) { + while (node && node.firstChild) { + node = node.firstChild; + } + return node; +} + +/** + * Get the next sibling within a container. This will walk up the + * DOM if a node's siblings have been exhausted. + * + * @param {DOMElement|DOMTextNode} node + * @return {?DOMElement|DOMTextNode} + */ +function getSiblingNode(node) { + while (node) { + if (node.nextSibling) { + return node.nextSibling; + } + node = node.parentNode; + } +} + +/** + * Get object describing the nodes which contain characters at offset. + * + * @param {DOMElement|DOMTextNode} root + * @param {number} offset + * @return {?object} + */ +function getNodeForCharacterOffset(root, offset) { + var node = getLeafNode(root); + var nodeStart = 0; + var nodeEnd = 0; + + while (node) { + if (node.nodeType === 3) { + nodeEnd = nodeStart + node.textContent.length; + + if (nodeStart <= offset && nodeEnd >= offset) { + return { + node: node, + offset: offset - nodeStart + }; + } + + nodeStart = nodeEnd; + } + + node = getLeafNode(getSiblingNode(node)); + } +} + +module.exports = getNodeForCharacterOffset; +},{}],131:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule getTextContentAccessor + */ + +'use strict'; + +var ExecutionEnvironment = _dereq_(147); + +var contentKey = null; + +/** + * Gets the key used to access text content on a DOM node. + * + * @return {?string} Key used to access text content. + * @internal + */ +function getTextContentAccessor() { + if (!contentKey && ExecutionEnvironment.canUseDOM) { + // Prefer textContent to innerText because many browsers support both but + // SVG <text> elements don't support innerText even when <div> does. + contentKey = 'textContent' in document.documentElement ? 'textContent' : 'innerText'; + } + return contentKey; +} + +module.exports = getTextContentAccessor; +},{"147":147}],132:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule instantiateReactComponent + * @typechecks static-only + */ + +'use strict'; + +var ReactCompositeComponent = _dereq_(38); +var ReactEmptyComponent = _dereq_(59); +var ReactNativeComponent = _dereq_(75); + +var assign = _dereq_(24); +var invariant = _dereq_(161); +var warning = _dereq_(173); + +// To avoid a cyclic dependency, we create the final class in this module +var ReactCompositeComponentWrapper = function () {}; +assign(ReactCompositeComponentWrapper.prototype, ReactCompositeComponent.Mixin, { + _instantiateReactComponent: instantiateReactComponent +}); + +function getDeclarationErrorAddendum(owner) { + if (owner) { + var name = owner.getName(); + if (name) { + return ' Check the render method of `' + name + '`.'; + } + } + return ''; +} + +/** + * Check if the type reference is a known internal type. I.e. not a user + * provided composite type. + * + * @param {function} type + * @return {boolean} Returns true if this is a valid internal type. + */ +function isInternalComponentType(type) { + return typeof type === 'function' && typeof type.prototype !== 'undefined' && typeof type.prototype.mountComponent === 'function' && typeof type.prototype.receiveComponent === 'function'; +} + +/** + * Given a ReactNode, create an instance that will actually be mounted. + * + * @param {ReactNode} node + * @return {object} A new instance of the element's constructor. + * @protected + */ +function instantiateReactComponent(node) { + var instance; + + if (node === null || node === false) { + instance = new ReactEmptyComponent(instantiateReactComponent); + } else if (typeof node === 'object') { + var element = node; + !(element && (typeof element.type === 'function' || typeof element.type === 'string')) ? "development" !== 'production' ? invariant(false, 'Element type is invalid: expected a string (for built-in components) ' + 'or a class/function (for composite components) but got: %s.%s', element.type == null ? element.type : typeof element.type, getDeclarationErrorAddendum(element._owner)) : invariant(false) : undefined; + + // Special case string values + if (typeof element.type === 'string') { + instance = ReactNativeComponent.createInternalComponent(element); + } else if (isInternalComponentType(element.type)) { + // This is temporarily available for custom components that are not string + // representations. I.e. ART. Once those are updated to use the string + // representation, we can drop this code path. + instance = new element.type(element); + } else { + instance = new ReactCompositeComponentWrapper(); + } + } else if (typeof node === 'string' || typeof node === 'number') { + instance = ReactNativeComponent.createInstanceForText(node); + } else { + !false ? "development" !== 'production' ? invariant(false, 'Encountered invalid React node of type %s', typeof node) : invariant(false) : undefined; + } + + if ("development" !== 'production') { + "development" !== 'production' ? warning(typeof instance.construct === 'function' && typeof instance.mountComponent === 'function' && typeof instance.receiveComponent === 'function' && typeof instance.unmountComponent === 'function', 'Only React Components can be mounted.') : undefined; + } + + // Sets up the instance. This can probably just move into the constructor now. + instance.construct(node); + + // These two fields are used by the DOM and ART diffing algorithms + // respectively. Instead of using expandos on components, we should be + // storing the state needed by the diffing algorithms elsewhere. + instance._mountIndex = 0; + instance._mountImage = null; + + if ("development" !== 'production') { + instance._isOwnerNecessary = false; + instance._warnedAboutRefsInRender = false; + } + + // Internal instances should fully constructed at this point, so they should + // not get any new fields added to them at this point. + if ("development" !== 'production') { + if (Object.preventExtensions) { + Object.preventExtensions(instance); + } + } + + return instance; +} + +module.exports = instantiateReactComponent; +},{"161":161,"173":173,"24":24,"38":38,"59":59,"75":75}],133:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule isEventSupported + */ + +'use strict'; + +var ExecutionEnvironment = _dereq_(147); + +var useHasFeature; +if (ExecutionEnvironment.canUseDOM) { + useHasFeature = document.implementation && document.implementation.hasFeature && + // always returns true in newer browsers as per the standard. + // @see http://dom.spec.whatwg.org/#dom-domimplementation-hasfeature + document.implementation.hasFeature('', '') !== true; +} + +/** + * Checks if an event is supported in the current execution environment. + * + * NOTE: This will not work correctly for non-generic events such as `change`, + * `reset`, `load`, `error`, and `select`. + * + * Borrows from Modernizr. + * + * @param {string} eventNameSuffix Event name, e.g. "click". + * @param {?boolean} capture Check if the capture phase is supported. + * @return {boolean} True if the event is supported. + * @internal + * @license Modernizr 3.0.0pre (Custom Build) | MIT + */ +function isEventSupported(eventNameSuffix, capture) { + if (!ExecutionEnvironment.canUseDOM || capture && !('addEventListener' in document)) { + return false; + } + + var eventName = 'on' + eventNameSuffix; + var isSupported = (eventName in document); + + if (!isSupported) { + var element = document.createElementNS('http://www.w3.org/1999/xhtml', 'div'); + element.setAttribute(eventName, 'return;'); + isSupported = typeof element[eventName] === 'function'; + } + + if (!isSupported && useHasFeature && eventNameSuffix === 'wheel') { + // This is the only way to test support for the `wheel` event in IE9+. + isSupported = document.implementation.hasFeature('Events.wheel', '3.0'); + } + + return isSupported; +} + +module.exports = isEventSupported; +},{"147":147}],134:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule isTextInputElement + */ + +'use strict'; + +/** + * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary + */ +var supportedInputTypes = { + 'color': true, + 'date': true, + 'datetime': true, + 'datetime-local': true, + 'email': true, + 'month': true, + 'number': true, + 'password': true, + 'range': true, + 'search': true, + 'tel': true, + 'text': true, + 'time': true, + 'url': true, + 'week': true +}; + +function isTextInputElement(elem) { + var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); + return nodeName && (nodeName === 'input' && supportedInputTypes[elem.type] || nodeName === 'textarea'); +} + +module.exports = isTextInputElement; +},{}],135:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule onlyChild + */ +'use strict'; + +var ReactElement = _dereq_(57); + +var invariant = _dereq_(161); + +/** + * Returns the first child in a collection of children and verifies that there + * is only one child in the collection. The current implementation of this + * function assumes that a single child gets passed without a wrapper, but the + * purpose of this helper function is to abstract away the particular structure + * of children. + * + * @param {?object} children Child collection structure. + * @return {ReactComponent} The first and only `ReactComponent` contained in the + * structure. + */ +function onlyChild(children) { + !ReactElement.isValidElement(children) ? "development" !== 'production' ? invariant(false, 'onlyChild must be passed a children with exactly one child.') : invariant(false) : undefined; + return children; +} + +module.exports = onlyChild; +},{"161":161,"57":57}],136:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule quoteAttributeValueForBrowser + */ + +'use strict'; + +var escapeTextContentForBrowser = _dereq_(121); + +/** + * Escapes attribute value to prevent scripting attacks. + * + * @param {*} value Value to escape. + * @return {string} An escaped string. + */ +function quoteAttributeValueForBrowser(value) { + return '"' + escapeTextContentForBrowser(value) + '"'; +} + +module.exports = quoteAttributeValueForBrowser; +},{"121":121}],137:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * +* @providesModule renderSubtreeIntoContainer +*/ + +'use strict'; + +var ReactMount = _dereq_(72); + +module.exports = ReactMount.renderSubtreeIntoContainer; +},{"72":72}],138:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule setInnerHTML + */ + +/* globals MSApp */ + +'use strict'; + +var ExecutionEnvironment = _dereq_(147); + +var WHITESPACE_TEST = /^[ \r\n\t\f]/; +var NONVISIBLE_TEST = /<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/; + +/** + * Set the innerHTML property of a node, ensuring that whitespace is preserved + * even in IE8. + * + * @param {DOMElement} node + * @param {string} html + * @internal + */ +var setInnerHTML = function (node, html) { + node.innerHTML = html; +}; + +// Win8 apps: Allow all html to be inserted +if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) { + setInnerHTML = function (node, html) { + MSApp.execUnsafeLocalFunction(function () { + node.innerHTML = html; + }); + }; +} + +if (ExecutionEnvironment.canUseDOM) { + // IE8: When updating a just created node with innerHTML only leading + // whitespace is removed. When updating an existing node with innerHTML + // whitespace in root TextNodes is also collapsed. + // @see quirksmode.org/bugreports/archives/2004/11/innerhtml_and_t.html + + // Feature detection; only IE8 is known to behave improperly like this. + var testElement = document.createElementNS('http://www.w3.org/1999/xhtml', 'div'); + testElement.innerHTML = ' '; + if (testElement.innerHTML === '') { + setInnerHTML = function (node, html) { + // Magic theory: IE8 supposedly differentiates between added and updated + // nodes when processing innerHTML, innerHTML on updated nodes suffers + // from worse whitespace behavior. Re-adding a node like this triggers + // the initial and more favorable whitespace behavior. + // TODO: What to do on a detached node? + if (node.parentNode) { + node.parentNode.replaceChild(node, node); + } + + // We also implement a workaround for non-visible tags disappearing into + // thin air on IE8, this only happens if there is no visible text + // in-front of the non-visible tags. Piggyback on the whitespace fix + // and simply check if any non-visible tags appear in the source. + if (WHITESPACE_TEST.test(html) || html[0] === '<' && NONVISIBLE_TEST.test(html)) { + // Recover leading whitespace by temporarily prepending any character. + // \uFEFF has the potential advantage of being zero-width/invisible. + // UglifyJS drops U+FEFF chars when parsing, so use String.fromCharCode + // in hopes that this is preserved even if "\uFEFF" is transformed to + // the actual Unicode character (by Babel, for example). + // https://github.com/mishoo/UglifyJS2/blob/v2.4.20/lib/parse.js#L216 + node.innerHTML = String.fromCharCode(0xFEFF) + html; + + // deleteData leaves an empty `TextNode` which offsets the index of all + // children. Definitely want to avoid this. + var textNode = node.firstChild; + if (textNode.data.length === 1) { + node.removeChild(textNode); + } else { + textNode.deleteData(0, 1); + } + } else { + node.innerHTML = html; + } + }; + } +} + +module.exports = setInnerHTML; +},{"147":147}],139:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule setTextContent + */ + +'use strict'; + +var ExecutionEnvironment = _dereq_(147); +var escapeTextContentForBrowser = _dereq_(121); +var setInnerHTML = _dereq_(138); + +/** + * Set the textContent property of a node, ensuring that whitespace is preserved + * even in IE8. innerText is a poor substitute for textContent and, among many + * issues, inserts <br> instead of the literal newline chars. innerHTML behaves + * as it should. + * + * @param {DOMElement} node + * @param {string} text + * @internal + */ +var setTextContent = function (node, text) { + node.textContent = text; +}; + +if (ExecutionEnvironment.canUseDOM) { + if (!('textContent' in document.documentElement)) { + setTextContent = function (node, text) { + setInnerHTML(node, escapeTextContentForBrowser(text)); + }; + } +} + +module.exports = setTextContent; +},{"121":121,"138":138,"147":147}],140:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * +* @providesModule shallowCompare +*/ + +'use strict'; + +var shallowEqual = _dereq_(171); + +/** + * Does a shallow comparison for props and state. + * See ReactComponentWithPureRenderMixin + */ +function shallowCompare(instance, nextProps, nextState) { + return !shallowEqual(instance.props, nextProps) || !shallowEqual(instance.state, nextState); +} + +module.exports = shallowCompare; +},{"171":171}],141:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule shouldUpdateReactComponent + * @typechecks static-only + */ + +'use strict'; + +/** + * Given a `prevElement` and `nextElement`, determines if the existing + * instance should be updated as opposed to being destroyed or replaced by a new + * instance. Both arguments are elements. This ensures that this logic can + * operate on stateless trees without any backing instance. + * + * @param {?object} prevElement + * @param {?object} nextElement + * @return {boolean} True if the existing instance should be updated. + * @protected + */ +function shouldUpdateReactComponent(prevElement, nextElement) { + var prevEmpty = prevElement === null || prevElement === false; + var nextEmpty = nextElement === null || nextElement === false; + if (prevEmpty || nextEmpty) { + return prevEmpty === nextEmpty; + } + + var prevType = typeof prevElement; + var nextType = typeof nextElement; + if (prevType === 'string' || prevType === 'number') { + return nextType === 'string' || nextType === 'number'; + } else { + return nextType === 'object' && prevElement.type === nextElement.type && prevElement.key === nextElement.key; + } + return false; +} + +module.exports = shouldUpdateReactComponent; +},{}],142:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule traverseAllChildren + */ + +'use strict'; + +var ReactCurrentOwner = _dereq_(39); +var ReactElement = _dereq_(57); +var ReactInstanceHandles = _dereq_(67); + +var getIteratorFn = _dereq_(129); +var invariant = _dereq_(161); +var warning = _dereq_(173); + +var SEPARATOR = ReactInstanceHandles.SEPARATOR; +var SUBSEPARATOR = ':'; + +/** + * TODO: Test that a single child and an array with one item have the same key + * pattern. + */ + +var userProvidedKeyEscaperLookup = { + '=': '=0', + '.': '=1', + ':': '=2' +}; + +var userProvidedKeyEscapeRegex = /[=.:]/g; + +var didWarnAboutMaps = false; + +function userProvidedKeyEscaper(match) { + return userProvidedKeyEscaperLookup[match]; +} + +/** + * Generate a key string that identifies a component within a set. + * + * @param {*} component A component that could contain a manual key. + * @param {number} index Index that is used if a manual key is not provided. + * @return {string} + */ +function getComponentKey(component, index) { + if (component && component.key != null) { + // Explicit key + return wrapUserProvidedKey(component.key); + } + // Implicit key determined by the index in the set + return index.toString(36); +} + +/** + * Escape a component key so that it is safe to use in a reactid. + * + * @param {*} text Component key to be escaped. + * @return {string} An escaped string. + */ +function escapeUserProvidedKey(text) { + return ('' + text).replace(userProvidedKeyEscapeRegex, userProvidedKeyEscaper); +} + +/** + * Wrap a `key` value explicitly provided by the user to distinguish it from + * implicitly-generated keys generated by a component's index in its parent. + * + * @param {string} key Value of a user-provided `key` attribute + * @return {string} + */ +function wrapUserProvidedKey(key) { + return '$' + escapeUserProvidedKey(key); +} + +/** + * @param {?*} children Children tree container. + * @param {!string} nameSoFar Name of the key path so far. + * @param {!function} callback Callback to invoke with each child found. + * @param {?*} traverseContext Used to pass information throughout the traversal + * process. + * @return {!number} The number of children in this subtree. + */ +function traverseAllChildrenImpl(children, nameSoFar, callback, traverseContext) { + var type = typeof children; + + if (type === 'undefined' || type === 'boolean') { + // All of the above are perceived as null. + children = null; + } + + if (children === null || type === 'string' || type === 'number' || ReactElement.isValidElement(children)) { + callback(traverseContext, children, + // If it's the only child, treat the name as if it was wrapped in an array + // so that it's consistent if the number of children grows. + nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar); + return 1; + } + + var child; + var nextName; + var subtreeCount = 0; // Count of children found in the current subtree. + var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR; + + if (Array.isArray(children)) { + for (var i = 0; i < children.length; i++) { + child = children[i]; + nextName = nextNamePrefix + getComponentKey(child, i); + subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); + } + } else { + var iteratorFn = getIteratorFn(children); + if (iteratorFn) { + var iterator = iteratorFn.call(children); + var step; + if (iteratorFn !== children.entries) { + var ii = 0; + while (!(step = iterator.next()).done) { + child = step.value; + nextName = nextNamePrefix + getComponentKey(child, ii++); + subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); + } + } else { + if ("development" !== 'production') { + "development" !== 'production' ? warning(didWarnAboutMaps, 'Using Maps as children is not yet fully supported. It is an ' + 'experimental feature that might be removed. Convert it to a ' + 'sequence / iterable of keyed ReactElements instead.') : undefined; + didWarnAboutMaps = true; + } + // Iterator will provide entry [k,v] tuples rather than values. + while (!(step = iterator.next()).done) { + var entry = step.value; + if (entry) { + child = entry[1]; + nextName = nextNamePrefix + wrapUserProvidedKey(entry[0]) + SUBSEPARATOR + getComponentKey(child, 0); + subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); + } + } + } + } else if (type === 'object') { + var addendum = ''; + if ("development" !== 'production') { + addendum = ' If you meant to render a collection of children, use an array ' + 'instead or wrap the object using createFragment(object) from the ' + 'React add-ons.'; + if (children._isReactElement) { + addendum = ' It looks like you\'re using an element created by a different ' + 'version of React. Make sure to use only one copy of React.'; + } + if (ReactCurrentOwner.current) { + var name = ReactCurrentOwner.current.getName(); + if (name) { + addendum += ' Check the render method of `' + name + '`.'; + } + } + } + var childrenString = String(children); + !false ? "development" !== 'production' ? invariant(false, 'Objects are not valid as a React child (found: %s).%s', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : invariant(false) : undefined; + } + } + + return subtreeCount; +} + +/** + * Traverses children that are typically specified as `props.children`, but + * might also be specified through attributes: + * + * - `traverseAllChildren(this.props.children, ...)` + * - `traverseAllChildren(this.props.leftPanelChildren, ...)` + * + * The `traverseContext` is an optional argument that is passed through the + * entire traversal. It can be used to store accumulations or anything else that + * the callback might find relevant. + * + * @param {?*} children Children tree object. + * @param {!function} callback To invoke upon traversing each child. + * @param {?*} traverseContext Context for traversal. + * @return {!number} The number of children in this subtree. + */ +function traverseAllChildren(children, callback, traverseContext) { + if (children == null) { + return 0; + } + + return traverseAllChildrenImpl(children, '', callback, traverseContext); +} + +module.exports = traverseAllChildren; +},{"129":129,"161":161,"173":173,"39":39,"57":57,"67":67}],143:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule update + */ + +/* global hasOwnProperty:true */ + +'use strict'; + +var assign = _dereq_(24); +var keyOf = _dereq_(166); +var invariant = _dereq_(161); +var hasOwnProperty = ({}).hasOwnProperty; + +function shallowCopy(x) { + if (Array.isArray(x)) { + return x.concat(); + } else if (x && typeof x === 'object') { + return assign(new x.constructor(), x); + } else { + return x; + } +} + +var COMMAND_PUSH = keyOf({ $push: null }); +var COMMAND_UNSHIFT = keyOf({ $unshift: null }); +var COMMAND_SPLICE = keyOf({ $splice: null }); +var COMMAND_SET = keyOf({ $set: null }); +var COMMAND_MERGE = keyOf({ $merge: null }); +var COMMAND_APPLY = keyOf({ $apply: null }); + +var ALL_COMMANDS_LIST = [COMMAND_PUSH, COMMAND_UNSHIFT, COMMAND_SPLICE, COMMAND_SET, COMMAND_MERGE, COMMAND_APPLY]; + +var ALL_COMMANDS_SET = {}; + +ALL_COMMANDS_LIST.forEach(function (command) { + ALL_COMMANDS_SET[command] = true; +}); + +function invariantArrayCase(value, spec, command) { + !Array.isArray(value) ? "development" !== 'production' ? invariant(false, 'update(): expected target of %s to be an array; got %s.', command, value) : invariant(false) : undefined; + var specValue = spec[command]; + !Array.isArray(specValue) ? "development" !== 'production' ? invariant(false, 'update(): expected spec of %s to be an array; got %s. ' + 'Did you forget to wrap your parameter in an array?', command, specValue) : invariant(false) : undefined; +} + +function update(value, spec) { + !(typeof spec === 'object') ? "development" !== 'production' ? invariant(false, 'update(): You provided a key path to update() that did not contain one ' + 'of %s. Did you forget to include {%s: ...}?', ALL_COMMANDS_LIST.join(', '), COMMAND_SET) : invariant(false) : undefined; + + if (hasOwnProperty.call(spec, COMMAND_SET)) { + !(Object.keys(spec).length === 1) ? "development" !== 'production' ? invariant(false, 'Cannot have more than one key in an object with %s', COMMAND_SET) : invariant(false) : undefined; + + return spec[COMMAND_SET]; + } + + var nextValue = shallowCopy(value); + + if (hasOwnProperty.call(spec, COMMAND_MERGE)) { + var mergeObj = spec[COMMAND_MERGE]; + !(mergeObj && typeof mergeObj === 'object') ? "development" !== 'production' ? invariant(false, 'update(): %s expects a spec of type \'object\'; got %s', COMMAND_MERGE, mergeObj) : invariant(false) : undefined; + !(nextValue && typeof nextValue === 'object') ? "development" !== 'production' ? invariant(false, 'update(): %s expects a target of type \'object\'; got %s', COMMAND_MERGE, nextValue) : invariant(false) : undefined; + assign(nextValue, spec[COMMAND_MERGE]); + } + + if (hasOwnProperty.call(spec, COMMAND_PUSH)) { + invariantArrayCase(value, spec, COMMAND_PUSH); + spec[COMMAND_PUSH].forEach(function (item) { + nextValue.push(item); + }); + } + + if (hasOwnProperty.call(spec, COMMAND_UNSHIFT)) { + invariantArrayCase(value, spec, COMMAND_UNSHIFT); + spec[COMMAND_UNSHIFT].forEach(function (item) { + nextValue.unshift(item); + }); + } + + if (hasOwnProperty.call(spec, COMMAND_SPLICE)) { + !Array.isArray(value) ? "development" !== 'production' ? invariant(false, 'Expected %s target to be an array; got %s', COMMAND_SPLICE, value) : invariant(false) : undefined; + !Array.isArray(spec[COMMAND_SPLICE]) ? "development" !== 'production' ? invariant(false, 'update(): expected spec of %s to be an array of arrays; got %s. ' + 'Did you forget to wrap your parameters in an array?', COMMAND_SPLICE, spec[COMMAND_SPLICE]) : invariant(false) : undefined; + spec[COMMAND_SPLICE].forEach(function (args) { + !Array.isArray(args) ? "development" !== 'production' ? invariant(false, 'update(): expected spec of %s to be an array of arrays; got %s. ' + 'Did you forget to wrap your parameters in an array?', COMMAND_SPLICE, spec[COMMAND_SPLICE]) : invariant(false) : undefined; + nextValue.splice.apply(nextValue, args); + }); + } + + if (hasOwnProperty.call(spec, COMMAND_APPLY)) { + !(typeof spec[COMMAND_APPLY] === 'function') ? "development" !== 'production' ? invariant(false, 'update(): expected spec of %s to be a function; got %s.', COMMAND_APPLY, spec[COMMAND_APPLY]) : invariant(false) : undefined; + nextValue = spec[COMMAND_APPLY](nextValue); + } + + for (var k in spec) { + if (!(ALL_COMMANDS_SET.hasOwnProperty(k) && ALL_COMMANDS_SET[k])) { + nextValue[k] = update(value[k], spec[k]); + } + } + + return nextValue; +} + +module.exports = update; +},{"161":161,"166":166,"24":24}],144:[function(_dereq_,module,exports){ +/** + * Copyright 2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule validateDOMNesting + */ + +'use strict'; + +var assign = _dereq_(24); +var emptyFunction = _dereq_(153); +var warning = _dereq_(173); + +var validateDOMNesting = emptyFunction; + +if ("development" !== 'production') { + // This validation code was written based on the HTML5 parsing spec: + // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope + // + // Note: this does not catch all invalid nesting, nor does it try to (as it's + // not clear what practical benefit doing so provides); instead, we warn only + // for cases where the parser will give a parse tree differing from what React + // intended. For example, <b><div></div></b> is invalid but we don't warn + // because it still parses correctly; we do warn for other cases like nested + // <p> tags where the beginning of the second element implicitly closes the + // first, causing a confusing mess. + + // https://html.spec.whatwg.org/multipage/syntax.html#special + var specialTags = ['address', 'applet', 'area', 'article', 'aside', 'base', 'basefont', 'bgsound', 'blockquote', 'body', 'br', 'button', 'caption', 'center', 'col', 'colgroup', 'dd', 'details', 'dir', 'div', 'dl', 'dt', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'iframe', 'img', 'input', 'isindex', 'li', 'link', 'listing', 'main', 'marquee', 'menu', 'menuitem', 'meta', 'nav', 'noembed', 'noframes', 'noscript', 'object', 'ol', 'p', 'param', 'plaintext', 'pre', 'script', 'section', 'select', 'source', 'style', 'summary', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul', 'wbr', 'xmp']; + + // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope + var inScopeTags = ['applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', 'template', + + // https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point + // TODO: Distinguish by namespace here -- for <title>, including it here + // errs on the side of fewer warnings + 'foreignObject', 'desc', 'title']; + + // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope + var buttonScopeTags = inScopeTags.concat(['button']); + + // https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags + var impliedEndTags = ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt']; + + var emptyAncestorInfo = { + parentTag: null, + + formTag: null, + aTagInScope: null, + buttonTagInScope: null, + nobrTagInScope: null, + pTagInButtonScope: null, + + listItemTagAutoclosing: null, + dlItemTagAutoclosing: null + }; + + var updatedAncestorInfo = function (oldInfo, tag, instance) { + var ancestorInfo = assign({}, oldInfo || emptyAncestorInfo); + var info = { tag: tag, instance: instance }; + + if (inScopeTags.indexOf(tag) !== -1) { + ancestorInfo.aTagInScope = null; + ancestorInfo.buttonTagInScope = null; + ancestorInfo.nobrTagInScope = null; + } + if (buttonScopeTags.indexOf(tag) !== -1) { + ancestorInfo.pTagInButtonScope = null; + } + + // See rules for 'li', 'dd', 'dt' start tags in + // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody + if (specialTags.indexOf(tag) !== -1 && tag !== 'address' && tag !== 'div' && tag !== 'p') { + ancestorInfo.listItemTagAutoclosing = null; + ancestorInfo.dlItemTagAutoclosing = null; + } + + ancestorInfo.parentTag = info; + + if (tag === 'form') { + ancestorInfo.formTag = info; + } + if (tag === 'a') { + ancestorInfo.aTagInScope = info; + } + if (tag === 'button') { + ancestorInfo.buttonTagInScope = info; + } + if (tag === 'nobr') { + ancestorInfo.nobrTagInScope = info; + } + if (tag === 'p') { + ancestorInfo.pTagInButtonScope = info; + } + if (tag === 'li') { + ancestorInfo.listItemTagAutoclosing = info; + } + if (tag === 'dd' || tag === 'dt') { + ancestorInfo.dlItemTagAutoclosing = info; + } + + return ancestorInfo; + }; + + /** + * Returns whether + */ + var isTagValidWithParent = function (tag, parentTag) { + // First, let's check if we're in an unusual parsing mode... + switch (parentTag) { + // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect + case 'select': + return tag === 'option' || tag === 'optgroup' || tag === '#text'; + case 'optgroup': + return tag === 'option' || tag === '#text'; + // Strictly speaking, seeing an <option> doesn't mean we're in a <select> + // but + case 'option': + return tag === '#text'; + + // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd + // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption + // No special behavior since these rules fall back to "in body" mode for + // all except special table nodes which cause bad parsing behavior anyway. + + // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr + case 'tr': + return tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' || tag === 'template'; + + // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody + case 'tbody': + case 'thead': + case 'tfoot': + return tag === 'tr' || tag === 'style' || tag === 'script' || tag === 'template'; + + // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup + case 'colgroup': + return tag === 'col' || tag === 'template'; + + // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable + case 'table': + return tag === 'caption' || tag === 'colgroup' || tag === 'tbody' || tag === 'tfoot' || tag === 'thead' || tag === 'style' || tag === 'script' || tag === 'template'; + + // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead + case 'head': + return tag === 'base' || tag === 'basefont' || tag === 'bgsound' || tag === 'link' || tag === 'meta' || tag === 'title' || tag === 'noscript' || tag === 'noframes' || tag === 'style' || tag === 'script' || tag === 'template'; + + // https://html.spec.whatwg.org/multipage/semantics.html#the-html-element + case 'html': + return tag === 'head' || tag === 'body'; + } + + // Probably in the "in body" parsing mode, so we outlaw only tag combos + // where the parsing rules cause implicit opens or closes to be added. + // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody + switch (tag) { + case 'h1': + case 'h2': + case 'h3': + case 'h4': + case 'h5': + case 'h6': + return parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' && parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6'; + + case 'rp': + case 'rt': + return impliedEndTags.indexOf(parentTag) === -1; + + case 'caption': + case 'col': + case 'colgroup': + case 'frame': + case 'head': + case 'tbody': + case 'td': + case 'tfoot': + case 'th': + case 'thead': + case 'tr': + // These tags are only valid with a few parents that have special child + // parsing rules -- if we're down here, then none of those matched and + // so we allow it only if we don't know what the parent is, as all other + // cases are invalid. + return parentTag == null; + } + + return true; + }; + + /** + * Returns whether + */ + var findInvalidAncestorForTag = function (tag, ancestorInfo) { + switch (tag) { + case 'address': + case 'article': + case 'aside': + case 'blockquote': + case 'center': + case 'details': + case 'dialog': + case 'dir': + case 'div': + case 'dl': + case 'fieldset': + case 'figcaption': + case 'figure': + case 'footer': + case 'header': + case 'hgroup': + case 'main': + case 'menu': + case 'nav': + case 'ol': + case 'p': + case 'section': + case 'summary': + case 'ul': + + case 'pre': + case 'listing': + + case 'table': + + case 'hr': + + case 'xmp': + + case 'h1': + case 'h2': + case 'h3': + case 'h4': + case 'h5': + case 'h6': + return ancestorInfo.pTagInButtonScope; + + case 'form': + return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope; + + case 'li': + return ancestorInfo.listItemTagAutoclosing; + + case 'dd': + case 'dt': + return ancestorInfo.dlItemTagAutoclosing; + + case 'button': + return ancestorInfo.buttonTagInScope; + + case 'a': + // Spec says something about storing a list of markers, but it sounds + // equivalent to this check. + return ancestorInfo.aTagInScope; + + case 'nobr': + return ancestorInfo.nobrTagInScope; + } + + return null; + }; + + /** + * Given a ReactCompositeComponent instance, return a list of its recursive + * owners, starting at the root and ending with the instance itself. + */ + var findOwnerStack = function (instance) { + if (!instance) { + return []; + } + + var stack = []; + /*eslint-disable space-after-keywords */ + do { + /*eslint-enable space-after-keywords */ + stack.push(instance); + } while (instance = instance._currentElement._owner); + stack.reverse(); + return stack; + }; + + var didWarn = {}; + + validateDOMNesting = function (childTag, childInstance, ancestorInfo) { + ancestorInfo = ancestorInfo || emptyAncestorInfo; + var parentInfo = ancestorInfo.parentTag; + var parentTag = parentInfo && parentInfo.tag; + + var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo; + var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo); + var problematic = invalidParent || invalidAncestor; + + if (problematic) { + var ancestorTag = problematic.tag; + var ancestorInstance = problematic.instance; + + var childOwner = childInstance && childInstance._currentElement._owner; + var ancestorOwner = ancestorInstance && ancestorInstance._currentElement._owner; + + var childOwners = findOwnerStack(childOwner); + var ancestorOwners = findOwnerStack(ancestorOwner); + + var minStackLen = Math.min(childOwners.length, ancestorOwners.length); + var i; + + var deepestCommon = -1; + for (i = 0; i < minStackLen; i++) { + if (childOwners[i] === ancestorOwners[i]) { + deepestCommon = i; + } else { + break; + } + } + + var UNKNOWN = '(unknown)'; + var childOwnerNames = childOwners.slice(deepestCommon + 1).map(function (inst) { + return inst.getName() || UNKNOWN; + }); + var ancestorOwnerNames = ancestorOwners.slice(deepestCommon + 1).map(function (inst) { + return inst.getName() || UNKNOWN; + }); + var ownerInfo = [].concat( + // If the parent and child instances have a common owner ancestor, start + // with that -- otherwise we just start with the parent's owners. + deepestCommon !== -1 ? childOwners[deepestCommon].getName() || UNKNOWN : [], ancestorOwnerNames, ancestorTag, + // If we're warning about an invalid (non-parent) ancestry, add '...' + invalidAncestor ? ['...'] : [], childOwnerNames, childTag).join(' > '); + + var warnKey = !!invalidParent + '|' + childTag + '|' + ancestorTag + '|' + ownerInfo; + if (didWarn[warnKey]) { + return; + } + didWarn[warnKey] = true; + + if (invalidParent) { + var info = ''; + if (ancestorTag === 'table' && childTag === 'tr') { + info += ' Add a <tbody> to your code to match the DOM tree generated by ' + 'the browser.'; + } + "development" !== 'production' ? warning(false, 'validateDOMNesting(...): <%s> cannot appear as a child of <%s>. ' + 'See %s.%s', childTag, ancestorTag, ownerInfo, info) : undefined; + } else { + "development" !== 'production' ? warning(false, 'validateDOMNesting(...): <%s> cannot appear as a descendant of ' + '<%s>. See %s.', childTag, ancestorTag, ownerInfo) : undefined; + } + } + }; + + validateDOMNesting.ancestorInfoContextKey = '__validateDOMNesting_ancestorInfo$' + Math.random().toString(36).slice(2); + + validateDOMNesting.updatedAncestorInfo = updatedAncestorInfo; + + // For testing + validateDOMNesting.isTagValidInContext = function (tag, ancestorInfo) { + ancestorInfo = ancestorInfo || emptyAncestorInfo; + var parentInfo = ancestorInfo.parentTag; + var parentTag = parentInfo && parentInfo.tag; + return isTagValidWithParent(tag, parentTag) && !findInvalidAncestorForTag(tag, ancestorInfo); + }; +} + +module.exports = validateDOMNesting; +},{"153":153,"173":173,"24":24}],145:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule CSSCore + * @typechecks + */ + +'use strict'; + +var invariant = _dereq_(161); + +/** + * The CSSCore module specifies the API (and implements most of the methods) + * that should be used when dealing with the display of elements (via their + * CSS classes and visibility on screen. It is an API focused on mutating the + * display and not reading it as no logical state should be encoded in the + * display of elements. + */ + +var CSSCore = { + + /** + * Adds the class passed in to the element if it doesn't already have it. + * + * @param {DOMElement} element the element to set the class on + * @param {string} className the CSS className + * @return {DOMElement} the element passed in + */ + addClass: function (element, className) { + !!/\s/.test(className) ? "development" !== 'production' ? invariant(false, 'CSSCore.addClass takes only a single class name. "%s" contains ' + 'multiple classes.', className) : invariant(false) : undefined; + + if (className) { + if (element.classList) { + element.classList.add(className); + } else if (!CSSCore.hasClass(element, className)) { + element.className = element.className + ' ' + className; + } + } + return element; + }, + + /** + * Removes the class passed in from the element + * + * @param {DOMElement} element the element to set the class on + * @param {string} className the CSS className + * @return {DOMElement} the element passed in + */ + removeClass: function (element, className) { + !!/\s/.test(className) ? "development" !== 'production' ? invariant(false, 'CSSCore.removeClass takes only a single class name. "%s" contains ' + 'multiple classes.', className) : invariant(false) : undefined; + + if (className) { + if (element.classList) { + element.classList.remove(className); + } else if (CSSCore.hasClass(element, className)) { + element.className = element.className.replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)', 'g'), '$1').replace(/\s+/g, ' ') // multiple spaces to one + .replace(/^\s*|\s*$/g, ''); // trim the ends + } + } + return element; + }, + + /** + * Helper to add or remove a class from an element based on a condition. + * + * @param {DOMElement} element the element to set the class on + * @param {string} className the CSS className + * @param {*} bool condition to whether to add or remove the class + * @return {DOMElement} the element passed in + */ + conditionClass: function (element, className, bool) { + return (bool ? CSSCore.addClass : CSSCore.removeClass)(element, className); + }, + + /** + * Tests whether the element has the class specified. + * + * @param {DOMNode|DOMWindow} element the element to set the class on + * @param {string} className the CSS className + * @return {boolean} true if the element has the class, false if not + */ + hasClass: function (element, className) { + !!/\s/.test(className) ? "development" !== 'production' ? invariant(false, 'CSS.hasClass takes only a single class name.') : invariant(false) : undefined; + if (element.classList) { + return !!className && element.classList.contains(className); + } + return (' ' + element.className + ' ').indexOf(' ' + className + ' ') > -1; + } + +}; + +module.exports = CSSCore; +},{"161":161}],146:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * @providesModule EventListener + * @typechecks + */ + +'use strict'; + +var emptyFunction = _dereq_(153); + +/** + * Upstream version of event listener. Does not take into account specific + * nature of platform. + */ +var EventListener = { + /** + * Listen to DOM events during the bubble phase. + * + * @param {DOMEventTarget} target DOM element to register listener on. + * @param {string} eventType Event type, e.g. 'click' or 'mouseover'. + * @param {function} callback Callback function. + * @return {object} Object with a `remove` method. + */ + listen: function (target, eventType, callback) { + if (target.addEventListener) { + target.addEventListener(eventType, callback, false); + return { + remove: function () { + target.removeEventListener(eventType, callback, false); + } + }; + } else if (target.attachEvent) { + target.attachEvent('on' + eventType, callback); + return { + remove: function () { + target.detachEvent('on' + eventType, callback); + } + }; + } + }, + + /** + * Listen to DOM events during the capture phase. + * + * @param {DOMEventTarget} target DOM element to register listener on. + * @param {string} eventType Event type, e.g. 'click' or 'mouseover'. + * @param {function} callback Callback function. + * @return {object} Object with a `remove` method. + */ + capture: function (target, eventType, callback) { + if (target.addEventListener) { + target.addEventListener(eventType, callback, true); + return { + remove: function () { + target.removeEventListener(eventType, callback, true); + } + }; + } else { + if ("development" !== 'production') { + console.error('Attempted to listen to events during the capture phase on a ' + 'browser that does not support the capture phase. Your application ' + 'will not receive some events.'); + } + return { + remove: emptyFunction + }; + } + }, + + registerDefault: function () {} +}; + +module.exports = EventListener; +},{"153":153}],147:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ExecutionEnvironment + */ + +'use strict'; + +var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement); + +/** + * Simple, lightweight module assisting with the detection and context of + * Worker. Helps avoid circular dependencies and allows code to reason about + * whether or not they are in a Worker, even if they never include the main + * `ReactWorker` dependency. + */ +var ExecutionEnvironment = { + + canUseDOM: canUseDOM, + + canUseWorkers: typeof Worker !== 'undefined', + + canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent), + + canUseViewport: canUseDOM && !!window.screen, + + isInWorker: !canUseDOM // For now, this is true - might change in the future. + +}; + +module.exports = ExecutionEnvironment; +},{}],148:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule camelize + * @typechecks + */ + +"use strict"; + +var _hyphenPattern = /-(.)/g; + +/** + * Camelcases a hyphenated string, for example: + * + * > camelize('background-color') + * < "backgroundColor" + * + * @param {string} string + * @return {string} + */ +function camelize(string) { + return string.replace(_hyphenPattern, function (_, character) { + return character.toUpperCase(); + }); +} + +module.exports = camelize; +},{}],149:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule camelizeStyleName + * @typechecks + */ + +'use strict'; + +var camelize = _dereq_(148); + +var msPattern = /^-ms-/; + +/** + * Camelcases a hyphenated CSS property name, for example: + * + * > camelizeStyleName('background-color') + * < "backgroundColor" + * > camelizeStyleName('-moz-transition') + * < "MozTransition" + * > camelizeStyleName('-ms-transition') + * < "msTransition" + * + * As Andi Smith suggests + * (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix + * is converted to lowercase `ms`. + * + * @param {string} string + * @return {string} + */ +function camelizeStyleName(string) { + return camelize(string.replace(msPattern, 'ms-')); +} + +module.exports = camelizeStyleName; +},{"148":148}],150:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule containsNode + * @typechecks + */ + +'use strict'; + +var isTextNode = _dereq_(163); + +/*eslint-disable no-bitwise */ + +/** + * Checks if a given DOM node contains or is another DOM node. + * + * @param {?DOMNode} outerNode Outer DOM node. + * @param {?DOMNode} innerNode Inner DOM node. + * @return {boolean} True if `outerNode` contains or is `innerNode`. + */ +function containsNode(_x, _x2) { + var _again = true; + + _function: while (_again) { + var outerNode = _x, + innerNode = _x2; + _again = false; + + if (!outerNode || !innerNode) { + return false; + } else if (outerNode === innerNode) { + return true; + } else if (isTextNode(outerNode)) { + return false; + } else if (isTextNode(innerNode)) { + _x = outerNode; + _x2 = innerNode.parentNode; + _again = true; + continue _function; + } else if (outerNode.contains) { + return outerNode.contains(innerNode); + } else if (outerNode.compareDocumentPosition) { + return !!(outerNode.compareDocumentPosition(innerNode) & 16); + } else { + return false; + } + } +} + +module.exports = containsNode; +},{"163":163}],151:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule createArrayFromMixed + * @typechecks + */ + +'use strict'; + +var toArray = _dereq_(172); + +/** + * Perform a heuristic test to determine if an object is "array-like". + * + * A monk asked Joshu, a Zen master, "Has a dog Buddha nature?" + * Joshu replied: "Mu." + * + * This function determines if its argument has "array nature": it returns + * true if the argument is an actual array, an `arguments' object, or an + * HTMLCollection (e.g. node.childNodes or node.getElementsByTagName()). + * + * It will return false for other array-like objects like Filelist. + * + * @param {*} obj + * @return {boolean} + */ +function hasArrayNature(obj) { + return( + // not null/false + !!obj && ( + // arrays are objects, NodeLists are functions in Safari + typeof obj == 'object' || typeof obj == 'function') && + // quacks like an array + 'length' in obj && + // not window + !('setInterval' in obj) && + // no DOM node should be considered an array-like + // a 'select' element has 'length' and 'item' properties on IE8 + typeof obj.nodeType != 'number' && ( + // a real array + Array.isArray(obj) || + // arguments + 'callee' in obj || + // HTMLCollection/NodeList + 'item' in obj) + ); +} + +/** + * Ensure that the argument is an array by wrapping it in an array if it is not. + * Creates a copy of the argument if it is already an array. + * + * This is mostly useful idiomatically: + * + * var createArrayFromMixed = require('createArrayFromMixed'); + * + * function takesOneOrMoreThings(things) { + * things = createArrayFromMixed(things); + * ... + * } + * + * This allows you to treat `things' as an array, but accept scalars in the API. + * + * If you need to convert an array-like object, like `arguments`, into an array + * use toArray instead. + * + * @param {*} obj + * @return {array} + */ +function createArrayFromMixed(obj) { + if (!hasArrayNature(obj)) { + return [obj]; + } else if (Array.isArray(obj)) { + return obj.slice(); + } else { + return toArray(obj); + } +} + +module.exports = createArrayFromMixed; +},{"172":172}],152:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule createNodesFromMarkup + * @typechecks + */ + +/*eslint-disable fb-www/unsafe-html*/ + +'use strict'; + +var ExecutionEnvironment = _dereq_(147); + +var createArrayFromMixed = _dereq_(151); +var getMarkupWrap = _dereq_(157); +var invariant = _dereq_(161); + +/** + * Dummy container used to render all markup. + */ +var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElementNS('http://www.w3.org/1999/xhtml', 'div') : null; + +/** + * Pattern used by `getNodeName`. + */ +var nodeNamePattern = /^\s*<(\w+)/; + +/** + * Extracts the `nodeName` of the first element in a string of markup. + * + * @param {string} markup String of markup. + * @return {?string} Node name of the supplied markup. + */ +function getNodeName(markup) { + var nodeNameMatch = markup.match(nodeNamePattern); + return nodeNameMatch && nodeNameMatch[1].toLowerCase(); +} + +/** + * Creates an array containing the nodes rendered from the supplied markup. The + * optionally supplied `handleScript` function will be invoked once for each + * <script> element that is rendered. If no `handleScript` function is supplied, + * an exception is thrown if any <script> elements are rendered. + * + * @param {string} markup A string of valid HTML markup. + * @param {?function} handleScript Invoked once for each rendered <script>. + * @return {array<DOMElement|DOMTextNode>} An array of rendered nodes. + */ +function createNodesFromMarkup(markup, handleScript) { + var node = dummyNode; + !!!dummyNode ? "development" !== 'production' ? invariant(false, 'createNodesFromMarkup dummy not initialized') : invariant(false) : undefined; + var nodeName = getNodeName(markup); + + var wrap = nodeName && getMarkupWrap(nodeName); + if (wrap) { + node.innerHTML = wrap[1] + markup + wrap[2]; + + var wrapDepth = wrap[0]; + while (wrapDepth--) { + node = node.lastChild; + } + } else { + node.innerHTML = markup; + } + + var scripts = node.getElementsByTagName('script'); + if (scripts.length) { + !handleScript ? "development" !== 'production' ? invariant(false, 'createNodesFromMarkup(...): Unexpected <script> element rendered.') : invariant(false) : undefined; + createArrayFromMixed(scripts).forEach(handleScript); + } + + var nodes = createArrayFromMixed(node.childNodes); + while (node.lastChild) { + node.removeChild(node.lastChild); + } + return nodes; +} + +module.exports = createNodesFromMarkup; + +},{"147":147,"151":151,"157":157,"161":161}],153:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule emptyFunction + */ + +"use strict"; + +function makeEmptyFunction(arg) { + return function () { + return arg; + }; +} + +/** + * This function accepts and discards inputs; it has no side effects. This is + * primarily useful idiomatically for overridable function endpoints which + * always need to be callable, since JS lacks a null-call idiom ala Cocoa. + */ +function emptyFunction() {} + +emptyFunction.thatReturns = makeEmptyFunction; +emptyFunction.thatReturnsFalse = makeEmptyFunction(false); +emptyFunction.thatReturnsTrue = makeEmptyFunction(true); +emptyFunction.thatReturnsNull = makeEmptyFunction(null); +emptyFunction.thatReturnsThis = function () { + return this; +}; +emptyFunction.thatReturnsArgument = function (arg) { + return arg; +}; + +module.exports = emptyFunction; +},{}],154:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule emptyObject + */ + +'use strict'; + +var emptyObject = {}; + +if ("development" !== 'production') { + Object.freeze(emptyObject); +} + +module.exports = emptyObject; +},{}],155:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule focusNode + */ + +'use strict'; + +/** + * @param {DOMElement} node input/textarea to focus + */ +function focusNode(node) { + // IE8 can throw "Can't move focus to the control because it is invisible, + // not enabled, or of a type that does not accept the focus." for all kinds of + // reasons that are too expensive and fragile to test. + try { + node.focus(); + } catch (e) {} +} + +module.exports = focusNode; +},{}],156:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule getActiveElement + * @typechecks + */ + +/* eslint-disable fb-www/typeof-undefined */ + +/** + * Same as document.activeElement but wraps in a try-catch block. In IE it is + * not safe to call document.activeElement if there is nothing focused. + * + * The activeElement will be null only if the document or document body is not + * yet defined. + */ +'use strict'; + +function getActiveElement() /*?DOMElement*/{ + if (typeof document === 'undefined') { + return null; + } + try { + return document.activeElement || document.body; + } catch (e) { + return document.body; + } +} + +module.exports = getActiveElement; +},{}],157:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule getMarkupWrap + */ + +/*eslint-disable fb-www/unsafe-html */ + +'use strict'; + +var ExecutionEnvironment = _dereq_(147); + +var invariant = _dereq_(161); + +/** + * Dummy container used to detect which wraps are necessary. + */ +var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElementNS('http://www.w3.org/1999/xhtml', 'div') : null; + +/** + * Some browsers cannot use `innerHTML` to render certain elements standalone, + * so we wrap them, render the wrapped nodes, then extract the desired node. + * + * In IE8, certain elements cannot render alone, so wrap all elements ('*'). + */ + +var shouldWrap = {}; + +var selectWrap = [1, '<select multiple="true">', '</select>']; +var tableWrap = [1, '<table>', '</table>']; +var trWrap = [3, '<table><tbody><tr>', '</tr></tbody></table>']; + +var svgWrap = [1, '<svg xmlns="http://www.w3.org/2000/svg">', '</svg>']; + +var markupWrap = { + '*': [1, '?<div>', '</div>'], + + 'area': [1, '<map>', '</map>'], + 'col': [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'], + 'legend': [1, '<fieldset>', '</fieldset>'], + 'param': [1, '<object>', '</object>'], + 'tr': [2, '<table><tbody>', '</tbody></table>'], + + 'optgroup': selectWrap, + 'option': selectWrap, + + 'caption': tableWrap, + 'colgroup': tableWrap, + 'tbody': tableWrap, + 'tfoot': tableWrap, + 'thead': tableWrap, + + 'td': trWrap, + 'th': trWrap +}; + +// Initialize the SVG elements since we know they'll always need to be wrapped +// consistently. If they are created inside a <div> they will be initialized in +// the wrong namespace (and will not display). +var svgElements = ['circle', 'clipPath', 'defs', 'ellipse', 'g', 'image', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'text', 'tspan']; +svgElements.forEach(function (nodeName) { + markupWrap[nodeName] = svgWrap; + shouldWrap[nodeName] = true; +}); + +/** + * Gets the markup wrap configuration for the supplied `nodeName`. + * + * NOTE: This lazily detects which wraps are necessary for the current browser. + * + * @param {string} nodeName Lowercase `nodeName`. + * @return {?array} Markup wrap configuration, if applicable. + */ +function getMarkupWrap(nodeName) { + !!!dummyNode ? "development" !== 'production' ? invariant(false, 'Markup wrapping node not initialized') : invariant(false) : undefined; + if (!markupWrap.hasOwnProperty(nodeName)) { + nodeName = '*'; + } + if (!shouldWrap.hasOwnProperty(nodeName)) { + if (nodeName === '*') { + dummyNode.innerHTML = '<link />'; + } else { + dummyNode.innerHTML = '<' + nodeName + '></' + nodeName + '>'; + } + shouldWrap[nodeName] = !dummyNode.firstChild; + } + return shouldWrap[nodeName] ? markupWrap[nodeName] : null; +} + +module.exports = getMarkupWrap; +},{"147":147,"161":161}],158:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule getUnboundedScrollPosition + * @typechecks + */ + +'use strict'; + +/** + * Gets the scroll position of the supplied element or window. + * + * The return values are unbounded, unlike `getScrollPosition`. This means they + * may be negative or exceed the element boundaries (which is possible using + * inertial scrolling). + * + * @param {DOMWindow|DOMElement} scrollable + * @return {object} Map with `x` and `y` keys. + */ +function getUnboundedScrollPosition(scrollable) { + if (scrollable === window) { + return { + x: window.pageXOffset || document.documentElement.scrollLeft, + y: window.pageYOffset || document.documentElement.scrollTop + }; + } + return { + x: scrollable.scrollLeft, + y: scrollable.scrollTop + }; +} + +module.exports = getUnboundedScrollPosition; +},{}],159:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule hyphenate + * @typechecks + */ + +'use strict'; + +var _uppercasePattern = /([A-Z])/g; + +/** + * Hyphenates a camelcased string, for example: + * + * > hyphenate('backgroundColor') + * < "background-color" + * + * For CSS style names, use `hyphenateStyleName` instead which works properly + * with all vendor prefixes, including `ms`. + * + * @param {string} string + * @return {string} + */ +function hyphenate(string) { + return string.replace(_uppercasePattern, '-$1').toLowerCase(); +} + +module.exports = hyphenate; +},{}],160:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule hyphenateStyleName + * @typechecks + */ + +'use strict'; + +var hyphenate = _dereq_(159); + +var msPattern = /^ms-/; + +/** + * Hyphenates a camelcased CSS property name, for example: + * + * > hyphenateStyleName('backgroundColor') + * < "background-color" + * > hyphenateStyleName('MozTransition') + * < "-moz-transition" + * > hyphenateStyleName('msTransition') + * < "-ms-transition" + * + * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix + * is converted to `-ms-`. + * + * @param {string} string + * @return {string} + */ +function hyphenateStyleName(string) { + return hyphenate(string).replace(msPattern, '-ms-'); +} + +module.exports = hyphenateStyleName; +},{"159":159}],161:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule invariant + */ + +'use strict'; + +/** + * Use invariant() to assert state which your program assumes to be true. + * + * Provide sprintf-style format (only %s is supported) and arguments + * to provide information about what broke and what you were + * expecting. + * + * The invariant message will be stripped in production, but the invariant + * will remain to ensure logic does not differ in production. + */ + +function invariant(condition, format, a, b, c, d, e, f) { + if ("development" !== 'production') { + if (format === undefined) { + throw new Error('invariant requires an error message argument'); + } + } + + if (!condition) { + var error; + if (format === undefined) { + error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); + } else { + var args = [a, b, c, d, e, f]; + var argIndex = 0; + error = new Error(format.replace(/%s/g, function () { + return args[argIndex++]; + })); + error.name = 'Invariant Violation'; + } + + error.framesToPop = 1; // we don't care about invariant's own frame + throw error; + } +} + +module.exports = invariant; +},{}],162:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule isNode + * @typechecks + */ + +/** + * @param {*} object The object to check. + * @return {boolean} Whether or not the object is a DOM node. + */ +'use strict'; + +function isNode(object) { + return !!(object && (typeof Node === 'function' ? object instanceof Node : typeof object === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string')); +} + +module.exports = isNode; +},{}],163:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule isTextNode + * @typechecks + */ + +'use strict'; + +var isNode = _dereq_(162); + +/** + * @param {*} object The object to check. + * @return {boolean} Whether or not the object is a DOM text node. + */ +function isTextNode(object) { + return isNode(object) && object.nodeType == 3; +} + +module.exports = isTextNode; +},{"162":162}],164:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule joinClasses + * @typechecks static-only + */ + +'use strict'; + +/** + * Combines multiple className strings into one. + * http://jsperf.com/joinclasses-args-vs-array + * + * @param {...?string} className + * @return {string} + */ +function joinClasses(className /*, ... */) { + if (!className) { + className = ''; + } + var nextClass; + var argLength = arguments.length; + if (argLength > 1) { + for (var ii = 1; ii < argLength; ii++) { + nextClass = arguments[ii]; + if (nextClass) { + className = (className ? className + ' ' : '') + nextClass; + } + } + } + return className; +} + +module.exports = joinClasses; +},{}],165:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule keyMirror + * @typechecks static-only + */ + +'use strict'; + +var invariant = _dereq_(161); + +/** + * Constructs an enumeration with keys equal to their value. + * + * For example: + * + * var COLORS = keyMirror({blue: null, red: null}); + * var myColor = COLORS.blue; + * var isColorValid = !!COLORS[myColor]; + * + * The last line could not be performed if the values of the generated enum were + * not equal to their keys. + * + * Input: {key1: val1, key2: val2} + * Output: {key1: key1, key2: key2} + * + * @param {object} obj + * @return {object} + */ +var keyMirror = function (obj) { + var ret = {}; + var key; + !(obj instanceof Object && !Array.isArray(obj)) ? "development" !== 'production' ? invariant(false, 'keyMirror(...): Argument must be an object.') : invariant(false) : undefined; + for (key in obj) { + if (!obj.hasOwnProperty(key)) { + continue; + } + ret[key] = key; + } + return ret; +}; + +module.exports = keyMirror; +},{"161":161}],166:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule keyOf + */ + +/** + * Allows extraction of a minified key. Let's the build system minify keys + * without losing the ability to dynamically use key strings as values + * themselves. Pass in an object with a single key/val pair and it will return + * you the string key of that single record. Suppose you want to grab the + * value for a key 'className' inside of an object. Key/val minification may + * have aliased that key to be 'xa12'. keyOf({className: null}) will return + * 'xa12' in that case. Resolve keys you want to use once at startup time, then + * reuse those resolutions. + */ +"use strict"; + +var keyOf = function (oneKeyObj) { + var key; + for (key in oneKeyObj) { + if (!oneKeyObj.hasOwnProperty(key)) { + continue; + } + return key; + } + return null; +}; + +module.exports = keyOf; +},{}],167:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule mapObject + */ + +'use strict'; + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +/** + * Executes the provided `callback` once for each enumerable own property in the + * object and constructs a new object from the results. The `callback` is + * invoked with three arguments: + * + * - the property value + * - the property name + * - the object being traversed + * + * Properties that are added after the call to `mapObject` will not be visited + * by `callback`. If the values of existing properties are changed, the value + * passed to `callback` will be the value at the time `mapObject` visits them. + * Properties that are deleted before being visited are not visited. + * + * @grep function objectMap() + * @grep function objMap() + * + * @param {?object} object + * @param {function} callback + * @param {*} context + * @return {?object} + */ +function mapObject(object, callback, context) { + if (!object) { + return null; + } + var result = {}; + for (var name in object) { + if (hasOwnProperty.call(object, name)) { + result[name] = callback.call(context, object[name], name, object); + } + } + return result; +} + +module.exports = mapObject; +},{}],168:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule memoizeStringOnly + * @typechecks static-only + */ + +'use strict'; + +/** + * Memoizes the return value of a function that accepts one string argument. + * + * @param {function} callback + * @return {function} + */ +function memoizeStringOnly(callback) { + var cache = {}; + return function (string) { + if (!cache.hasOwnProperty(string)) { + cache[string] = callback.call(this, string); + } + return cache[string]; + }; +} + +module.exports = memoizeStringOnly; +},{}],169:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule performance + * @typechecks + */ + +'use strict'; + +var ExecutionEnvironment = _dereq_(147); + +var performance; + +if (ExecutionEnvironment.canUseDOM) { + performance = window.performance || window.msPerformance || window.webkitPerformance; +} + +module.exports = performance || {}; +},{"147":147}],170:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule performanceNow + * @typechecks + */ + +'use strict'; + +var performance = _dereq_(169); + +var performanceNow; + +/** + * Detect if we can use `window.performance.now()` and gracefully fallback to + * `Date.now()` if it doesn't exist. We need to support Firefox < 15 for now + * because of Facebook's testing infrastructure. + */ +if (performance.now) { + performanceNow = function () { + return performance.now(); + }; +} else { + performanceNow = function () { + return Date.now(); + }; +} + +module.exports = performanceNow; +},{"169":169}],171:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule shallowEqual + * @typechecks + * + */ + +'use strict'; + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +/** + * Performs equality by iterating through keys on an object and returning false + * when any key has values which are not strictly equal between the arguments. + * Returns true when the values of all keys are strictly equal. + */ +function shallowEqual(objA, objB) { + if (objA === objB) { + return true; + } + + if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) { + return false; + } + + var keysA = Object.keys(objA); + var keysB = Object.keys(objB); + + if (keysA.length !== keysB.length) { + return false; + } + + // Test for A's keys different from B. + var bHasOwnProperty = hasOwnProperty.bind(objB); + for (var i = 0; i < keysA.length; i++) { + if (!bHasOwnProperty(keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) { + return false; + } + } + + return true; +} + +module.exports = shallowEqual; +},{}],172:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule toArray + * @typechecks + */ + +'use strict'; + +var invariant = _dereq_(161); + +/** + * Convert array-like objects to arrays. + * + * This API assumes the caller knows the contents of the data type. For less + * well defined inputs use createArrayFromMixed. + * + * @param {object|function|filelist} obj + * @return {array} + */ +function toArray(obj) { + var length = obj.length; + + // Some browse builtin objects can report typeof 'function' (e.g. NodeList in + // old versions of Safari). + !(!Array.isArray(obj) && (typeof obj === 'object' || typeof obj === 'function')) ? "development" !== 'production' ? invariant(false, 'toArray: Array-like object expected') : invariant(false) : undefined; + + !(typeof length === 'number') ? "development" !== 'production' ? invariant(false, 'toArray: Object needs a length property') : invariant(false) : undefined; + + !(length === 0 || length - 1 in obj) ? "development" !== 'production' ? invariant(false, 'toArray: Object should have keys for indices') : invariant(false) : undefined; + + // Old IE doesn't give collections access to hasOwnProperty. Assume inputs + // without method will throw during the slice call and skip straight to the + // fallback. + if (obj.hasOwnProperty) { + try { + return Array.prototype.slice.call(obj); + } catch (e) { + // IE < 9 does not support Array#slice on collections objects + } + } + + // Fall back to copying key by key. This assumes all keys have a value, + // so will not preserve sparsely populated inputs. + var ret = Array(length); + for (var ii = 0; ii < length; ii++) { + ret[ii] = obj[ii]; + } + return ret; +} + +module.exports = toArray; +},{"161":161}],173:[function(_dereq_,module,exports){ +/** + * Copyright 2014-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule warning + */ + +'use strict'; + +var emptyFunction = _dereq_(153); + +/** + * Similar to invariant but only logs a warning if the condition is not met. + * This can be used to log issues in development environments in critical + * paths. Removing the logging code for production environments will keep the + * same logic and follow the same code paths. + */ + +var warning = emptyFunction; + +if ("development" !== 'production') { + warning = function (condition, format) { + for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { + args[_key - 2] = arguments[_key]; + } + + if (format === undefined) { + throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument'); + } + + if (format.indexOf('Failed Composite propType: ') === 0) { + return; // Ignore CompositeComponent proptype check. + } + + if (!condition) { + var argIndex = 0; + var message = 'Warning: ' + format.replace(/%s/g, function () { + return args[argIndex++]; + }); + if (typeof console !== 'undefined') { + console.error(message); + } + try { + // --- Welcome to debugging React --- + // This error was thrown as a convenience so that you can use this stack + // to find the callsite that caused this warning to fire. + throw new Error(message); + } catch (x) {} + } + }; +} + +module.exports = warning; +},{"153":153}]},{},[1])(1) +}); diff --git a/devtools/client/shared/vendor/react-dom.js b/devtools/client/shared/vendor/react-dom.js new file mode 100644 index 000000000..f7c77bd90 --- /dev/null +++ b/devtools/client/shared/vendor/react-dom.js @@ -0,0 +1,42 @@ +/** + * ReactDOM v0.14.1 + * + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ +// Based off https://github.com/ForbesLindesay/umd/blob/master/template.js +;(function(f) { + // CommonJS + if (typeof exports === "object" && typeof module !== "undefined") { + module.exports = f(require('devtools/client/shared/vendor/react')); + + // RequireJS + } else if (typeof define === "function" && define.amd) { + define(['devtools/client/shared/vendor/react'], f); + + // <script> + } else { + var g + if (typeof window !== "undefined") { + g = window; + } else if (typeof global !== "undefined") { + g = global; + } else if (typeof self !== "undefined") { + g = self; + } else { + // works providing we're not in "use strict"; + // needed for Java 8 Nashorn + // see https://github.com/facebook/react/issues/3037 + g = this; + } + g.ReactDOM = f(g.React); + } + +})(function(React) { + return React.__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; +}); diff --git a/devtools/client/shared/vendor/react-proxy.js b/devtools/client/shared/vendor/react-proxy.js new file mode 100644 index 000000000..95346a026 --- /dev/null +++ b/devtools/client/shared/vendor/react-proxy.js @@ -0,0 +1,1909 @@ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define(factory); + else if(typeof exports === 'object') + exports["ReactProxy"] = factory(); + else + root["ReactProxy"] = factory(); +})(this, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; +/******/ +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ exports: {}, +/******/ id: moduleId, +/******/ loaded: false +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.loaded = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + Object.defineProperty(exports, '__esModule', { + value: true + }); + + function _interopRequire(obj) { return obj && obj.__esModule ? obj['default'] : obj; } + + var _createClassProxy = __webpack_require__(12); + + exports.createProxy = _interopRequire(_createClassProxy); + + var _reactDeepForceUpdate = __webpack_require__(39); + + exports.getForceUpdate = _interopRequire(_reactDeepForceUpdate); + +/***/ }, +/* 1 */ +/***/ function(module, exports, __webpack_require__) { + + /** + * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. + * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(1); + * // => false + */ + function isObject(value) { + // Avoid a V8 JIT bug in Chrome 19-20. + // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); + } + + module.exports = isObject; + + +/***/ }, +/* 2 */ +/***/ function(module, exports, __webpack_require__) { + + var getLength = __webpack_require__(30), + isLength = __webpack_require__(5); + + /** + * Checks if `value` is array-like. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + */ + function isArrayLike(value) { + return value != null && isLength(getLength(value)); + } + + module.exports = isArrayLike; + + +/***/ }, +/* 3 */ +/***/ function(module, exports, __webpack_require__) { + + /** + * Checks if `value` is object-like. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + */ + function isObjectLike(value) { + return !!value && typeof value == 'object'; + } + + module.exports = isObjectLike; + + +/***/ }, +/* 4 */ +/***/ function(module, exports, __webpack_require__) { + + var isNative = __webpack_require__(35); + + /** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ + function getNative(object, key) { + var value = object == null ? undefined : object[key]; + return isNative(value) ? value : undefined; + } + + module.exports = getNative; + + +/***/ }, +/* 5 */ +/***/ function(module, exports, __webpack_require__) { + + /** + * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer) + * of an array-like value. + */ + var MAX_SAFE_INTEGER = 9007199254740991; + + /** + * Checks if `value` is a valid array-like length. + * + * **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength). + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + */ + function isLength(value) { + return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; + } + + module.exports = isLength; + + +/***/ }, +/* 6 */ +/***/ function(module, exports, __webpack_require__) { + + /** Used to detect unsigned integer values. */ + var reIsUint = /^\d+$/; + + /** + * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer) + * of an array-like value. + */ + var MAX_SAFE_INTEGER = 9007199254740991; + + /** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ + function isIndex(value, length) { + value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1; + length = length == null ? MAX_SAFE_INTEGER : length; + return value > -1 && value % 1 == 0 && value < length; + } + + module.exports = isIndex; + + +/***/ }, +/* 7 */ +/***/ function(module, exports, __webpack_require__) { + + var isArrayLike = __webpack_require__(2), + isObjectLike = __webpack_require__(3); + + /** Used for native method references. */ + var objectProto = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty = objectProto.hasOwnProperty; + + /** Native method references. */ + var propertyIsEnumerable = objectProto.propertyIsEnumerable; + + /** + * Checks if `value` is classified as an `arguments` object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ + function isArguments(value) { + return isObjectLike(value) && isArrayLike(value) && + hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); + } + + module.exports = isArguments; + + +/***/ }, +/* 8 */ +/***/ function(module, exports, __webpack_require__) { + + var getNative = __webpack_require__(4), + isLength = __webpack_require__(5), + isObjectLike = __webpack_require__(3); + + /** `Object#toString` result references. */ + var arrayTag = '[object Array]'; + + /** Used for native method references. */ + var objectProto = Object.prototype; + + /** + * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) + * of values. + */ + var objToString = objectProto.toString; + + /* Native method references for those with the same name as other `lodash` methods. */ + var nativeIsArray = getNative(Array, 'isArray'); + + /** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(function() { return arguments; }()); + * // => false + */ + var isArray = nativeIsArray || function(value) { + return isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag; + }; + + module.exports = isArray; + + +/***/ }, +/* 9 */ +/***/ function(module, exports, __webpack_require__) { + + /** Used as the `TypeError` message for "Functions" methods. */ + var FUNC_ERROR_TEXT = 'Expected a function'; + + /* Native method references for those with the same name as other `lodash` methods. */ + var nativeMax = Math.max; + + /** + * Creates a function that invokes `func` with the `this` binding of the + * created function and arguments from `start` and beyond provided as an array. + * + * **Note:** This method is based on the [rest parameter](https://developer.mozilla.org/Web/JavaScript/Reference/Functions/rest_parameters). + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + * @example + * + * var say = _.restParam(function(what, names) { + * return what + ' ' + _.initial(names).join(', ') + + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); + * }); + * + * say('hello', 'fred', 'barney', 'pebbles'); + * // => 'hello fred, barney, & pebbles' + */ + function restParam(func, start) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + start = nativeMax(start === undefined ? (func.length - 1) : (+start || 0), 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + rest = Array(length); + + while (++index < length) { + rest[index] = args[start + index]; + } + switch (start) { + case 0: return func.call(this, rest); + case 1: return func.call(this, args[0], rest); + case 2: return func.call(this, args[0], args[1], rest); + } + var otherArgs = Array(start + 1); + index = -1; + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = rest; + return func.apply(this, otherArgs); + }; + } + + module.exports = restParam; + + +/***/ }, +/* 10 */ +/***/ function(module, exports, __webpack_require__) { + + var getNative = __webpack_require__(4), + isArrayLike = __webpack_require__(2), + isObject = __webpack_require__(1), + shimKeys = __webpack_require__(33); + + /* Native method references for those with the same name as other `lodash` methods. */ + var nativeKeys = getNative(Object, 'keys'); + + /** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys) + * for more details. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ + var keys = !nativeKeys ? shimKeys : function(object) { + var Ctor = object == null ? undefined : object.constructor; + if ((typeof Ctor == 'function' && Ctor.prototype === object) || + (typeof object != 'function' && isArrayLike(object))) { + return shimKeys(object); + } + return isObject(object) ? nativeKeys(object) : []; + }; + + module.exports = keys; + + +/***/ }, +/* 11 */ +/***/ function(module, exports, __webpack_require__) { + + /** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of React source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * Original: + * https://github.com/facebook/react/blob/6508b1ad273a6f371e8d90ae676e5390199461b4/src/isomorphic/classic/class/ReactClass.js#L650-L713 + */ + + 'use strict'; + + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports['default'] = bindAutoBindMethods; + function bindAutoBindMethod(component, method) { + var boundMethod = method.bind(component); + + boundMethod.__reactBoundContext = component; + boundMethod.__reactBoundMethod = method; + boundMethod.__reactBoundArguments = null; + + var componentName = component.constructor.displayName, + _bind = boundMethod.bind; + + boundMethod.bind = function (newThis) { + var args = Array.prototype.slice.call(arguments, 1); + if (newThis !== component && newThis !== null) { + console.warn('bind(): React component methods may only be bound to the ' + 'component instance. See ' + componentName); + } else if (!args.length) { + console.warn('bind(): You are binding a component method to the component. ' + 'React does this for you automatically in a high-performance ' + 'way, so you can safely remove this call. See ' + componentName); + return boundMethod; + } + + var reboundMethod = _bind.apply(boundMethod, arguments); + reboundMethod.__reactBoundContext = component; + reboundMethod.__reactBoundMethod = method; + reboundMethod.__reactBoundArguments = args; + + return reboundMethod; + }; + + return boundMethod; + } + + function bindAutoBindMethods(component) { + for (var autoBindKey in component.__reactAutoBindMap) { + if (!component.__reactAutoBindMap.hasOwnProperty(autoBindKey)) { + return; + } + + // Tweak: skip methods that are already bound. + // This is to preserve method reference in case it is used + // as a subscription handler that needs to be detached later. + if (component.hasOwnProperty(autoBindKey) && component[autoBindKey].__reactBoundContext === component) { + continue; + } + + var method = component.__reactAutoBindMap[autoBindKey]; + component[autoBindKey] = bindAutoBindMethod(component, method); + } + } + + ; + module.exports = exports['default']; + +/***/ }, +/* 12 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + Object.defineProperty(exports, '__esModule', { + value: true + }); + + var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; + + exports['default'] = proxyClass; + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + + var _createPrototypeProxy = __webpack_require__(13); + + var _createPrototypeProxy2 = _interopRequireDefault(_createPrototypeProxy); + + var _bindAutoBindMethods = __webpack_require__(11); + + var _bindAutoBindMethods2 = _interopRequireDefault(_bindAutoBindMethods); + + var _deleteUnknownAutoBindMethods = __webpack_require__(14); + + var _deleteUnknownAutoBindMethods2 = _interopRequireDefault(_deleteUnknownAutoBindMethods); + + var RESERVED_STATICS = ['length', 'name', 'arguments', 'caller', 'prototype', 'toString']; + + function isEqualDescriptor(a, b) { + if (!a && !b) { + return true; + } + if (!a || !b) { + return false; + } + for (var key in a) { + if (a[key] !== b[key]) { + return false; + } + } + return true; + } + + function proxyClass(InitialClass) { + // Prevent double wrapping. + // Given a proxy class, return the existing proxy managing it. + if (Object.prototype.hasOwnProperty.call(InitialClass, '__reactPatchProxy')) { + return InitialClass.__reactPatchProxy; + } + + var prototypeProxy = (0, _createPrototypeProxy2['default'])(); + var CurrentClass = undefined; + + var staticDescriptors = {}; + function wasStaticModifiedByUser(key) { + // Compare the descriptor with the one we previously set ourselves. + var currentDescriptor = Object.getOwnPropertyDescriptor(ProxyClass, key); + return !isEqualDescriptor(staticDescriptors[key], currentDescriptor); + } + + var ProxyClass = undefined; + try { + // Create a proxy constructor with matching name + ProxyClass = new Function('getCurrentClass', 'return function ' + (InitialClass.name || 'ProxyClass') + '() {\n return getCurrentClass().apply(this, arguments);\n }')(function () { + return CurrentClass; + }); + } catch (err) { + // Some environments may forbid dynamic evaluation + ProxyClass = function () { + return CurrentClass.apply(this, arguments); + }; + } + + // Point proxy constructor to the proxy prototype + ProxyClass.prototype = prototypeProxy.get(); + + // Proxy toString() to the current constructor + ProxyClass.toString = function toString() { + return CurrentClass.toString(); + }; + + function update(_x) { + var _again = true; + + _function: while (_again) { + var NextClass = _x; + mountedInstances = undefined; + _again = false; + + if (typeof NextClass !== 'function') { + throw new Error('Expected a constructor.'); + } + + // Prevent proxy cycles + if (Object.prototype.hasOwnProperty.call(NextClass, '__reactPatchProxy')) { + _x = NextClass.__reactPatchProxy.__getCurrent(); + _again = true; + continue _function; + } + + // Save the next constructor so we call it + CurrentClass = NextClass; + + // Update the prototype proxy with new methods + var mountedInstances = prototypeProxy.update(NextClass.prototype); + + // Set up the constructor property so accessing the statics work + ProxyClass.prototype.constructor = ProxyClass; + + // Set up the same prototype for inherited statics + ProxyClass.__proto__ = NextClass.__proto__; + + // Copy static methods and properties + Object.getOwnPropertyNames(NextClass).forEach(function (key) { + if (RESERVED_STATICS.indexOf(key) > -1) { + return; + } + + var staticDescriptor = _extends({}, Object.getOwnPropertyDescriptor(NextClass, key), { + configurable: true + }); + + // Copy static unless user has redefined it at runtime + if (!wasStaticModifiedByUser(key)) { + Object.defineProperty(ProxyClass, key, staticDescriptor); + staticDescriptors[key] = staticDescriptor; + } + }); + + // Remove old static methods and properties + Object.getOwnPropertyNames(ProxyClass).forEach(function (key) { + if (RESERVED_STATICS.indexOf(key) > -1) { + return; + } + + // Skip statics that exist on the next class + if (NextClass.hasOwnProperty(key)) { + return; + } + + // Skip non-configurable statics + var descriptor = Object.getOwnPropertyDescriptor(ProxyClass, key); + if (descriptor && !descriptor.configurable) { + return; + } + + // Delete static unless user has redefined it at runtime + if (!wasStaticModifiedByUser(key)) { + delete ProxyClass[key]; + delete staticDescriptors[key]; + } + }); + + // Try to infer displayName + ProxyClass.displayName = NextClass.displayName || NextClass.name; + + // We might have added new methods that need to be auto-bound + mountedInstances.forEach(_bindAutoBindMethods2['default']); + mountedInstances.forEach(_deleteUnknownAutoBindMethods2['default']); + + // Let the user take care of redrawing + return mountedInstances; + } + }; + + function get() { + return ProxyClass; + } + + function getCurrent() { + return CurrentClass; + } + + update(InitialClass); + + var proxy = { get: get, update: update }; + + Object.defineProperty(proxy, '__getCurrent', { + configurable: false, + writable: false, + enumerable: false, + value: getCurrent + }); + + Object.defineProperty(ProxyClass, '__reactPatchProxy', { + configurable: false, + writable: false, + enumerable: false, + value: proxy + }); + + return proxy; + } + + module.exports = exports['default']; + +/***/ }, +/* 13 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports['default'] = createPrototypeProxy; + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + + var _lodashObjectAssign = __webpack_require__(36); + + var _lodashObjectAssign2 = _interopRequireDefault(_lodashObjectAssign); + + var _lodashArrayDifference = __webpack_require__(15); + + var _lodashArrayDifference2 = _interopRequireDefault(_lodashArrayDifference); + + function createPrototypeProxy() { + var proxy = {}; + var current = null; + var mountedInstances = []; + + /** + * Creates a proxied toString() method pointing to the current version's toString(). + */ + function proxyToString(name) { + // Wrap to always call the current version + return function toString() { + if (typeof current[name] === 'function') { + return current[name].toString(); + } else { + return '<method was deleted>'; + } + }; + } + + /** + * Creates a proxied method that calls the current version, whenever available. + */ + function proxyMethod(name) { + // Wrap to always call the current version + var proxiedMethod = function proxiedMethod() { + if (typeof current[name] === 'function') { + return current[name].apply(this, arguments); + } + }; + + // Copy properties of the original function, if any + (0, _lodashObjectAssign2['default'])(proxiedMethod, current[name]); + proxiedMethod.toString = proxyToString(name); + + return proxiedMethod; + } + + /** + * Augments the original componentDidMount with instance tracking. + */ + function proxiedComponentDidMount() { + mountedInstances.push(this); + if (typeof current.componentDidMount === 'function') { + return current.componentDidMount.apply(this, arguments); + } + } + proxiedComponentDidMount.toString = proxyToString('componentDidMount'); + + /** + * Augments the original componentWillUnmount with instance tracking. + */ + function proxiedComponentWillUnmount() { + var index = mountedInstances.indexOf(this); + // Unless we're in a weird environment without componentDidMount + if (index !== -1) { + mountedInstances.splice(index, 1); + } + if (typeof current.componentWillUnmount === 'function') { + return current.componentWillUnmount.apply(this, arguments); + } + } + proxiedComponentWillUnmount.toString = proxyToString('componentWillUnmount'); + + /** + * Defines a property on the proxy. + */ + function defineProxyProperty(name, descriptor) { + Object.defineProperty(proxy, name, descriptor); + } + + /** + * Defines a property, attempting to keep the original descriptor configuration. + */ + function defineProxyPropertyWithValue(name, value) { + var _ref = Object.getOwnPropertyDescriptor(current, name) || {}; + + var _ref$enumerable = _ref.enumerable; + var enumerable = _ref$enumerable === undefined ? false : _ref$enumerable; + var _ref$writable = _ref.writable; + var writable = _ref$writable === undefined ? true : _ref$writable; + + defineProxyProperty(name, { + configurable: true, + enumerable: enumerable, + writable: writable, + value: value + }); + } + + /** + * Creates an auto-bind map mimicking the original map, but directed at proxy. + */ + function createAutoBindMap() { + if (!current.__reactAutoBindMap) { + return; + } + + var __reactAutoBindMap = {}; + for (var _name in current.__reactAutoBindMap) { + if (current.__reactAutoBindMap.hasOwnProperty(_name)) { + __reactAutoBindMap[_name] = proxy[_name]; + } + } + + return __reactAutoBindMap; + } + + /** + * Applies the updated prototype. + */ + function update(next) { + // Save current source of truth + current = next; + + // Find changed property names + var currentNames = Object.getOwnPropertyNames(current); + var previousName = Object.getOwnPropertyNames(proxy); + var addedNames = (0, _lodashArrayDifference2['default'])(currentNames, previousName); + var removedNames = (0, _lodashArrayDifference2['default'])(previousName, currentNames); + + // Remove properties and methods that are no longer there + removedNames.forEach(function (name) { + delete proxy[name]; + }); + + // Copy every descriptor + currentNames.forEach(function (name) { + var descriptor = Object.getOwnPropertyDescriptor(current, name); + if (typeof descriptor.value === 'function') { + // Functions require additional wrapping so they can be bound later + defineProxyPropertyWithValue(name, proxyMethod(name)); + } else { + // Other values can be copied directly + defineProxyProperty(name, descriptor); + } + }); + + // Track mounting and unmounting + defineProxyPropertyWithValue('componentDidMount', proxiedComponentDidMount); + defineProxyPropertyWithValue('componentWillUnmount', proxiedComponentWillUnmount); + defineProxyPropertyWithValue('__reactAutoBindMap', createAutoBindMap()); + + // Set up the prototype chain + proxy.__proto__ = next; + + return mountedInstances; + } + + /** + * Returns the up-to-date proxy prototype. + */ + function get() { + return proxy; + } + + return { + update: update, + get: get + }; + } + + ; + module.exports = exports['default']; + +/***/ }, +/* 14 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports['default'] = deleteUnknownAutoBindMethods; + function shouldDeleteClassicInstanceMethod(component, name) { + if (component.__reactAutoBindMap.hasOwnProperty(name)) { + // It's a known autobound function, keep it + return false; + } + + if (component[name].__reactBoundArguments !== null) { + // It's a function bound to specific args, keep it + return false; + } + + // It's a cached bound method for a function + // that was deleted by user, so we delete it from component. + return true; + } + + function shouldDeleteModernInstanceMethod(component, name) { + var prototype = component.constructor.prototype; + + var prototypeDescriptor = Object.getOwnPropertyDescriptor(prototype, name); + + if (!prototypeDescriptor || !prototypeDescriptor.get) { + // This is definitely not an autobinding getter + return false; + } + + if (prototypeDescriptor.get().length !== component[name].length) { + // The length doesn't match, bail out + return false; + } + + // This seems like a method bound using an autobinding getter on the prototype + // Hopefully we won't run into too many false positives. + return true; + } + + function shouldDeleteInstanceMethod(component, name) { + var descriptor = Object.getOwnPropertyDescriptor(component, name); + if (typeof descriptor.value !== 'function') { + // Not a function, or something fancy: bail out + return; + } + + if (component.__reactAutoBindMap) { + // Classic + return shouldDeleteClassicInstanceMethod(component, name); + } else { + // Modern + return shouldDeleteModernInstanceMethod(component, name); + } + } + + /** + * Deletes autobound methods from the instance. + * + * For classic React classes, we only delete the methods that no longer exist in map. + * This means the user actually deleted them in code. + * + * For modern classes, we delete methods that exist on prototype with the same length, + * and which have getters on prototype, but are normal values on the instance. + * This is usually an indication that an autobinding decorator is being used, + * and the getter will re-generate the memoized handler on next access. + */ + + function deleteUnknownAutoBindMethods(component) { + var names = Object.getOwnPropertyNames(component); + + names.forEach(function (name) { + if (shouldDeleteInstanceMethod(component, name)) { + delete component[name]; + } + }); + } + + module.exports = exports['default']; + +/***/ }, +/* 15 */ +/***/ function(module, exports, __webpack_require__) { + + var baseDifference = __webpack_require__(21), + baseFlatten = __webpack_require__(22), + isArrayLike = __webpack_require__(2), + isObjectLike = __webpack_require__(3), + restParam = __webpack_require__(9); + + /** + * Creates an array of unique `array` values not included in the other + * provided arrays using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) + * for equality comparisons. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The arrays of values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.difference([1, 2, 3], [4, 2]); + * // => [1, 3] + */ + var difference = restParam(function(array, values) { + return (isObjectLike(array) && isArrayLike(array)) + ? baseDifference(array, baseFlatten(values, false, true)) + : []; + }); + + module.exports = difference; + + +/***/ }, +/* 16 */ +/***/ function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(global) {var cachePush = __webpack_require__(27), + getNative = __webpack_require__(4); + + /** Native method references. */ + var Set = getNative(global, 'Set'); + + /* Native method references for those with the same name as other `lodash` methods. */ + var nativeCreate = getNative(Object, 'create'); + + /** + * + * Creates a cache object to store unique values. + * + * @private + * @param {Array} [values] The values to cache. + */ + function SetCache(values) { + var length = values ? values.length : 0; + + this.data = { 'hash': nativeCreate(null), 'set': new Set }; + while (length--) { + this.push(values[length]); + } + } + + // Add functions to the `Set` cache. + SetCache.prototype.push = cachePush; + + module.exports = SetCache; + + /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) + +/***/ }, +/* 17 */ +/***/ function(module, exports, __webpack_require__) { + + /** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ + function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; + + while (++index < length) { + array[offset + index] = values[index]; + } + return array; + } + + module.exports = arrayPush; + + +/***/ }, +/* 18 */ +/***/ function(module, exports, __webpack_require__) { + + var keys = __webpack_require__(10); + + /** + * A specialized version of `_.assign` for customizing assigned values without + * support for argument juggling, multiple sources, and `this` binding `customizer` + * functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {Function} customizer The function to customize assigned values. + * @returns {Object} Returns `object`. + */ + function assignWith(object, source, customizer) { + var index = -1, + props = keys(source), + length = props.length; + + while (++index < length) { + var key = props[index], + value = object[key], + result = customizer(value, source[key], key, object, source); + + if ((result === result ? (result !== value) : (value === value)) || + (value === undefined && !(key in object))) { + object[key] = result; + } + } + return object; + } + + module.exports = assignWith; + + +/***/ }, +/* 19 */ +/***/ function(module, exports, __webpack_require__) { + + var baseCopy = __webpack_require__(20), + keys = __webpack_require__(10); + + /** + * The base implementation of `_.assign` without support for argument juggling, + * multiple sources, and `customizer` functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. + */ + function baseAssign(object, source) { + return source == null + ? object + : baseCopy(source, keys(source), object); + } + + module.exports = baseAssign; + + +/***/ }, +/* 20 */ +/***/ function(module, exports, __webpack_require__) { + + /** + * Copies properties of `source` to `object`. + * + * @private + * @param {Object} source The object to copy properties from. + * @param {Array} props The property names to copy. + * @param {Object} [object={}] The object to copy properties to. + * @returns {Object} Returns `object`. + */ + function baseCopy(source, props, object) { + object || (object = {}); + + var index = -1, + length = props.length; + + while (++index < length) { + var key = props[index]; + object[key] = source[key]; + } + return object; + } + + module.exports = baseCopy; + + +/***/ }, +/* 21 */ +/***/ function(module, exports, __webpack_require__) { + + var baseIndexOf = __webpack_require__(23), + cacheIndexOf = __webpack_require__(26), + createCache = __webpack_require__(29); + + /** Used as the size to enable large array optimizations. */ + var LARGE_ARRAY_SIZE = 200; + + /** + * The base implementation of `_.difference` which accepts a single array + * of values to exclude. + * + * @private + * @param {Array} array The array to inspect. + * @param {Array} values The values to exclude. + * @returns {Array} Returns the new array of filtered values. + */ + function baseDifference(array, values) { + var length = array ? array.length : 0, + result = []; + + if (!length) { + return result; + } + var index = -1, + indexOf = baseIndexOf, + isCommon = true, + cache = (isCommon && values.length >= LARGE_ARRAY_SIZE) ? createCache(values) : null, + valuesLength = values.length; + + if (cache) { + indexOf = cacheIndexOf; + isCommon = false; + values = cache; + } + outer: + while (++index < length) { + var value = array[index]; + + if (isCommon && value === value) { + var valuesIndex = valuesLength; + while (valuesIndex--) { + if (values[valuesIndex] === value) { + continue outer; + } + } + result.push(value); + } + else if (indexOf(values, value, 0) < 0) { + result.push(value); + } + } + return result; + } + + module.exports = baseDifference; + + +/***/ }, +/* 22 */ +/***/ function(module, exports, __webpack_require__) { + + var arrayPush = __webpack_require__(17), + isArguments = __webpack_require__(7), + isArray = __webpack_require__(8), + isArrayLike = __webpack_require__(2), + isObjectLike = __webpack_require__(3); + + /** + * The base implementation of `_.flatten` with added support for restricting + * flattening and specifying the start index. + * + * @private + * @param {Array} array The array to flatten. + * @param {boolean} [isDeep] Specify a deep flatten. + * @param {boolean} [isStrict] Restrict flattening to arrays-like objects. + * @param {Array} [result=[]] The initial result value. + * @returns {Array} Returns the new flattened array. + */ + function baseFlatten(array, isDeep, isStrict, result) { + result || (result = []); + + var index = -1, + length = array.length; + + while (++index < length) { + var value = array[index]; + if (isObjectLike(value) && isArrayLike(value) && + (isStrict || isArray(value) || isArguments(value))) { + if (isDeep) { + // Recursively flatten arrays (susceptible to call stack limits). + baseFlatten(value, isDeep, isStrict, result); + } else { + arrayPush(result, value); + } + } else if (!isStrict) { + result[result.length] = value; + } + } + return result; + } + + module.exports = baseFlatten; + + +/***/ }, +/* 23 */ +/***/ function(module, exports, __webpack_require__) { + + var indexOfNaN = __webpack_require__(31); + + /** + * The base implementation of `_.indexOf` without support for binary searches. + * + * @private + * @param {Array} array The array to search. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseIndexOf(array, value, fromIndex) { + if (value !== value) { + return indexOfNaN(array, fromIndex); + } + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (array[index] === value) { + return index; + } + } + return -1; + } + + module.exports = baseIndexOf; + + +/***/ }, +/* 24 */ +/***/ function(module, exports, __webpack_require__) { + + /** + * The base implementation of `_.property` without support for deep paths. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new function. + */ + function baseProperty(key) { + return function(object) { + return object == null ? undefined : object[key]; + }; + } + + module.exports = baseProperty; + + +/***/ }, +/* 25 */ +/***/ function(module, exports, __webpack_require__) { + + var identity = __webpack_require__(38); + + /** + * A specialized version of `baseCallback` which only supports `this` binding + * and specifying the number of arguments to provide to `func`. + * + * @private + * @param {Function} func The function to bind. + * @param {*} thisArg The `this` binding of `func`. + * @param {number} [argCount] The number of arguments to provide to `func`. + * @returns {Function} Returns the callback. + */ + function bindCallback(func, thisArg, argCount) { + if (typeof func != 'function') { + return identity; + } + if (thisArg === undefined) { + return func; + } + switch (argCount) { + case 1: return function(value) { + return func.call(thisArg, value); + }; + case 3: return function(value, index, collection) { + return func.call(thisArg, value, index, collection); + }; + case 4: return function(accumulator, value, index, collection) { + return func.call(thisArg, accumulator, value, index, collection); + }; + case 5: return function(value, other, key, object, source) { + return func.call(thisArg, value, other, key, object, source); + }; + } + return function() { + return func.apply(thisArg, arguments); + }; + } + + module.exports = bindCallback; + + +/***/ }, +/* 26 */ +/***/ function(module, exports, __webpack_require__) { + + var isObject = __webpack_require__(1); + + /** + * Checks if `value` is in `cache` mimicking the return signature of + * `_.indexOf` by returning `0` if the value is found, else `-1`. + * + * @private + * @param {Object} cache The cache to search. + * @param {*} value The value to search for. + * @returns {number} Returns `0` if `value` is found, else `-1`. + */ + function cacheIndexOf(cache, value) { + var data = cache.data, + result = (typeof value == 'string' || isObject(value)) ? data.set.has(value) : data.hash[value]; + + return result ? 0 : -1; + } + + module.exports = cacheIndexOf; + + +/***/ }, +/* 27 */ +/***/ function(module, exports, __webpack_require__) { + + var isObject = __webpack_require__(1); + + /** + * Adds `value` to the cache. + * + * @private + * @name push + * @memberOf SetCache + * @param {*} value The value to cache. + */ + function cachePush(value) { + var data = this.data; + if (typeof value == 'string' || isObject(value)) { + data.set.add(value); + } else { + data.hash[value] = true; + } + } + + module.exports = cachePush; + + +/***/ }, +/* 28 */ +/***/ function(module, exports, __webpack_require__) { + + var bindCallback = __webpack_require__(25), + isIterateeCall = __webpack_require__(32), + restParam = __webpack_require__(9); + + /** + * Creates a `_.assign`, `_.defaults`, or `_.merge` function. + * + * @private + * @param {Function} assigner The function to assign values. + * @returns {Function} Returns the new assigner function. + */ + function createAssigner(assigner) { + return restParam(function(object, sources) { + var index = -1, + length = object == null ? 0 : sources.length, + customizer = length > 2 ? sources[length - 2] : undefined, + guard = length > 2 ? sources[2] : undefined, + thisArg = length > 1 ? sources[length - 1] : undefined; + + if (typeof customizer == 'function') { + customizer = bindCallback(customizer, thisArg, 5); + length -= 2; + } else { + customizer = typeof thisArg == 'function' ? thisArg : undefined; + length -= (customizer ? 1 : 0); + } + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + customizer = length < 3 ? undefined : customizer; + length = 1; + } + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, customizer); + } + } + return object; + }); + } + + module.exports = createAssigner; + + +/***/ }, +/* 29 */ +/***/ function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(global) {var SetCache = __webpack_require__(16), + getNative = __webpack_require__(4); + + /** Native method references. */ + var Set = getNative(global, 'Set'); + + /* Native method references for those with the same name as other `lodash` methods. */ + var nativeCreate = getNative(Object, 'create'); + + /** + * Creates a `Set` cache object to optimize linear searches of large arrays. + * + * @private + * @param {Array} [values] The values to cache. + * @returns {null|Object} Returns the new cache object if `Set` is supported, else `null`. + */ + function createCache(values) { + return (nativeCreate && Set) ? new SetCache(values) : null; + } + + module.exports = createCache; + + /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) + +/***/ }, +/* 30 */ +/***/ function(module, exports, __webpack_require__) { + + var baseProperty = __webpack_require__(24); + + /** + * Gets the "length" property value of `object`. + * + * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) + * that affects Safari on at least iOS 8.1-8.3 ARM64. + * + * @private + * @param {Object} object The object to query. + * @returns {*} Returns the "length" value. + */ + var getLength = baseProperty('length'); + + module.exports = getLength; + + +/***/ }, +/* 31 */ +/***/ function(module, exports, __webpack_require__) { + + /** + * Gets the index at which the first occurrence of `NaN` is found in `array`. + * + * @private + * @param {Array} array The array to search. + * @param {number} fromIndex The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched `NaN`, else `-1`. + */ + function indexOfNaN(array, fromIndex, fromRight) { + var length = array.length, + index = fromIndex + (fromRight ? 0 : -1); + + while ((fromRight ? index-- : ++index < length)) { + var other = array[index]; + if (other !== other) { + return index; + } + } + return -1; + } + + module.exports = indexOfNaN; + + +/***/ }, +/* 32 */ +/***/ function(module, exports, __webpack_require__) { + + var isArrayLike = __webpack_require__(2), + isIndex = __webpack_require__(6), + isObject = __webpack_require__(1); + + /** + * Checks if the provided arguments are from an iteratee call. + * + * @private + * @param {*} value The potential iteratee value argument. + * @param {*} index The potential iteratee index or key argument. + * @param {*} object The potential iteratee object argument. + * @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`. + */ + function isIterateeCall(value, index, object) { + if (!isObject(object)) { + return false; + } + var type = typeof index; + if (type == 'number' + ? (isArrayLike(object) && isIndex(index, object.length)) + : (type == 'string' && index in object)) { + var other = object[index]; + return value === value ? (value === other) : (other !== other); + } + return false; + } + + module.exports = isIterateeCall; + + +/***/ }, +/* 33 */ +/***/ function(module, exports, __webpack_require__) { + + var isArguments = __webpack_require__(7), + isArray = __webpack_require__(8), + isIndex = __webpack_require__(6), + isLength = __webpack_require__(5), + keysIn = __webpack_require__(37); + + /** Used for native method references. */ + var objectProto = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty = objectProto.hasOwnProperty; + + /** + * A fallback implementation of `Object.keys` which creates an array of the + * own enumerable property names of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function shimKeys(object) { + var props = keysIn(object), + propsLength = props.length, + length = propsLength && object.length; + + var allowIndexes = !!length && isLength(length) && + (isArray(object) || isArguments(object)); + + var index = -1, + result = []; + + while (++index < propsLength) { + var key = props[index]; + if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) { + result.push(key); + } + } + return result; + } + + module.exports = shimKeys; + + +/***/ }, +/* 34 */ +/***/ function(module, exports, __webpack_require__) { + + var isObject = __webpack_require__(1); + + /** `Object#toString` result references. */ + var funcTag = '[object Function]'; + + /** Used for native method references. */ + var objectProto = Object.prototype; + + /** + * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) + * of values. + */ + var objToString = objectProto.toString; + + /** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ + function isFunction(value) { + // The use of `Object#toString` avoids issues with the `typeof` operator + // in older versions of Chrome and Safari which return 'function' for regexes + // and Safari 8 which returns 'object' for typed array constructors. + return isObject(value) && objToString.call(value) == funcTag; + } + + module.exports = isFunction; + + +/***/ }, +/* 35 */ +/***/ function(module, exports, __webpack_require__) { + + var isFunction = __webpack_require__(34), + isObjectLike = __webpack_require__(3); + + /** Used to detect host constructors (Safari > 5). */ + var reIsHostCtor = /^\[object .+?Constructor\]$/; + + /** Used for native method references. */ + var objectProto = Object.prototype; + + /** Used to resolve the decompiled source of functions. */ + var fnToString = Function.prototype.toString; + + /** Used to check objects for own properties. */ + var hasOwnProperty = objectProto.hasOwnProperty; + + /** Used to detect if a method is native. */ + var reIsNative = RegExp('^' + + fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' + ); + + /** + * Checks if `value` is a native function. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, else `false`. + * @example + * + * _.isNative(Array.prototype.push); + * // => true + * + * _.isNative(_); + * // => false + */ + function isNative(value) { + if (value == null) { + return false; + } + if (isFunction(value)) { + return reIsNative.test(fnToString.call(value)); + } + return isObjectLike(value) && reIsHostCtor.test(value); + } + + module.exports = isNative; + + +/***/ }, +/* 36 */ +/***/ function(module, exports, __webpack_require__) { + + var assignWith = __webpack_require__(18), + baseAssign = __webpack_require__(19), + createAssigner = __webpack_require__(28); + + /** + * Assigns own enumerable properties of source object(s) to the destination + * object. Subsequent sources overwrite property assignments of previous sources. + * If `customizer` is provided it's invoked to produce the assigned values. + * The `customizer` is bound to `thisArg` and invoked with five arguments: + * (objectValue, sourceValue, key, object, source). + * + * **Note:** This method mutates `object` and is based on + * [`Object.assign`](http://ecma-international.org/ecma-262/6.0/#sec-object.assign). + * + * @static + * @memberOf _ + * @alias extend + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @param {*} [thisArg] The `this` binding of `customizer`. + * @returns {Object} Returns `object`. + * @example + * + * _.assign({ 'user': 'barney' }, { 'age': 40 }, { 'user': 'fred' }); + * // => { 'user': 'fred', 'age': 40 } + * + * // using a customizer callback + * var defaults = _.partialRight(_.assign, function(value, other) { + * return _.isUndefined(value) ? other : value; + * }); + * + * defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' }); + * // => { 'user': 'barney', 'age': 36 } + */ + var assign = createAssigner(function(object, source, customizer) { + return customizer + ? assignWith(object, source, customizer) + : baseAssign(object, source); + }); + + module.exports = assign; + + +/***/ }, +/* 37 */ +/***/ function(module, exports, __webpack_require__) { + + var isArguments = __webpack_require__(7), + isArray = __webpack_require__(8), + isIndex = __webpack_require__(6), + isLength = __webpack_require__(5), + isObject = __webpack_require__(1); + + /** Used for native method references. */ + var objectProto = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty = objectProto.hasOwnProperty; + + /** + * Creates an array of the own and inherited enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keysIn(new Foo); + * // => ['a', 'b', 'c'] (iteration order is not guaranteed) + */ + function keysIn(object) { + if (object == null) { + return []; + } + if (!isObject(object)) { + object = Object(object); + } + var length = object.length; + length = (length && isLength(length) && + (isArray(object) || isArguments(object)) && length) || 0; + + var Ctor = object.constructor, + index = -1, + isProto = typeof Ctor == 'function' && Ctor.prototype === object, + result = Array(length), + skipIndexes = length > 0; + + while (++index < length) { + result[index] = (index + ''); + } + for (var key in object) { + if (!(skipIndexes && isIndex(key, length)) && + !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { + result.push(key); + } + } + return result; + } + + module.exports = keysIn; + + +/***/ }, +/* 38 */ +/***/ function(module, exports, __webpack_require__) { + + /** + * This method returns the first argument provided to it. + * + * @static + * @memberOf _ + * @category Utility + * @param {*} value Any value. + * @returns {*} Returns `value`. + * @example + * + * var object = { 'user': 'fred' }; + * + * _.identity(object) === object; + * // => true + */ + function identity(value) { + return value; + } + + module.exports = identity; + + +/***/ }, +/* 39 */ +/***/ function(module, exports, __webpack_require__) { + + "use strict"; + + exports.__esModule = true; + exports["default"] = getForceUpdate; + function traverseRenderedChildren(internalInstance, callback, argument) { + callback(internalInstance, argument); + + if (internalInstance._renderedComponent) { + traverseRenderedChildren(internalInstance._renderedComponent, callback, argument); + } else { + for (var key in internalInstance._renderedChildren) { + if (internalInstance._renderedChildren.hasOwnProperty(key)) { + traverseRenderedChildren(internalInstance._renderedChildren[key], callback, argument); + } + } + } + } + + function setPendingForceUpdate(internalInstance) { + if (internalInstance._pendingForceUpdate === false) { + internalInstance._pendingForceUpdate = true; + } + } + + function forceUpdateIfPending(internalInstance, React) { + if (internalInstance._pendingForceUpdate === true) { + var publicInstance = internalInstance._instance; + React.Component.prototype.forceUpdate.call(publicInstance); + } + } + + function getForceUpdate(React) { + return function (instance) { + var internalInstance = instance._reactInternalInstance; + traverseRenderedChildren(internalInstance, setPendingForceUpdate); + traverseRenderedChildren(internalInstance, forceUpdateIfPending, React); + }; + } + + module.exports = exports["default"]; + +/***/ } +/******/ ]) +}); diff --git a/devtools/client/shared/vendor/react-redux.js b/devtools/client/shared/vendor/react-redux.js new file mode 100644 index 000000000..562f4916f --- /dev/null +++ b/devtools/client/shared/vendor/react-redux.js @@ -0,0 +1,724 @@ +var REACT_PATH = "devtools/client/shared/vendor/react"; +var REDUX_PATH = "devtools/client/shared/vendor/redux"; + +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(require(REACT_PATH), require(REDUX_PATH)); + else if(typeof define === 'function' && define.amd) + define(["react", "redux"], factory); + else if(typeof exports === 'object') + exports["ReactRedux"] = factory(require("react"), require("redux")); + else + root["ReactRedux"] = factory(root["React"], root["Redux"]); +})(this, function(__WEBPACK_EXTERNAL_MODULE_10__, __WEBPACK_EXTERNAL_MODULE_11__) { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; + +/******/ // The require function +/******/ function __webpack_require__(moduleId) { + +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; + +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ exports: {}, +/******/ id: moduleId, +/******/ loaded: false +/******/ }; + +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + +/******/ // Flag the module as loaded +/******/ module.loaded = true; + +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } + + +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; + +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; + +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; + +/******/ // Load entry module and return exports +/******/ return __webpack_require__(0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + exports.__esModule = true; + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + + var _react = __webpack_require__(10); + + var _react2 = _interopRequireDefault(_react); + + var _componentsCreateAll = __webpack_require__(2); + + var _componentsCreateAll2 = _interopRequireDefault(_componentsCreateAll); + + var _createAll = _componentsCreateAll2['default'](_react2['default']); + + var Provider = _createAll.Provider; + var connect = _createAll.connect; + exports.Provider = Provider; + exports.connect = connect; + +/***/ }, +/* 1 */ +/***/ function(module, exports) { + + "use strict"; + + exports.__esModule = true; + exports["default"] = createStoreShape; + + function createStoreShape(PropTypes) { + return PropTypes.shape({ + subscribe: PropTypes.func.isRequired, + dispatch: PropTypes.func.isRequired, + getState: PropTypes.func.isRequired + }); + } + + module.exports = exports["default"]; + +/***/ }, +/* 2 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + exports.__esModule = true; + exports['default'] = createAll; + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + + var _createProvider = __webpack_require__(4); + + var _createProvider2 = _interopRequireDefault(_createProvider); + + var _createConnect = __webpack_require__(3); + + var _createConnect2 = _interopRequireDefault(_createConnect); + + function createAll(React) { + var Provider = _createProvider2['default'](React); + var connect = _createConnect2['default'](React); + + return { Provider: Provider, connect: connect }; + } + + module.exports = exports['default']; + +/***/ }, +/* 3 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + exports.__esModule = true; + + var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; + + exports['default'] = createConnect; + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + + function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + + var _utilsCreateStoreShape = __webpack_require__(1); + + var _utilsCreateStoreShape2 = _interopRequireDefault(_utilsCreateStoreShape); + + var _utilsShallowEqual = __webpack_require__(6); + + var _utilsShallowEqual2 = _interopRequireDefault(_utilsShallowEqual); + + var _utilsIsPlainObject = __webpack_require__(5); + + var _utilsIsPlainObject2 = _interopRequireDefault(_utilsIsPlainObject); + + var _utilsWrapActionCreators = __webpack_require__(7); + + var _utilsWrapActionCreators2 = _interopRequireDefault(_utilsWrapActionCreators); + + var _hoistNonReactStatics = __webpack_require__(8); + + var _hoistNonReactStatics2 = _interopRequireDefault(_hoistNonReactStatics); + + var _invariant = __webpack_require__(9); + + var _invariant2 = _interopRequireDefault(_invariant); + + var defaultMapStateToProps = function defaultMapStateToProps() { + return {}; + }; + var defaultMapDispatchToProps = function defaultMapDispatchToProps(dispatch) { + return { dispatch: dispatch }; + }; + var defaultMergeProps = function defaultMergeProps(stateProps, dispatchProps, parentProps) { + return _extends({}, parentProps, stateProps, dispatchProps); + }; + + function getDisplayName(Component) { + return Component.displayName || Component.name || 'Component'; + } + + // Helps track hot reloading. + var nextVersion = 0; + + function createConnect(React) { + var Component = React.Component; + var PropTypes = React.PropTypes; + + var storeShape = _utilsCreateStoreShape2['default'](PropTypes); + + return function connect(mapStateToProps, mapDispatchToProps, mergeProps) { + var options = arguments.length <= 3 || arguments[3] === undefined ? {} : arguments[3]; + + var shouldSubscribe = Boolean(mapStateToProps); + var finalMapStateToProps = mapStateToProps || defaultMapStateToProps; + var finalMapDispatchToProps = _utilsIsPlainObject2['default'](mapDispatchToProps) ? _utilsWrapActionCreators2['default'](mapDispatchToProps) : mapDispatchToProps || defaultMapDispatchToProps; + var finalMergeProps = mergeProps || defaultMergeProps; + var shouldUpdateStateProps = finalMapStateToProps.length > 1; + var shouldUpdateDispatchProps = finalMapDispatchToProps.length > 1; + var _options$pure = options.pure; + var pure = _options$pure === undefined ? true : _options$pure; + + // Helps track hot reloading. + var version = nextVersion++; + + function computeStateProps(store, props) { + var state = store.getState(); + var stateProps = shouldUpdateStateProps ? finalMapStateToProps(state, props) : finalMapStateToProps(state); + + _invariant2['default'](_utilsIsPlainObject2['default'](stateProps), '`mapStateToProps` must return an object. Instead received %s.', stateProps); + return stateProps; + } + + function computeDispatchProps(store, props) { + var dispatch = store.dispatch; + + var dispatchProps = shouldUpdateDispatchProps ? finalMapDispatchToProps(dispatch, props) : finalMapDispatchToProps(dispatch); + + _invariant2['default'](_utilsIsPlainObject2['default'](dispatchProps), '`mapDispatchToProps` must return an object. Instead received %s.', dispatchProps); + return dispatchProps; + } + + function _computeNextState(stateProps, dispatchProps, parentProps) { + var mergedProps = finalMergeProps(stateProps, dispatchProps, parentProps); + _invariant2['default'](_utilsIsPlainObject2['default'](mergedProps), '`mergeProps` must return an object. Instead received %s.', mergedProps); + return mergedProps; + } + + return function wrapWithConnect(WrappedComponent) { + var Connect = (function (_Component) { + _inherits(Connect, _Component); + + Connect.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps, nextState) { + if (!pure) { + this.updateStateProps(nextProps); + this.updateDispatchProps(nextProps); + this.updateState(nextProps); + return true; + } + + var storeChanged = nextState.storeState !== this.state.storeState; + var propsChanged = !_utilsShallowEqual2['default'](nextProps, this.props); + var mapStateProducedChange = false; + var dispatchPropsChanged = false; + + if (storeChanged || propsChanged && shouldUpdateStateProps) { + mapStateProducedChange = this.updateStateProps(nextProps); + } + + if (propsChanged && shouldUpdateDispatchProps) { + dispatchPropsChanged = this.updateDispatchProps(nextProps); + } + + if (propsChanged || mapStateProducedChange || dispatchPropsChanged) { + this.updateState(nextProps); + return true; + } + + return false; + }; + + function Connect(props, context) { + _classCallCheck(this, Connect); + + _Component.call(this, props, context); + this.version = version; + this.store = props.store || context.store; + + _invariant2['default'](this.store, 'Could not find "store" in either the context or ' + ('props of "' + this.constructor.displayName + '". ') + 'Either wrap the root component in a <Provider>, ' + ('or explicitly pass "store" as a prop to "' + this.constructor.displayName + '".')); + + this.stateProps = computeStateProps(this.store, props); + this.dispatchProps = computeDispatchProps(this.store, props); + this.state = { storeState: null }; + this.updateState(); + } + + Connect.prototype.computeNextState = function computeNextState() { + var props = arguments.length <= 0 || arguments[0] === undefined ? this.props : arguments[0]; + + return _computeNextState(this.stateProps, this.dispatchProps, props); + }; + + Connect.prototype.updateStateProps = function updateStateProps() { + var props = arguments.length <= 0 || arguments[0] === undefined ? this.props : arguments[0]; + + var nextStateProps = computeStateProps(this.store, props); + if (_utilsShallowEqual2['default'](nextStateProps, this.stateProps)) { + return false; + } + + this.stateProps = nextStateProps; + return true; + }; + + Connect.prototype.updateDispatchProps = function updateDispatchProps() { + var props = arguments.length <= 0 || arguments[0] === undefined ? this.props : arguments[0]; + + var nextDispatchProps = computeDispatchProps(this.store, props); + if (_utilsShallowEqual2['default'](nextDispatchProps, this.dispatchProps)) { + return false; + } + + this.dispatchProps = nextDispatchProps; + return true; + }; + + Connect.prototype.updateState = function updateState() { + var props = arguments.length <= 0 || arguments[0] === undefined ? this.props : arguments[0]; + + this.nextState = this.computeNextState(props); + }; + + Connect.prototype.isSubscribed = function isSubscribed() { + return typeof this.unsubscribe === 'function'; + }; + + Connect.prototype.trySubscribe = function trySubscribe() { + if (shouldSubscribe && !this.unsubscribe) { + this.unsubscribe = this.store.subscribe(this.handleChange.bind(this)); + this.handleChange(); + } + }; + + Connect.prototype.tryUnsubscribe = function tryUnsubscribe() { + if (this.unsubscribe) { + this.unsubscribe(); + this.unsubscribe = null; + } + }; + + Connect.prototype.componentDidMount = function componentDidMount() { + this.trySubscribe(); + }; + + Connect.prototype.componentWillUnmount = function componentWillUnmount() { + this.tryUnsubscribe(); + }; + + Connect.prototype.handleChange = function handleChange() { + if (!this.unsubscribe) { + return; + } + + this.setState({ + storeState: this.store.getState() + }); + }; + + Connect.prototype.getWrappedInstance = function getWrappedInstance() { + return this.refs.wrappedInstance; + }; + + Connect.prototype.render = function render() { + return React.createElement(WrappedComponent, _extends({ ref: 'wrappedInstance' + }, this.nextState)); + }; + + return Connect; + })(Component); + + Connect.displayName = 'Connect(' + getDisplayName(WrappedComponent) + ')'; + Connect.WrappedComponent = WrappedComponent; + Connect.contextTypes = { + store: storeShape + }; + Connect.propTypes = { + store: storeShape + }; + + if (true) { + Connect.prototype.componentWillUpdate = function componentWillUpdate() { + if (this.version === version) { + return; + } + + // We are hot reloading! + this.version = version; + + // Update the state and bindings. + this.trySubscribe(); + this.updateStateProps(); + this.updateDispatchProps(); + this.updateState(); + }; + } + + return _hoistNonReactStatics2['default'](Connect, WrappedComponent); + }; + }; + } + + module.exports = exports['default']; + +/***/ }, +/* 4 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + exports.__esModule = true; + exports['default'] = createProvider; + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + + function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + + var _utilsCreateStoreShape = __webpack_require__(1); + + var _utilsCreateStoreShape2 = _interopRequireDefault(_utilsCreateStoreShape); + + function isUsingOwnerContext(React) { + var version = React.version; + + if (typeof version !== 'string') { + return true; + } + + var sections = version.split('.'); + var major = parseInt(sections[0], 10); + var minor = parseInt(sections[1], 10); + + return major === 0 && minor === 13; + } + + function createProvider(React) { + var Component = React.Component; + var PropTypes = React.PropTypes; + var Children = React.Children; + + var storeShape = _utilsCreateStoreShape2['default'](PropTypes); + var requireFunctionChild = isUsingOwnerContext(React); + + var didWarnAboutChild = false; + function warnAboutFunctionChild() { + if (didWarnAboutChild || requireFunctionChild) { + return; + } + + didWarnAboutChild = true; + console.error( // eslint-disable-line no-console + 'With React 0.14 and later versions, you no longer need to ' + 'wrap <Provider> child into a function.'); + } + function warnAboutElementChild() { + if (didWarnAboutChild || !requireFunctionChild) { + return; + } + + didWarnAboutChild = true; + console.error( // eslint-disable-line no-console + 'With React 0.13, you need to ' + 'wrap <Provider> child into a function. ' + 'This restriction will be removed with React 0.14.'); + } + + var didWarnAboutReceivingStore = false; + function warnAboutReceivingStore() { + if (didWarnAboutReceivingStore) { + return; + } + + didWarnAboutReceivingStore = true; + console.error( // eslint-disable-line no-console + '<Provider> does not support changing `store` on the fly. ' + 'It is most likely that you see this error because you updated to ' + 'Redux 2.x and React Redux 2.x which no longer hot reload reducers ' + 'automatically. See https://github.com/rackt/react-redux/releases/' + 'tag/v2.0.0 for the migration instructions.'); + } + + var Provider = (function (_Component) { + _inherits(Provider, _Component); + + Provider.prototype.getChildContext = function getChildContext() { + return { store: this.store }; + }; + + function Provider(props, context) { + _classCallCheck(this, Provider); + + _Component.call(this, props, context); + this.store = props.store; + } + + Provider.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { + var store = this.store; + var nextStore = nextProps.store; + + if (store !== nextStore) { + warnAboutReceivingStore(); + } + }; + + Provider.prototype.render = function render() { + var children = this.props.children; + + if (typeof children === 'function') { + warnAboutFunctionChild(); + children = children(); + } else { + warnAboutElementChild(); + } + + return Children.only(children); + }; + + return Provider; + })(Component); + + Provider.childContextTypes = { + store: storeShape.isRequired + }; + Provider.propTypes = { + store: storeShape.isRequired, + children: (requireFunctionChild ? PropTypes.func : PropTypes.element).isRequired + }; + + return Provider; + } + + module.exports = exports['default']; + +/***/ }, +/* 5 */ +/***/ function(module, exports) { + + 'use strict'; + + exports.__esModule = true; + exports['default'] = isPlainObject; + var fnToString = function fnToString(fn) { + return Function.prototype.toString.call(fn); + }; + + /** + * @param {any} obj The object to inspect. + * @returns {boolean} True if the argument appears to be a plain object. + */ + + function isPlainObject(obj) { + if (!obj || typeof obj !== 'object') { + return false; + } + + var proto = typeof obj.constructor === 'function' ? Object.getPrototypeOf(obj) : Object.prototype; + + if (proto === null) { + return true; + } + + var constructor = proto.constructor; + + return typeof constructor === 'function' && constructor instanceof constructor && fnToString(constructor) === fnToString(Object); + } + + module.exports = exports['default']; + +/***/ }, +/* 6 */ +/***/ function(module, exports) { + + "use strict"; + + exports.__esModule = true; + exports["default"] = shallowEqual; + + function shallowEqual(objA, objB) { + if (objA === objB) { + return true; + } + + var keysA = Object.keys(objA); + var keysB = Object.keys(objB); + + if (keysA.length !== keysB.length) { + return false; + } + + // Test for A's keys different from B. + var hasOwn = Object.prototype.hasOwnProperty; + for (var i = 0; i < keysA.length; i++) { + if (!hasOwn.call(objB, keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) { + return false; + } + } + + return true; + } + + module.exports = exports["default"]; + +/***/ }, +/* 7 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + exports.__esModule = true; + exports['default'] = wrapActionCreators; + + var _redux = __webpack_require__(11); + + function wrapActionCreators(actionCreators) { + return function (dispatch) { + return _redux.bindActionCreators(actionCreators, dispatch); + }; + } + + module.exports = exports['default']; + +/***/ }, +/* 8 */ +/***/ function(module, exports) { + + /** + * Copyright 2015, Yahoo! Inc. + * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ + 'use strict'; + + var REACT_STATICS = { + childContextTypes: true, + contextTypes: true, + defaultProps: true, + displayName: true, + getDefaultProps: true, + mixins: true, + propTypes: true, + type: true + }; + + var KNOWN_STATICS = { + name: true, + length: true, + prototype: true, + caller: true, + arguments: true, + arity: true + }; + + module.exports = function hoistNonReactStatics(targetComponent, sourceComponent) { + var keys = Object.getOwnPropertyNames(sourceComponent); + for (var i=0; i<keys.length; ++i) { + if (!REACT_STATICS[keys[i]] && !KNOWN_STATICS[keys[i]]) { + targetComponent[keys[i]] = sourceComponent[keys[i]]; + } + } + + return targetComponent; + }; + + +/***/ }, +/* 9 */ +/***/ function(module, exports, __webpack_require__) { + + /** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule invariant + */ + + 'use strict'; + + /** + * Use invariant() to assert state which your program assumes to be true. + * + * Provide sprintf-style format (only %s is supported) and arguments + * to provide information about what broke and what you were + * expecting. + * + * The invariant message will be stripped in production, but the invariant + * will remain to ensure logic does not differ in production. + */ + + var invariant = function(condition, format, a, b, c, d, e, f) { + if (true) { + if (format === undefined) { + throw new Error('invariant requires an error message argument'); + } + } + + if (!condition) { + var error; + if (format === undefined) { + error = new Error( + 'Minified exception occurred; use the non-minified dev environment ' + + 'for the full error message and additional helpful warnings.' + ); + } else { + var args = [a, b, c, d, e, f]; + var argIndex = 0; + error = new Error( + 'Invariant Violation: ' + + format.replace(/%s/g, function() { return args[argIndex++]; }) + ); + } + + error.framesToPop = 1; // we don't care about invariant's own frame + throw error; + } + }; + + module.exports = invariant; + + +/***/ }, +/* 10 */ +/***/ function(module, exports) { + + module.exports = __WEBPACK_EXTERNAL_MODULE_10__; + +/***/ }, +/* 11 */ +/***/ function(module, exports) { + + module.exports = __WEBPACK_EXTERNAL_MODULE_11__; + +/***/ } +/******/ ]) +}); +; diff --git a/devtools/client/shared/vendor/react-virtualized.js b/devtools/client/shared/vendor/react-virtualized.js new file mode 100644 index 000000000..dab201ac6 --- /dev/null +++ b/devtools/client/shared/vendor/react-virtualized.js @@ -0,0 +1,4296 @@ +var REACT_PATH = "devtools/client/shared/vendor/react"; +var REACT_DOM_PATH = "devtools/client/shared/vendor/react-dom"; +var REACT_SHALLOW_COMPARE = "devtools/client/shared/vendor/react-addons-shallow-compare"; + +!function(root, factory) { + let React = require(REACT_PATH); + let shallowCompare = require(REACT_SHALLOW_COMPARE); + let ReactDOM = require(REACT_DOM_PATH); + module.exports = factory(React, shallowCompare, ReactDOM); +}(this, function(__WEBPACK_EXTERNAL_MODULE_89__, __WEBPACK_EXTERNAL_MODULE_90__, __WEBPACK_EXTERNAL_MODULE_96__) { + /******/ + return function(modules) { + /******/ + /******/ + // The require function + /******/ + function __webpack_require__(moduleId) { + /******/ + /******/ + // Check if module is in cache + /******/ + if (installedModules[moduleId]) /******/ + return installedModules[moduleId].exports; + /******/ + /******/ + // Create a new module (and put it into the cache) + /******/ + var module = installedModules[moduleId] = { + /******/ + exports: {}, + /******/ + id: moduleId, + /******/ + loaded: !1 + }; + /******/ + /******/ + // Return the exports of the module + /******/ + /******/ + /******/ + // Execute the module function + /******/ + /******/ + /******/ + // Flag the module as loaded + /******/ + return modules[moduleId].call(module.exports, module, module.exports, __webpack_require__), + module.loaded = !0, module.exports; + } + // webpackBootstrap + /******/ + // The module cache + /******/ + var installedModules = {}; + /******/ + /******/ + // Load entry module and return exports + /******/ + /******/ + /******/ + /******/ + // expose the modules object (__webpack_modules__) + /******/ + /******/ + /******/ + // expose the module cache + /******/ + /******/ + /******/ + // __webpack_public_path__ + /******/ + return __webpack_require__.m = modules, __webpack_require__.c = installedModules, + __webpack_require__.p = "", __webpack_require__(0); + }([ /* 0 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + Object.defineProperty(exports, "__esModule", { + value: !0 + }); + var _ArrowKeyStepper = __webpack_require__(1); + Object.defineProperty(exports, "ArrowKeyStepper", { + enumerable: !0, + get: function() { + return _ArrowKeyStepper.ArrowKeyStepper; + } + }); + var _AutoSizer = __webpack_require__(91); + Object.defineProperty(exports, "AutoSizer", { + enumerable: !0, + get: function() { + return _AutoSizer.AutoSizer; + } + }); + var _CellMeasurer = __webpack_require__(94); + Object.defineProperty(exports, "CellMeasurer", { + enumerable: !0, + get: function() { + return _CellMeasurer.CellMeasurer; + } + }), Object.defineProperty(exports, "defaultCellMeasurerCellSizeCache", { + enumerable: !0, + get: function() { + return _CellMeasurer.defaultCellSizeCache; + } + }), Object.defineProperty(exports, "uniformSizeCellMeasurerCellSizeCache", { + enumerable: !0, + get: function() { + return _CellMeasurer.defaultCellSizeCache; + } + }); + var _Collection = __webpack_require__(98); + Object.defineProperty(exports, "Collection", { + enumerable: !0, + get: function() { + return _Collection.Collection; + } + }); + var _ColumnSizer = __webpack_require__(118); + Object.defineProperty(exports, "ColumnSizer", { + enumerable: !0, + get: function() { + return _ColumnSizer.ColumnSizer; + } + }); + var _Table = __webpack_require__(128); + Object.defineProperty(exports, "defaultTableCellDataGetter", { + enumerable: !0, + get: function() { + return _Table.defaultCellDataGetter; + } + }), Object.defineProperty(exports, "defaultTableCellRenderer", { + enumerable: !0, + get: function() { + return _Table.defaultCellRenderer; + } + }), Object.defineProperty(exports, "defaultTableHeaderRenderer", { + enumerable: !0, + get: function() { + return _Table.defaultHeaderRenderer; + } + }), Object.defineProperty(exports, "defaultTableRowRenderer", { + enumerable: !0, + get: function() { + return _Table.defaultRowRenderer; + } + }), Object.defineProperty(exports, "Table", { + enumerable: !0, + get: function() { + return _Table.Table; + } + }), Object.defineProperty(exports, "Column", { + enumerable: !0, + get: function() { + return _Table.Column; + } + }), Object.defineProperty(exports, "SortDirection", { + enumerable: !0, + get: function() { + return _Table.SortDirection; + } + }), Object.defineProperty(exports, "SortIndicator", { + enumerable: !0, + get: function() { + return _Table.SortIndicator; + } + }); + var _Grid = __webpack_require__(120); + Object.defineProperty(exports, "defaultCellRangeRenderer", { + enumerable: !0, + get: function() { + return _Grid.defaultCellRangeRenderer; + } + }), Object.defineProperty(exports, "Grid", { + enumerable: !0, + get: function() { + return _Grid.Grid; + } + }); + var _InfiniteLoader = __webpack_require__(137); + Object.defineProperty(exports, "InfiniteLoader", { + enumerable: !0, + get: function() { + return _InfiniteLoader.InfiniteLoader; + } + }); + var _ScrollSync = __webpack_require__(139); + Object.defineProperty(exports, "ScrollSync", { + enumerable: !0, + get: function() { + return _ScrollSync.ScrollSync; + } + }); + var _List = __webpack_require__(141); + Object.defineProperty(exports, "List", { + enumerable: !0, + get: function() { + return _List.List; + } + }); + var _WindowScroller = __webpack_require__(143); + Object.defineProperty(exports, "WindowScroller", { + enumerable: !0, + get: function() { + return _WindowScroller.WindowScroller; + } + }); + }, /* 1 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + Object.defineProperty(exports, "__esModule", { + value: !0 + }), exports.ArrowKeyStepper = exports.default = void 0; + var _ArrowKeyStepper2 = __webpack_require__(2), _ArrowKeyStepper3 = _interopRequireDefault(_ArrowKeyStepper2); + exports.default = _ArrowKeyStepper3.default, exports.ArrowKeyStepper = _ArrowKeyStepper3.default; + }, /* 2 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + Object.defineProperty(exports, "__esModule", { + value: !0 + }); + var _getPrototypeOf = __webpack_require__(3), _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf), _classCallCheck2 = __webpack_require__(29), _classCallCheck3 = _interopRequireDefault(_classCallCheck2), _createClass2 = __webpack_require__(30), _createClass3 = _interopRequireDefault(_createClass2), _possibleConstructorReturn2 = __webpack_require__(34), _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2), _inherits2 = __webpack_require__(81), _inherits3 = _interopRequireDefault(_inherits2), _react = __webpack_require__(89), _react2 = _interopRequireDefault(_react), _reactAddonsShallowCompare = __webpack_require__(90), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), ArrowKeyStepper = function(_Component) { + function ArrowKeyStepper(props, context) { + (0, _classCallCheck3.default)(this, ArrowKeyStepper); + var _this = (0, _possibleConstructorReturn3.default)(this, (ArrowKeyStepper.__proto__ || (0, + _getPrototypeOf2.default)(ArrowKeyStepper)).call(this, props, context)); + return _this.state = { + scrollToColumn: 0, + scrollToRow: 0 + }, _this._columnStartIndex = 0, _this._columnStopIndex = 0, _this._rowStartIndex = 0, + _this._rowStopIndex = 0, _this._onKeyDown = _this._onKeyDown.bind(_this), _this._onSectionRendered = _this._onSectionRendered.bind(_this), + _this; + } + return (0, _inherits3.default)(ArrowKeyStepper, _Component), (0, _createClass3.default)(ArrowKeyStepper, [ { + key: "render", + value: function() { + var _props = this.props, className = _props.className, children = _props.children, _state = this.state, scrollToColumn = _state.scrollToColumn, scrollToRow = _state.scrollToRow; + return _react2.default.createElement("div", { + className: className, + onKeyDown: this._onKeyDown + }, children({ + onSectionRendered: this._onSectionRendered, + scrollToColumn: scrollToColumn, + scrollToRow: scrollToRow + })); + } + }, { + key: "shouldComponentUpdate", + value: function(nextProps, nextState) { + return (0, _reactAddonsShallowCompare2.default)(this, nextProps, nextState); + } + }, { + key: "_onKeyDown", + value: function(event) { + var _props2 = this.props, columnCount = _props2.columnCount, rowCount = _props2.rowCount; + switch (event.key) { + case "ArrowDown": + event.preventDefault(), this.setState({ + scrollToRow: Math.min(this._rowStopIndex + 1, rowCount - 1) + }); + break; + + case "ArrowLeft": + event.preventDefault(), this.setState({ + scrollToColumn: Math.max(this._columnStartIndex - 1, 0) + }); + break; + + case "ArrowRight": + event.preventDefault(), this.setState({ + scrollToColumn: Math.min(this._columnStopIndex + 1, columnCount - 1) + }); + break; + + case "ArrowUp": + event.preventDefault(), this.setState({ + scrollToRow: Math.max(this._rowStartIndex - 1, 0) + }); + } + } + }, { + key: "_onSectionRendered", + value: function(_ref) { + var columnStartIndex = _ref.columnStartIndex, columnStopIndex = _ref.columnStopIndex, rowStartIndex = _ref.rowStartIndex, rowStopIndex = _ref.rowStopIndex; + this._columnStartIndex = columnStartIndex, this._columnStopIndex = columnStopIndex, + this._rowStartIndex = rowStartIndex, this._rowStopIndex = rowStopIndex; + } + } ]), ArrowKeyStepper; + }(_react.Component); + exports.default = ArrowKeyStepper; + }, /* 3 */ + /***/ + function(module, exports, __webpack_require__) { + module.exports = { + default: __webpack_require__(4), + __esModule: !0 + }; + }, /* 4 */ + /***/ + function(module, exports, __webpack_require__) { + __webpack_require__(5), module.exports = __webpack_require__(16).Object.getPrototypeOf; + }, /* 5 */ + /***/ + function(module, exports, __webpack_require__) { + // 19.1.2.9 Object.getPrototypeOf(O) + var toObject = __webpack_require__(6), $getPrototypeOf = __webpack_require__(8); + __webpack_require__(14)("getPrototypeOf", function() { + return function(it) { + return $getPrototypeOf(toObject(it)); + }; + }); + }, /* 6 */ + /***/ + function(module, exports, __webpack_require__) { + // 7.1.13 ToObject(argument) + var defined = __webpack_require__(7); + module.exports = function(it) { + return Object(defined(it)); + }; + }, /* 7 */ + /***/ + function(module, exports) { + // 7.2.1 RequireObjectCoercible(argument) + module.exports = function(it) { + if (void 0 == it) throw TypeError("Can't call method on " + it); + return it; + }; + }, /* 8 */ + /***/ + function(module, exports, __webpack_require__) { + // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) + var has = __webpack_require__(9), toObject = __webpack_require__(6), IE_PROTO = __webpack_require__(10)("IE_PROTO"), ObjectProto = Object.prototype; + module.exports = Object.getPrototypeOf || function(O) { + return O = toObject(O), has(O, IE_PROTO) ? O[IE_PROTO] : "function" == typeof O.constructor && O instanceof O.constructor ? O.constructor.prototype : O instanceof Object ? ObjectProto : null; + }; + }, /* 9 */ + /***/ + function(module, exports) { + var hasOwnProperty = {}.hasOwnProperty; + module.exports = function(it, key) { + return hasOwnProperty.call(it, key); + }; + }, /* 10 */ + /***/ + function(module, exports, __webpack_require__) { + var shared = __webpack_require__(11)("keys"), uid = __webpack_require__(13); + module.exports = function(key) { + return shared[key] || (shared[key] = uid(key)); + }; + }, /* 11 */ + /***/ + function(module, exports, __webpack_require__) { + var global = __webpack_require__(12), SHARED = "__core-js_shared__", store = global[SHARED] || (global[SHARED] = {}); + module.exports = function(key) { + return store[key] || (store[key] = {}); + }; + }, /* 12 */ + /***/ + function(module, exports) { + // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 + var global = module.exports = "undefined" != typeof window && window.Math == Math ? window : "undefined" != typeof self && self.Math == Math ? self : Function("return this")(); + "number" == typeof __g && (__g = global); + }, /* 13 */ + /***/ + function(module, exports) { + var id = 0, px = Math.random(); + module.exports = function(key) { + return "Symbol(".concat(void 0 === key ? "" : key, ")_", (++id + px).toString(36)); + }; + }, /* 14 */ + /***/ + function(module, exports, __webpack_require__) { + // most Object methods by ES6 should accept primitives + var $export = __webpack_require__(15), core = __webpack_require__(16), fails = __webpack_require__(25); + module.exports = function(KEY, exec) { + var fn = (core.Object || {})[KEY] || Object[KEY], exp = {}; + exp[KEY] = exec(fn), $export($export.S + $export.F * fails(function() { + fn(1); + }), "Object", exp); + }; + }, /* 15 */ + /***/ + function(module, exports, __webpack_require__) { + var global = __webpack_require__(12), core = __webpack_require__(16), ctx = __webpack_require__(17), hide = __webpack_require__(19), PROTOTYPE = "prototype", $export = function(type, name, source) { + var key, own, out, IS_FORCED = type & $export.F, IS_GLOBAL = type & $export.G, IS_STATIC = type & $export.S, IS_PROTO = type & $export.P, IS_BIND = type & $export.B, IS_WRAP = type & $export.W, exports = IS_GLOBAL ? core : core[name] || (core[name] = {}), expProto = exports[PROTOTYPE], target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE]; + IS_GLOBAL && (source = name); + for (key in source) // contains in native + own = !IS_FORCED && target && void 0 !== target[key], own && key in exports || (// export native or passed + out = own ? target[key] : source[key], // prevent global pollution for namespaces + exports[key] = IS_GLOBAL && "function" != typeof target[key] ? source[key] : IS_BIND && own ? ctx(out, global) : IS_WRAP && target[key] == out ? function(C) { + var F = function(a, b, c) { + if (this instanceof C) { + switch (arguments.length) { + case 0: + return new C(); + + case 1: + return new C(a); + + case 2: + return new C(a, b); + } + return new C(a, b, c); + } + return C.apply(this, arguments); + }; + return F[PROTOTYPE] = C[PROTOTYPE], F; + }(out) : IS_PROTO && "function" == typeof out ? ctx(Function.call, out) : out, // export proto methods to core.%CONSTRUCTOR%.methods.%NAME% + IS_PROTO && ((exports.virtual || (exports.virtual = {}))[key] = out, // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME% + type & $export.R && expProto && !expProto[key] && hide(expProto, key, out))); + }; + // type bitmap + $export.F = 1, // forced + $export.G = 2, // global + $export.S = 4, // static + $export.P = 8, // proto + $export.B = 16, // bind + $export.W = 32, // wrap + $export.U = 64, // safe + $export.R = 128, // real proto method for `library` + module.exports = $export; + }, /* 16 */ + /***/ + function(module, exports) { + var core = module.exports = { + version: "2.4.0" + }; + "number" == typeof __e && (__e = core); + }, /* 17 */ + /***/ + function(module, exports, __webpack_require__) { + // optional / simple context binding + var aFunction = __webpack_require__(18); + module.exports = function(fn, that, length) { + if (aFunction(fn), void 0 === that) return fn; + switch (length) { + case 1: + return function(a) { + return fn.call(that, a); + }; + + case 2: + return function(a, b) { + return fn.call(that, a, b); + }; + + case 3: + return function(a, b, c) { + return fn.call(that, a, b, c); + }; + } + return function() { + return fn.apply(that, arguments); + }; + }; + }, /* 18 */ + /***/ + function(module, exports) { + module.exports = function(it) { + if ("function" != typeof it) throw TypeError(it + " is not a function!"); + return it; + }; + }, /* 19 */ + /***/ + function(module, exports, __webpack_require__) { + var dP = __webpack_require__(20), createDesc = __webpack_require__(28); + module.exports = __webpack_require__(24) ? function(object, key, value) { + return dP.f(object, key, createDesc(1, value)); + } : function(object, key, value) { + return object[key] = value, object; + }; + }, /* 20 */ + /***/ + function(module, exports, __webpack_require__) { + var anObject = __webpack_require__(21), IE8_DOM_DEFINE = __webpack_require__(23), toPrimitive = __webpack_require__(27), dP = Object.defineProperty; + exports.f = __webpack_require__(24) ? Object.defineProperty : function(O, P, Attributes) { + if (anObject(O), P = toPrimitive(P, !0), anObject(Attributes), IE8_DOM_DEFINE) try { + return dP(O, P, Attributes); + } catch (e) {} + if ("get" in Attributes || "set" in Attributes) throw TypeError("Accessors not supported!"); + return "value" in Attributes && (O[P] = Attributes.value), O; + }; + }, /* 21 */ + /***/ + function(module, exports, __webpack_require__) { + var isObject = __webpack_require__(22); + module.exports = function(it) { + if (!isObject(it)) throw TypeError(it + " is not an object!"); + return it; + }; + }, /* 22 */ + /***/ + function(module, exports) { + module.exports = function(it) { + return "object" == typeof it ? null !== it : "function" == typeof it; + }; + }, /* 23 */ + /***/ + function(module, exports, __webpack_require__) { + module.exports = !__webpack_require__(24) && !__webpack_require__(25)(function() { + return 7 != Object.defineProperty(__webpack_require__(26)("div"), "a", { + get: function() { + return 7; + } + }).a; + }); + }, /* 24 */ + /***/ + function(module, exports, __webpack_require__) { + // Thank's IE8 for his funny defineProperty + module.exports = !__webpack_require__(25)(function() { + return 7 != Object.defineProperty({}, "a", { + get: function() { + return 7; + } + }).a; + }); + }, /* 25 */ + /***/ + function(module, exports) { + module.exports = function(exec) { + try { + return !!exec(); + } catch (e) { + return !0; + } + }; + }, /* 26 */ + /***/ + function(module, exports, __webpack_require__) { + var isObject = __webpack_require__(22), document = __webpack_require__(12).document, is = isObject(document) && isObject(document.createElement); + module.exports = function(it) { + return is ? document.createElementNS("http://www.w3.org/1999/xhtml",it) : {}; + }; + }, /* 27 */ + /***/ + function(module, exports, __webpack_require__) { + // 7.1.1 ToPrimitive(input [, PreferredType]) + var isObject = __webpack_require__(22); + // instead of the ES6 spec version, we didn't implement @@toPrimitive case + // and the second argument - flag - preferred type is a string + module.exports = function(it, S) { + if (!isObject(it)) return it; + var fn, val; + if (S && "function" == typeof (fn = it.toString) && !isObject(val = fn.call(it))) return val; + if ("function" == typeof (fn = it.valueOf) && !isObject(val = fn.call(it))) return val; + if (!S && "function" == typeof (fn = it.toString) && !isObject(val = fn.call(it))) return val; + throw TypeError("Can't convert object to primitive value"); + }; + }, /* 28 */ + /***/ + function(module, exports) { + module.exports = function(bitmap, value) { + return { + enumerable: !(1 & bitmap), + configurable: !(2 & bitmap), + writable: !(4 & bitmap), + value: value + }; + }; + }, /* 29 */ + /***/ + function(module, exports) { + "use strict"; + exports.__esModule = !0, exports.default = function(instance, Constructor) { + if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); + }; + }, /* 30 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + exports.__esModule = !0; + var _defineProperty = __webpack_require__(31), _defineProperty2 = _interopRequireDefault(_defineProperty); + exports.default = function() { + function defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, + "value" in descriptor && (descriptor.writable = !0), (0, _defineProperty2.default)(target, descriptor.key, descriptor); + } + } + return function(Constructor, protoProps, staticProps) { + return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), + Constructor; + }; + }(); + }, /* 31 */ + /***/ + function(module, exports, __webpack_require__) { + module.exports = { + default: __webpack_require__(32), + __esModule: !0 + }; + }, /* 32 */ + /***/ + function(module, exports, __webpack_require__) { + __webpack_require__(33); + var $Object = __webpack_require__(16).Object; + module.exports = function(it, key, desc) { + return $Object.defineProperty(it, key, desc); + }; + }, /* 33 */ + /***/ + function(module, exports, __webpack_require__) { + var $export = __webpack_require__(15); + // 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) + $export($export.S + $export.F * !__webpack_require__(24), "Object", { + defineProperty: __webpack_require__(20).f + }); + }, /* 34 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + exports.__esModule = !0; + var _typeof2 = __webpack_require__(35), _typeof3 = _interopRequireDefault(_typeof2); + exports.default = function(self, call) { + if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + return !call || "object" !== ("undefined" == typeof call ? "undefined" : (0, _typeof3.default)(call)) && "function" != typeof call ? self : call; + }; + }, /* 35 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + exports.__esModule = !0; + var _iterator = __webpack_require__(36), _iterator2 = _interopRequireDefault(_iterator), _symbol = __webpack_require__(65), _symbol2 = _interopRequireDefault(_symbol), _typeof = "function" == typeof _symbol2.default && "symbol" == typeof _iterator2.default ? function(obj) { + return typeof obj; + } : function(obj) { + return obj && "function" == typeof _symbol2.default && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj; + }; + exports.default = "function" == typeof _symbol2.default && "symbol" === _typeof(_iterator2.default) ? function(obj) { + return "undefined" == typeof obj ? "undefined" : _typeof(obj); + } : function(obj) { + return obj && "function" == typeof _symbol2.default && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : "undefined" == typeof obj ? "undefined" : _typeof(obj); + }; + }, /* 36 */ + /***/ + function(module, exports, __webpack_require__) { + module.exports = { + default: __webpack_require__(37), + __esModule: !0 + }; + }, /* 37 */ + /***/ + function(module, exports, __webpack_require__) { + __webpack_require__(38), __webpack_require__(60), module.exports = __webpack_require__(64).f("iterator"); + }, /* 38 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + var $at = __webpack_require__(39)(!0); + // 21.1.3.27 String.prototype[@@iterator]() + __webpack_require__(41)(String, "String", function(iterated) { + this._t = String(iterated), // target + this._i = 0; + }, function() { + var point, O = this._t, index = this._i; + return index >= O.length ? { + value: void 0, + done: !0 + } : (point = $at(O, index), this._i += point.length, { + value: point, + done: !1 + }); + }); + }, /* 39 */ + /***/ + function(module, exports, __webpack_require__) { + var toInteger = __webpack_require__(40), defined = __webpack_require__(7); + // true -> String#at + // false -> String#codePointAt + module.exports = function(TO_STRING) { + return function(that, pos) { + var a, b, s = String(defined(that)), i = toInteger(pos), l = s.length; + return i < 0 || i >= l ? TO_STRING ? "" : void 0 : (a = s.charCodeAt(i), a < 55296 || a > 56319 || i + 1 === l || (b = s.charCodeAt(i + 1)) < 56320 || b > 57343 ? TO_STRING ? s.charAt(i) : a : TO_STRING ? s.slice(i, i + 2) : (a - 55296 << 10) + (b - 56320) + 65536); + }; + }; + }, /* 40 */ + /***/ + function(module, exports) { + // 7.1.4 ToInteger + var ceil = Math.ceil, floor = Math.floor; + module.exports = function(it) { + return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); + }; + }, /* 41 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + var LIBRARY = __webpack_require__(42), $export = __webpack_require__(15), redefine = __webpack_require__(43), hide = __webpack_require__(19), has = __webpack_require__(9), Iterators = __webpack_require__(44), $iterCreate = __webpack_require__(45), setToStringTag = __webpack_require__(58), getPrototypeOf = __webpack_require__(8), ITERATOR = __webpack_require__(59)("iterator"), BUGGY = !([].keys && "next" in [].keys()), FF_ITERATOR = "@@iterator", KEYS = "keys", VALUES = "values", returnThis = function() { + return this; + }; + module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) { + $iterCreate(Constructor, NAME, next); + var methods, key, IteratorPrototype, getMethod = function(kind) { + if (!BUGGY && kind in proto) return proto[kind]; + switch (kind) { + case KEYS: + return function() { + return new Constructor(this, kind); + }; + + case VALUES: + return function() { + return new Constructor(this, kind); + }; + } + return function() { + return new Constructor(this, kind); + }; + }, TAG = NAME + " Iterator", DEF_VALUES = DEFAULT == VALUES, VALUES_BUG = !1, proto = Base.prototype, $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT], $default = $native || getMethod(DEFAULT), $entries = DEFAULT ? DEF_VALUES ? getMethod("entries") : $default : void 0, $anyNative = "Array" == NAME ? proto.entries || $native : $native; + if (// Fix native + $anyNative && (IteratorPrototype = getPrototypeOf($anyNative.call(new Base())), + IteratorPrototype !== Object.prototype && (// Set @@toStringTag to native iterators + setToStringTag(IteratorPrototype, TAG, !0), // fix for some old engines + LIBRARY || has(IteratorPrototype, ITERATOR) || hide(IteratorPrototype, ITERATOR, returnThis))), + // fix Array#{values, @@iterator}.name in V8 / FF + DEF_VALUES && $native && $native.name !== VALUES && (VALUES_BUG = !0, $default = function() { + return $native.call(this); + }), // Define iterator + LIBRARY && !FORCED || !BUGGY && !VALUES_BUG && proto[ITERATOR] || hide(proto, ITERATOR, $default), + // Plug for library + Iterators[NAME] = $default, Iterators[TAG] = returnThis, DEFAULT) if (methods = { + values: DEF_VALUES ? $default : getMethod(VALUES), + keys: IS_SET ? $default : getMethod(KEYS), + entries: $entries + }, FORCED) for (key in methods) key in proto || redefine(proto, key, methods[key]); else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); + return methods; + }; + }, /* 42 */ + /***/ + function(module, exports) { + module.exports = !0; + }, /* 43 */ + /***/ + function(module, exports, __webpack_require__) { + module.exports = __webpack_require__(19); + }, /* 44 */ + /***/ + function(module, exports) { + module.exports = {}; + }, /* 45 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + var create = __webpack_require__(46), descriptor = __webpack_require__(28), setToStringTag = __webpack_require__(58), IteratorPrototype = {}; + // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() + __webpack_require__(19)(IteratorPrototype, __webpack_require__(59)("iterator"), function() { + return this; + }), module.exports = function(Constructor, NAME, next) { + Constructor.prototype = create(IteratorPrototype, { + next: descriptor(1, next) + }), setToStringTag(Constructor, NAME + " Iterator"); + }; + }, /* 46 */ + /***/ + function(module, exports, __webpack_require__) { + // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) + var anObject = __webpack_require__(21), dPs = __webpack_require__(47), enumBugKeys = __webpack_require__(56), IE_PROTO = __webpack_require__(10)("IE_PROTO"), Empty = function() {}, PROTOTYPE = "prototype", createDict = function() { + // Thrash, waste and sodomy: IE GC bug + var iframeDocument, iframe = __webpack_require__(26)("iframe"), i = enumBugKeys.length, lt = "<", gt = ">"; + for (iframe.style.display = "none", __webpack_require__(57).appendChild(iframe), + iframe.src = "javascript:", // eslint-disable-line no-script-url + // createDict = iframe.contentWindow.Object; + // html.removeChild(iframe); + iframeDocument = iframe.contentWindow.document, iframeDocument.open(), iframeDocument.write(lt + "script" + gt + "document.F=Object" + lt + "/script" + gt), + iframeDocument.close(), createDict = iframeDocument.F; i--; ) delete createDict[PROTOTYPE][enumBugKeys[i]]; + return createDict(); + }; + module.exports = Object.create || function(O, Properties) { + var result; + // add "__proto__" for Object.getPrototypeOf polyfill + return null !== O ? (Empty[PROTOTYPE] = anObject(O), result = new Empty(), Empty[PROTOTYPE] = null, + result[IE_PROTO] = O) : result = createDict(), void 0 === Properties ? result : dPs(result, Properties); + }; + }, /* 47 */ + /***/ + function(module, exports, __webpack_require__) { + var dP = __webpack_require__(20), anObject = __webpack_require__(21), getKeys = __webpack_require__(48); + module.exports = __webpack_require__(24) ? Object.defineProperties : function(O, Properties) { + anObject(O); + for (var P, keys = getKeys(Properties), length = keys.length, i = 0; length > i; ) dP.f(O, P = keys[i++], Properties[P]); + return O; + }; + }, /* 48 */ + /***/ + function(module, exports, __webpack_require__) { + // 19.1.2.14 / 15.2.3.14 Object.keys(O) + var $keys = __webpack_require__(49), enumBugKeys = __webpack_require__(56); + module.exports = Object.keys || function(O) { + return $keys(O, enumBugKeys); + }; + }, /* 49 */ + /***/ + function(module, exports, __webpack_require__) { + var has = __webpack_require__(9), toIObject = __webpack_require__(50), arrayIndexOf = __webpack_require__(53)(!1), IE_PROTO = __webpack_require__(10)("IE_PROTO"); + module.exports = function(object, names) { + var key, O = toIObject(object), i = 0, result = []; + for (key in O) key != IE_PROTO && has(O, key) && result.push(key); + // Don't enum bug & hidden keys + for (;names.length > i; ) has(O, key = names[i++]) && (~arrayIndexOf(result, key) || result.push(key)); + return result; + }; + }, /* 50 */ + /***/ + function(module, exports, __webpack_require__) { + // to indexed object, toObject with fallback for non-array-like ES3 strings + var IObject = __webpack_require__(51), defined = __webpack_require__(7); + module.exports = function(it) { + return IObject(defined(it)); + }; + }, /* 51 */ + /***/ + function(module, exports, __webpack_require__) { + // fallback for non-array-like ES3 and non-enumerable old V8 strings + var cof = __webpack_require__(52); + module.exports = Object("z").propertyIsEnumerable(0) ? Object : function(it) { + return "String" == cof(it) ? it.split("") : Object(it); + }; + }, /* 52 */ + /***/ + function(module, exports) { + var toString = {}.toString; + module.exports = function(it) { + return toString.call(it).slice(8, -1); + }; + }, /* 53 */ + /***/ + function(module, exports, __webpack_require__) { + // false -> Array#indexOf + // true -> Array#includes + var toIObject = __webpack_require__(50), toLength = __webpack_require__(54), toIndex = __webpack_require__(55); + module.exports = function(IS_INCLUDES) { + return function($this, el, fromIndex) { + var value, O = toIObject($this), length = toLength(O.length), index = toIndex(fromIndex, length); + // Array#includes uses SameValueZero equality algorithm + if (IS_INCLUDES && el != el) { + for (;length > index; ) if (value = O[index++], value != value) return !0; + } else for (;length > index; index++) if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0; + return !IS_INCLUDES && -1; + }; + }; + }, /* 54 */ + /***/ + function(module, exports, __webpack_require__) { + // 7.1.15 ToLength + var toInteger = __webpack_require__(40), min = Math.min; + module.exports = function(it) { + return it > 0 ? min(toInteger(it), 9007199254740991) : 0; + }; + }, /* 55 */ + /***/ + function(module, exports, __webpack_require__) { + var toInteger = __webpack_require__(40), max = Math.max, min = Math.min; + module.exports = function(index, length) { + return index = toInteger(index), index < 0 ? max(index + length, 0) : min(index, length); + }; + }, /* 56 */ + /***/ + function(module, exports) { + // IE 8- don't enum bug keys + module.exports = "constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(","); + }, /* 57 */ + /***/ + function(module, exports, __webpack_require__) { + module.exports = __webpack_require__(12).document && document.documentElement; + }, /* 58 */ + /***/ + function(module, exports, __webpack_require__) { + var def = __webpack_require__(20).f, has = __webpack_require__(9), TAG = __webpack_require__(59)("toStringTag"); + module.exports = function(it, tag, stat) { + it && !has(it = stat ? it : it.prototype, TAG) && def(it, TAG, { + configurable: !0, + value: tag + }); + }; + }, /* 59 */ + /***/ + function(module, exports, __webpack_require__) { + var store = __webpack_require__(11)("wks"), uid = __webpack_require__(13), Symbol = __webpack_require__(12).Symbol, USE_SYMBOL = "function" == typeof Symbol, $exports = module.exports = function(name) { + return store[name] || (store[name] = USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)("Symbol." + name)); + }; + $exports.store = store; + }, /* 60 */ + /***/ + function(module, exports, __webpack_require__) { + __webpack_require__(61); + for (var global = __webpack_require__(12), hide = __webpack_require__(19), Iterators = __webpack_require__(44), TO_STRING_TAG = __webpack_require__(59)("toStringTag"), collections = [ "NodeList", "DOMTokenList", "MediaList", "StyleSheetList", "CSSRuleList" ], i = 0; i < 5; i++) { + var NAME = collections[i], Collection = global[NAME], proto = Collection && Collection.prototype; + proto && !proto[TO_STRING_TAG] && hide(proto, TO_STRING_TAG, NAME), Iterators[NAME] = Iterators.Array; + } + }, /* 61 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + var addToUnscopables = __webpack_require__(62), step = __webpack_require__(63), Iterators = __webpack_require__(44), toIObject = __webpack_require__(50); + // 22.1.3.4 Array.prototype.entries() + // 22.1.3.13 Array.prototype.keys() + // 22.1.3.29 Array.prototype.values() + // 22.1.3.30 Array.prototype[@@iterator]() + module.exports = __webpack_require__(41)(Array, "Array", function(iterated, kind) { + this._t = toIObject(iterated), // target + this._i = 0, // next index + this._k = kind; + }, function() { + var O = this._t, kind = this._k, index = this._i++; + return !O || index >= O.length ? (this._t = void 0, step(1)) : "keys" == kind ? step(0, index) : "values" == kind ? step(0, O[index]) : step(0, [ index, O[index] ]); + }, "values"), // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) + Iterators.Arguments = Iterators.Array, addToUnscopables("keys"), addToUnscopables("values"), + addToUnscopables("entries"); + }, /* 62 */ + /***/ + function(module, exports) { + module.exports = function() {}; + }, /* 63 */ + /***/ + function(module, exports) { + module.exports = function(done, value) { + return { + value: value, + done: !!done + }; + }; + }, /* 64 */ + /***/ + function(module, exports, __webpack_require__) { + exports.f = __webpack_require__(59); + }, /* 65 */ + /***/ + function(module, exports, __webpack_require__) { + module.exports = { + default: __webpack_require__(66), + __esModule: !0 + }; + }, /* 66 */ + /***/ + function(module, exports, __webpack_require__) { + __webpack_require__(67), __webpack_require__(78), __webpack_require__(79), __webpack_require__(80), + module.exports = __webpack_require__(16).Symbol; + }, /* 67 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + // ECMAScript 6 symbols shim + var global = __webpack_require__(12), has = __webpack_require__(9), DESCRIPTORS = __webpack_require__(24), $export = __webpack_require__(15), redefine = __webpack_require__(43), META = __webpack_require__(68).KEY, $fails = __webpack_require__(25), shared = __webpack_require__(11), setToStringTag = __webpack_require__(58), uid = __webpack_require__(13), wks = __webpack_require__(59), wksExt = __webpack_require__(64), wksDefine = __webpack_require__(69), keyOf = __webpack_require__(70), enumKeys = __webpack_require__(71), isArray = __webpack_require__(74), anObject = __webpack_require__(21), toIObject = __webpack_require__(50), toPrimitive = __webpack_require__(27), createDesc = __webpack_require__(28), _create = __webpack_require__(46), gOPNExt = __webpack_require__(75), $GOPD = __webpack_require__(77), $DP = __webpack_require__(20), $keys = __webpack_require__(48), gOPD = $GOPD.f, dP = $DP.f, gOPN = gOPNExt.f, $Symbol = global.Symbol, $JSON = global.JSON, _stringify = $JSON && $JSON.stringify, PROTOTYPE = "prototype", HIDDEN = wks("_hidden"), TO_PRIMITIVE = wks("toPrimitive"), isEnum = {}.propertyIsEnumerable, SymbolRegistry = shared("symbol-registry"), AllSymbols = shared("symbols"), OPSymbols = shared("op-symbols"), ObjectProto = Object[PROTOTYPE], USE_NATIVE = "function" == typeof $Symbol, QObject = global.QObject, setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild, setSymbolDesc = DESCRIPTORS && $fails(function() { + return 7 != _create(dP({}, "a", { + get: function() { + return dP(this, "a", { + value: 7 + }).a; + } + })).a; + }) ? function(it, key, D) { + var protoDesc = gOPD(ObjectProto, key); + protoDesc && delete ObjectProto[key], dP(it, key, D), protoDesc && it !== ObjectProto && dP(ObjectProto, key, protoDesc); + } : dP, wrap = function(tag) { + var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]); + return sym._k = tag, sym; + }, isSymbol = USE_NATIVE && "symbol" == typeof $Symbol.iterator ? function(it) { + return "symbol" == typeof it; + } : function(it) { + return it instanceof $Symbol; + }, $defineProperty = function(it, key, D) { + return it === ObjectProto && $defineProperty(OPSymbols, key, D), anObject(it), key = toPrimitive(key, !0), + anObject(D), has(AllSymbols, key) ? (D.enumerable ? (has(it, HIDDEN) && it[HIDDEN][key] && (it[HIDDEN][key] = !1), + D = _create(D, { + enumerable: createDesc(0, !1) + })) : (has(it, HIDDEN) || dP(it, HIDDEN, createDesc(1, {})), it[HIDDEN][key] = !0), + setSymbolDesc(it, key, D)) : dP(it, key, D); + }, $defineProperties = function(it, P) { + anObject(it); + for (var key, keys = enumKeys(P = toIObject(P)), i = 0, l = keys.length; l > i; ) $defineProperty(it, key = keys[i++], P[key]); + return it; + }, $create = function(it, P) { + return void 0 === P ? _create(it) : $defineProperties(_create(it), P); + }, $propertyIsEnumerable = function(key) { + var E = isEnum.call(this, key = toPrimitive(key, !0)); + return !(this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) && (!(E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key]) || E); + }, $getOwnPropertyDescriptor = function(it, key) { + if (it = toIObject(it), key = toPrimitive(key, !0), it !== ObjectProto || !has(AllSymbols, key) || has(OPSymbols, key)) { + var D = gOPD(it, key); + return !D || !has(AllSymbols, key) || has(it, HIDDEN) && it[HIDDEN][key] || (D.enumerable = !0), + D; + } + }, $getOwnPropertyNames = function(it) { + for (var key, names = gOPN(toIObject(it)), result = [], i = 0; names.length > i; ) has(AllSymbols, key = names[i++]) || key == HIDDEN || key == META || result.push(key); + return result; + }, $getOwnPropertySymbols = function(it) { + for (var key, IS_OP = it === ObjectProto, names = gOPN(IS_OP ? OPSymbols : toIObject(it)), result = [], i = 0; names.length > i; ) !has(AllSymbols, key = names[i++]) || IS_OP && !has(ObjectProto, key) || result.push(AllSymbols[key]); + return result; + }; + // 19.4.1.1 Symbol([description]) + USE_NATIVE || ($Symbol = function() { + if (this instanceof $Symbol) throw TypeError("Symbol is not a constructor!"); + var tag = uid(arguments.length > 0 ? arguments[0] : void 0), $set = function(value) { + this === ObjectProto && $set.call(OPSymbols, value), has(this, HIDDEN) && has(this[HIDDEN], tag) && (this[HIDDEN][tag] = !1), + setSymbolDesc(this, tag, createDesc(1, value)); + }; + return DESCRIPTORS && setter && setSymbolDesc(ObjectProto, tag, { + configurable: !0, + set: $set + }), wrap(tag); + }, redefine($Symbol[PROTOTYPE], "toString", function() { + return this._k; + }), $GOPD.f = $getOwnPropertyDescriptor, $DP.f = $defineProperty, __webpack_require__(76).f = gOPNExt.f = $getOwnPropertyNames, + __webpack_require__(73).f = $propertyIsEnumerable, __webpack_require__(72).f = $getOwnPropertySymbols, + DESCRIPTORS && !__webpack_require__(42) && redefine(ObjectProto, "propertyIsEnumerable", $propertyIsEnumerable, !0), + wksExt.f = function(name) { + return wrap(wks(name)); + }), $export($export.G + $export.W + $export.F * !USE_NATIVE, { + Symbol: $Symbol + }); + for (var symbols = "hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","), i = 0; symbols.length > i; ) wks(symbols[i++]); + for (var symbols = $keys(wks.store), i = 0; symbols.length > i; ) wksDefine(symbols[i++]); + $export($export.S + $export.F * !USE_NATIVE, "Symbol", { + // 19.4.2.1 Symbol.for(key) + for: function(key) { + return has(SymbolRegistry, key += "") ? SymbolRegistry[key] : SymbolRegistry[key] = $Symbol(key); + }, + // 19.4.2.5 Symbol.keyFor(sym) + keyFor: function(key) { + if (isSymbol(key)) return keyOf(SymbolRegistry, key); + throw TypeError(key + " is not a symbol!"); + }, + useSetter: function() { + setter = !0; + }, + useSimple: function() { + setter = !1; + } + }), $export($export.S + $export.F * !USE_NATIVE, "Object", { + // 19.1.2.2 Object.create(O [, Properties]) + create: $create, + // 19.1.2.4 Object.defineProperty(O, P, Attributes) + defineProperty: $defineProperty, + // 19.1.2.3 Object.defineProperties(O, Properties) + defineProperties: $defineProperties, + // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) + getOwnPropertyDescriptor: $getOwnPropertyDescriptor, + // 19.1.2.7 Object.getOwnPropertyNames(O) + getOwnPropertyNames: $getOwnPropertyNames, + // 19.1.2.8 Object.getOwnPropertySymbols(O) + getOwnPropertySymbols: $getOwnPropertySymbols + }), // 24.3.2 JSON.stringify(value [, replacer [, space]]) + $JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function() { + var S = $Symbol(); + // MS Edge converts symbol values to JSON as {} + // WebKit converts symbol values to JSON as null + // V8 throws on boxed symbols + return "[null]" != _stringify([ S ]) || "{}" != _stringify({ + a: S + }) || "{}" != _stringify(Object(S)); + })), "JSON", { + stringify: function(it) { + if (void 0 !== it && !isSymbol(it)) { + for (// IE8 returns string on undefined + var replacer, $replacer, args = [ it ], i = 1; arguments.length > i; ) args.push(arguments[i++]); + return replacer = args[1], "function" == typeof replacer && ($replacer = replacer), + !$replacer && isArray(replacer) || (replacer = function(key, value) { + if ($replacer && (value = $replacer.call(this, key, value)), !isSymbol(value)) return value; + }), args[1] = replacer, _stringify.apply($JSON, args); + } + } + }), // 19.4.3.4 Symbol.prototype[@@toPrimitive](hint) + $Symbol[PROTOTYPE][TO_PRIMITIVE] || __webpack_require__(19)($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf), + // 19.4.3.5 Symbol.prototype[@@toStringTag] + setToStringTag($Symbol, "Symbol"), // 20.2.1.9 Math[@@toStringTag] + setToStringTag(Math, "Math", !0), // 24.3.3 JSON[@@toStringTag] + setToStringTag(global.JSON, "JSON", !0); + }, /* 68 */ + /***/ + function(module, exports, __webpack_require__) { + var META = __webpack_require__(13)("meta"), isObject = __webpack_require__(22), has = __webpack_require__(9), setDesc = __webpack_require__(20).f, id = 0, isExtensible = Object.isExtensible || function() { + return !0; + }, FREEZE = !__webpack_require__(25)(function() { + return isExtensible(Object.preventExtensions({})); + }), setMeta = function(it) { + setDesc(it, META, { + value: { + i: "O" + ++id, + // object ID + w: {} + } + }); + }, fastKey = function(it, create) { + // return primitive with prefix + if (!isObject(it)) return "symbol" == typeof it ? it : ("string" == typeof it ? "S" : "P") + it; + if (!has(it, META)) { + // can't set metadata to uncaught frozen object + if (!isExtensible(it)) return "F"; + // not necessary to add metadata + if (!create) return "E"; + // add missing metadata + setMeta(it); + } + return it[META].i; + }, getWeak = function(it, create) { + if (!has(it, META)) { + // can't set metadata to uncaught frozen object + if (!isExtensible(it)) return !0; + // not necessary to add metadata + if (!create) return !1; + // add missing metadata + setMeta(it); + } + return it[META].w; + }, onFreeze = function(it) { + return FREEZE && meta.NEED && isExtensible(it) && !has(it, META) && setMeta(it), + it; + }, meta = module.exports = { + KEY: META, + NEED: !1, + fastKey: fastKey, + getWeak: getWeak, + onFreeze: onFreeze + }; + }, /* 69 */ + /***/ + function(module, exports, __webpack_require__) { + var global = __webpack_require__(12), core = __webpack_require__(16), LIBRARY = __webpack_require__(42), wksExt = __webpack_require__(64), defineProperty = __webpack_require__(20).f; + module.exports = function(name) { + var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {}); + "_" == name.charAt(0) || name in $Symbol || defineProperty($Symbol, name, { + value: wksExt.f(name) + }); + }; + }, /* 70 */ + /***/ + function(module, exports, __webpack_require__) { + var getKeys = __webpack_require__(48), toIObject = __webpack_require__(50); + module.exports = function(object, el) { + for (var key, O = toIObject(object), keys = getKeys(O), length = keys.length, index = 0; length > index; ) if (O[key = keys[index++]] === el) return key; + }; + }, /* 71 */ + /***/ + function(module, exports, __webpack_require__) { + // all enumerable object keys, includes symbols + var getKeys = __webpack_require__(48), gOPS = __webpack_require__(72), pIE = __webpack_require__(73); + module.exports = function(it) { + var result = getKeys(it), getSymbols = gOPS.f; + if (getSymbols) for (var key, symbols = getSymbols(it), isEnum = pIE.f, i = 0; symbols.length > i; ) isEnum.call(it, key = symbols[i++]) && result.push(key); + return result; + }; + }, /* 72 */ + /***/ + function(module, exports) { + exports.f = Object.getOwnPropertySymbols; + }, /* 73 */ + /***/ + function(module, exports) { + exports.f = {}.propertyIsEnumerable; + }, /* 74 */ + /***/ + function(module, exports, __webpack_require__) { + // 7.2.2 IsArray(argument) + var cof = __webpack_require__(52); + module.exports = Array.isArray || function(arg) { + return "Array" == cof(arg); + }; + }, /* 75 */ + /***/ + function(module, exports, __webpack_require__) { + // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window + var toIObject = __webpack_require__(50), gOPN = __webpack_require__(76).f, toString = {}.toString, windowNames = "object" == typeof window && window && Object.getOwnPropertyNames ? Object.getOwnPropertyNames(window) : [], getWindowNames = function(it) { + try { + return gOPN(it); + } catch (e) { + return windowNames.slice(); + } + }; + module.exports.f = function(it) { + return windowNames && "[object Window]" == toString.call(it) ? getWindowNames(it) : gOPN(toIObject(it)); + }; + }, /* 76 */ + /***/ + function(module, exports, __webpack_require__) { + // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) + var $keys = __webpack_require__(49), hiddenKeys = __webpack_require__(56).concat("length", "prototype"); + exports.f = Object.getOwnPropertyNames || function(O) { + return $keys(O, hiddenKeys); + }; + }, /* 77 */ + /***/ + function(module, exports, __webpack_require__) { + var pIE = __webpack_require__(73), createDesc = __webpack_require__(28), toIObject = __webpack_require__(50), toPrimitive = __webpack_require__(27), has = __webpack_require__(9), IE8_DOM_DEFINE = __webpack_require__(23), gOPD = Object.getOwnPropertyDescriptor; + exports.f = __webpack_require__(24) ? gOPD : function(O, P) { + if (O = toIObject(O), P = toPrimitive(P, !0), IE8_DOM_DEFINE) try { + return gOPD(O, P); + } catch (e) {} + if (has(O, P)) return createDesc(!pIE.f.call(O, P), O[P]); + }; + }, /* 78 */ + /***/ + function(module, exports) {}, /* 79 */ + /***/ + function(module, exports, __webpack_require__) { + __webpack_require__(69)("asyncIterator"); + }, /* 80 */ + /***/ + function(module, exports, __webpack_require__) { + __webpack_require__(69)("observable"); + }, /* 81 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + exports.__esModule = !0; + var _setPrototypeOf = __webpack_require__(82), _setPrototypeOf2 = _interopRequireDefault(_setPrototypeOf), _create = __webpack_require__(86), _create2 = _interopRequireDefault(_create), _typeof2 = __webpack_require__(35), _typeof3 = _interopRequireDefault(_typeof2); + exports.default = function(subClass, superClass) { + if ("function" != typeof superClass && null !== superClass) throw new TypeError("Super expression must either be null or a function, not " + ("undefined" == typeof superClass ? "undefined" : (0, + _typeof3.default)(superClass))); + subClass.prototype = (0, _create2.default)(superClass && superClass.prototype, { + constructor: { + value: subClass, + enumerable: !1, + writable: !0, + configurable: !0 + } + }), superClass && (_setPrototypeOf2.default ? (0, _setPrototypeOf2.default)(subClass, superClass) : subClass.__proto__ = superClass); + }; + }, /* 82 */ + /***/ + function(module, exports, __webpack_require__) { + module.exports = { + default: __webpack_require__(83), + __esModule: !0 + }; + }, /* 83 */ + /***/ + function(module, exports, __webpack_require__) { + __webpack_require__(84), module.exports = __webpack_require__(16).Object.setPrototypeOf; + }, /* 84 */ + /***/ + function(module, exports, __webpack_require__) { + // 19.1.3.19 Object.setPrototypeOf(O, proto) + var $export = __webpack_require__(15); + $export($export.S, "Object", { + setPrototypeOf: __webpack_require__(85).set + }); + }, /* 85 */ + /***/ + function(module, exports, __webpack_require__) { + // Works with __proto__ only. Old v8 can't work with null proto objects. + /* eslint-disable no-proto */ + var isObject = __webpack_require__(22), anObject = __webpack_require__(21), check = function(O, proto) { + if (anObject(O), !isObject(proto) && null !== proto) throw TypeError(proto + ": can't set as prototype!"); + }; + module.exports = { + set: Object.setPrototypeOf || ("__proto__" in {} ? // eslint-disable-line + function(test, buggy, set) { + try { + set = __webpack_require__(17)(Function.call, __webpack_require__(77).f(Object.prototype, "__proto__").set, 2), + set(test, []), buggy = !(test instanceof Array); + } catch (e) { + buggy = !0; + } + return function(O, proto) { + return check(O, proto), buggy ? O.__proto__ = proto : set(O, proto), O; + }; + }({}, !1) : void 0), + check: check + }; + }, /* 86 */ + /***/ + function(module, exports, __webpack_require__) { + module.exports = { + default: __webpack_require__(87), + __esModule: !0 + }; + }, /* 87 */ + /***/ + function(module, exports, __webpack_require__) { + __webpack_require__(88); + var $Object = __webpack_require__(16).Object; + module.exports = function(P, D) { + return $Object.create(P, D); + }; + }, /* 88 */ + /***/ + function(module, exports, __webpack_require__) { + var $export = __webpack_require__(15); + // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) + $export($export.S, "Object", { + create: __webpack_require__(46) + }); + }, /* 89 */ + /***/ + function(module, exports) { + module.exports = __WEBPACK_EXTERNAL_MODULE_89__; + }, /* 90 */ + /***/ + function(module, exports) { + module.exports = __WEBPACK_EXTERNAL_MODULE_90__; + }, /* 91 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + Object.defineProperty(exports, "__esModule", { + value: !0 + }), exports.AutoSizer = exports.default = void 0; + var _AutoSizer2 = __webpack_require__(92), _AutoSizer3 = _interopRequireDefault(_AutoSizer2); + exports.default = _AutoSizer3.default, exports.AutoSizer = _AutoSizer3.default; + }, /* 92 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + Object.defineProperty(exports, "__esModule", { + value: !0 + }); + var _getPrototypeOf = __webpack_require__(3), _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf), _classCallCheck2 = __webpack_require__(29), _classCallCheck3 = _interopRequireDefault(_classCallCheck2), _createClass2 = __webpack_require__(30), _createClass3 = _interopRequireDefault(_createClass2), _possibleConstructorReturn2 = __webpack_require__(34), _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2), _inherits2 = __webpack_require__(81), _inherits3 = _interopRequireDefault(_inherits2), _react = __webpack_require__(89), _react2 = _interopRequireDefault(_react), _reactAddonsShallowCompare = __webpack_require__(90), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), _detectElementResize = __webpack_require__(93), _detectElementResize2 = _interopRequireDefault(_detectElementResize), AutoSizer = function(_Component) { + function AutoSizer(props) { + (0, _classCallCheck3.default)(this, AutoSizer); + var _this = (0, _possibleConstructorReturn3.default)(this, (AutoSizer.__proto__ || (0, + _getPrototypeOf2.default)(AutoSizer)).call(this, props)); + return _this.state = { + height: 0, + width: 0 + }, _this._onResize = _this._onResize.bind(_this), _this._setRef = _this._setRef.bind(_this), + _this; + } + return (0, _inherits3.default)(AutoSizer, _Component), (0, _createClass3.default)(AutoSizer, [ { + key: "componentDidMount", + value: function() { + this._parentNode = this._autoSizer.parentNode, this._detectElementResize = (0, _detectElementResize2.default)(), + this._detectElementResize.addResizeListener(this._parentNode, this._onResize), this._onResize(); + } + }, { + key: "componentWillUnmount", + value: function() { + this._detectElementResize && this._detectElementResize.removeResizeListener(this._parentNode, this._onResize); + } + }, { + key: "render", + value: function() { + var _props = this.props, children = _props.children, disableHeight = _props.disableHeight, disableWidth = _props.disableWidth, _state = this.state, height = _state.height, width = _state.width, outerStyle = { + overflow: "visible" + }; + return disableHeight || (outerStyle.height = 0), disableWidth || (outerStyle.width = 0), + _react2.default.createElement("div", { + ref: this._setRef, + style: outerStyle + }, children({ + height: height, + width: width + })); + } + }, { + key: "shouldComponentUpdate", + value: function(nextProps, nextState) { + return (0, _reactAddonsShallowCompare2.default)(this, nextProps, nextState); + } + }, { + key: "_onResize", + value: function() { + var onResize = this.props.onResize, boundingRect = this._parentNode.getBoundingClientRect(), height = boundingRect.height || 0, width = boundingRect.width || 0, style = window.getComputedStyle(this._parentNode), paddingLeft = parseInt(style.paddingLeft, 10) || 0, paddingRight = parseInt(style.paddingRight, 10) || 0, paddingTop = parseInt(style.paddingTop, 10) || 0, paddingBottom = parseInt(style.paddingBottom, 10) || 0; + this.setState({ + height: height - paddingTop - paddingBottom, + width: width - paddingLeft - paddingRight + }), onResize({ + height: height, + width: width + }); + } + }, { + key: "_setRef", + value: function(autoSizer) { + this._autoSizer = autoSizer; + } + } ]), AutoSizer; + }(_react.Component); + AutoSizer.defaultProps = { + onResize: function() {} + }, exports.default = AutoSizer; + }, /* 93 */ + /***/ + function(module, exports) { + "use strict"; + function createDetectElementResize() { + var _window; + _window = "undefined" != typeof window ? window : "undefined" != typeof self ? self : this; + var attachEvent = "undefined" != typeof document && document.attachEvent, stylesCreated = !1; + if (!attachEvent) { + var requestFrame = function() { + var raf = _window.requestAnimationFrame || _window.mozRequestAnimationFrame || _window.webkitRequestAnimationFrame || function(fn) { + return _window.setTimeout(fn, 20); + }; + return function(fn) { + return raf(fn); + }; + }(), cancelFrame = function() { + var cancel = _window.cancelAnimationFrame || _window.mozCancelAnimationFrame || _window.webkitCancelAnimationFrame || _window.clearTimeout; + return function(id) { + return cancel(id); + }; + }(), resetTriggers = function(element) { + var triggers = element.__resizeTriggers__, expand = triggers.firstElementChild, contract = triggers.lastElementChild, expandChild = expand.firstElementChild; + contract.scrollLeft = contract.scrollWidth, contract.scrollTop = contract.scrollHeight, + expandChild.style.width = expand.offsetWidth + 1 + "px", expandChild.style.height = expand.offsetHeight + 1 + "px", + expand.scrollLeft = expand.scrollWidth, expand.scrollTop = expand.scrollHeight; + }, checkTriggers = function(element) { + return element.offsetWidth != element.__resizeLast__.width || element.offsetHeight != element.__resizeLast__.height; + }, scrollListener = function(e) { + if (!(e.target.className.indexOf("contract-trigger") < 0 && e.target.className.indexOf("expand-trigger") < 0)) { + var element = this; + resetTriggers(this), this.__resizeRAF__ && cancelFrame(this.__resizeRAF__), this.__resizeRAF__ = requestFrame(function() { + checkTriggers(element) && (element.__resizeLast__.width = element.offsetWidth, element.__resizeLast__.height = element.offsetHeight, + element.__resizeListeners__.forEach(function(fn) { + fn.call(element, e); + })); + }); + } + }, animation = !1, animationstring = "animation", keyframeprefix = "", animationstartevent = "animationstart", domPrefixes = "Webkit Moz O ms".split(" "), startEvents = "webkitAnimationStart animationstart oAnimationStart MSAnimationStart".split(" "), pfx = "", elm = document.createElementNS("http://www.w3.org/1999/xhtml","fakeelement"); + if (void 0 !== elm.style.animationName && (animation = !0), animation === !1) for (var i = 0; i < domPrefixes.length; i++) if (void 0 !== elm.style[domPrefixes[i] + "AnimationName"]) { + pfx = domPrefixes[i], animationstring = pfx + "Animation", keyframeprefix = "-" + pfx.toLowerCase() + "-", + animationstartevent = startEvents[i], animation = !0; + break; + } + var animationName = "resizeanim", animationKeyframes = "@" + keyframeprefix + "keyframes " + animationName + " { from { opacity: 0; } to { opacity: 0; } } ", animationStyle = keyframeprefix + "animation: 1ms " + animationName + "; "; + } + var createStyles = function() { + if (!stylesCreated) { + var css = (animationKeyframes ? animationKeyframes : "") + ".resize-triggers { " + (animationStyle ? animationStyle : "") + 'visibility: hidden; opacity: 0; } .resize-triggers, .resize-triggers > div, .contract-trigger:before { content: " "; display: block; position: absolute; top: 0; left: 0; height: 100%; width: 100%; overflow: hidden; z-index: -1; } .resize-triggers > div { background: #eee; overflow: auto; } .contract-trigger:before { width: 200%; height: 200%; }', head = document.firstElementChild || document.getElementsByTagName("head")[0], style = document.createElementNS("http://www.w3.org/1999/xhtml","style"); + style.type = "text/css", style.styleSheet ? style.styleSheet.cssText = css : style.appendChild(document.createTextNode(css)), + head.appendChild(style), stylesCreated = !0; + } + }, addResizeListener = function(element, fn) { + attachEvent ? element.attachEvent("onresize", fn) : (element.__resizeTriggers__ || ("static" == _window.getComputedStyle(element).position && (element.style.position = "relative"), + createStyles(), element.__resizeLast__ = {}, element.__resizeListeners__ = [], (element.__resizeTriggers__ = document.createElementNS("http://www.w3.org/1999/xhtml","div")).className = "resize-triggers", + element.__resizeTriggers__.innerHTML = '<div class="expand-trigger"><div></div></div><div class="contract-trigger"></div>', + element.appendChild(element.__resizeTriggers__), resetTriggers(element), element.addEventListener("scroll", scrollListener, !0), + animationstartevent && (element.__resizeTriggers__.__animationListener__ = function(e) { + e.animationName == animationName && resetTriggers(element); + }, element.__resizeTriggers__.addEventListener(animationstartevent, element.__resizeTriggers__.__animationListener__))), + element.__resizeListeners__.push(fn)); + }, removeResizeListener = function(element, fn) { + attachEvent ? element.detachEvent("onresize", fn) : (element.__resizeListeners__.splice(element.__resizeListeners__.indexOf(fn), 1), + element.__resizeListeners__.length || (element.removeEventListener("scroll", scrollListener, !0), + element.__resizeTriggers__.__animationListener__ && (element.__resizeTriggers__.removeEventListener(animationstartevent, element.__resizeTriggers__.__animationListener__), + element.__resizeTriggers__.__animationListener__ = null), element.__resizeTriggers__ = !element.removeChild(element.__resizeTriggers__))); + }; + return { + addResizeListener: addResizeListener, + removeResizeListener: removeResizeListener + }; + } + Object.defineProperty(exports, "__esModule", { + value: !0 + }), exports.default = createDetectElementResize; + }, /* 94 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + Object.defineProperty(exports, "__esModule", { + value: !0 + }), exports.defaultCellSizeCache = exports.CellMeasurer = exports.default = void 0; + var _CellMeasurer2 = __webpack_require__(95), _CellMeasurer3 = _interopRequireDefault(_CellMeasurer2), _defaultCellSizeCache2 = __webpack_require__(97), _defaultCellSizeCache3 = _interopRequireDefault(_defaultCellSizeCache2); + exports.default = _CellMeasurer3.default, exports.CellMeasurer = _CellMeasurer3.default, + exports.defaultCellSizeCache = _defaultCellSizeCache3.default; + }, /* 95 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + Object.defineProperty(exports, "__esModule", { + value: !0 + }); + var _getPrototypeOf = __webpack_require__(3), _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf), _classCallCheck2 = __webpack_require__(29), _classCallCheck3 = _interopRequireDefault(_classCallCheck2), _createClass2 = __webpack_require__(30), _createClass3 = _interopRequireDefault(_createClass2), _possibleConstructorReturn2 = __webpack_require__(34), _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2), _inherits2 = __webpack_require__(81), _inherits3 = _interopRequireDefault(_inherits2), _react = __webpack_require__(89), _reactAddonsShallowCompare = (_interopRequireDefault(_react), + __webpack_require__(90)), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), _reactDom = __webpack_require__(96), _reactDom2 = _interopRequireDefault(_reactDom), _defaultCellSizeCache = __webpack_require__(97), _defaultCellSizeCache2 = _interopRequireDefault(_defaultCellSizeCache), CellMeasurer = function(_Component) { + function CellMeasurer(props, state) { + (0, _classCallCheck3.default)(this, CellMeasurer); + var _this = (0, _possibleConstructorReturn3.default)(this, (CellMeasurer.__proto__ || (0, + _getPrototypeOf2.default)(CellMeasurer)).call(this, props, state)); + return _this._cellSizeCache = props.cellSizeCache || new _defaultCellSizeCache2.default(), + _this.getColumnWidth = _this.getColumnWidth.bind(_this), _this.getRowHeight = _this.getRowHeight.bind(_this), + _this.resetMeasurements = _this.resetMeasurements.bind(_this), _this.resetMeasurementForColumn = _this.resetMeasurementForColumn.bind(_this), + _this.resetMeasurementForRow = _this.resetMeasurementForRow.bind(_this), _this; + } + return (0, _inherits3.default)(CellMeasurer, _Component), (0, _createClass3.default)(CellMeasurer, [ { + key: "getColumnWidth", + value: function(_ref) { + var index = _ref.index; + if (this._cellSizeCache.hasColumnWidth(index)) return this._cellSizeCache.getColumnWidth(index); + for (var rowCount = this.props.rowCount, maxWidth = 0, rowIndex = 0; rowIndex < rowCount; rowIndex++) { + var _measureCell2 = this._measureCell({ + clientWidth: !0, + columnIndex: index, + rowIndex: rowIndex + }), width = _measureCell2.width; + maxWidth = Math.max(maxWidth, width); + } + return this._cellSizeCache.setColumnWidth(index, maxWidth), maxWidth; + } + }, { + key: "getRowHeight", + value: function(_ref2) { + var index = _ref2.index; + if (this._cellSizeCache.hasRowHeight(index)) return this._cellSizeCache.getRowHeight(index); + for (var columnCount = this.props.columnCount, maxHeight = 0, columnIndex = 0; columnIndex < columnCount; columnIndex++) { + var _measureCell3 = this._measureCell({ + clientHeight: !0, + columnIndex: columnIndex, + rowIndex: index + }), height = _measureCell3.height; + maxHeight = Math.max(maxHeight, height); + } + return this._cellSizeCache.setRowHeight(index, maxHeight), maxHeight; + } + }, { + key: "resetMeasurementForColumn", + value: function(columnIndex) { + this._cellSizeCache.clearColumnWidth(columnIndex); + } + }, { + key: "resetMeasurementForRow", + value: function(rowIndex) { + this._cellSizeCache.clearRowHeight(rowIndex); + } + }, { + key: "resetMeasurements", + value: function() { + this._cellSizeCache.clearAllColumnWidths(), this._cellSizeCache.clearAllRowHeights(); + } + }, { + key: "componentDidMount", + value: function() { + this._renderAndMount(); + } + }, { + key: "componentWillReceiveProps", + value: function(nextProps) { + var cellSizeCache = this.props.cellSizeCache; + cellSizeCache !== nextProps.cellSizeCache && (this._cellSizeCache = nextProps.cellSizeCache), + this._updateDivDimensions(nextProps); + } + }, { + key: "componentWillUnmount", + value: function() { + this._unmountContainer(); + } + }, { + key: "render", + value: function() { + var children = this.props.children; + return children({ + getColumnWidth: this.getColumnWidth, + getRowHeight: this.getRowHeight, + resetMeasurements: this.resetMeasurements, + resetMeasurementForColumn: this.resetMeasurementForColumn, + resetMeasurementForRow: this.resetMeasurementForRow + }); + } + }, { + key: "shouldComponentUpdate", + value: function(nextProps, nextState) { + return (0, _reactAddonsShallowCompare2.default)(this, nextProps, nextState); + } + }, { + key: "_getContainerNode", + value: function(props) { + var container = props.container; + return container ? _reactDom2.default.findDOMNode("function" == typeof container ? container() : container) : document.firstElementChild; + } + }, { + key: "_measureCell", + value: function(_ref3) { + var _ref3$clientHeight = _ref3.clientHeight, clientHeight = void 0 !== _ref3$clientHeight && _ref3$clientHeight, _ref3$clientWidth = _ref3.clientWidth, clientWidth = void 0 === _ref3$clientWidth || _ref3$clientWidth, columnIndex = _ref3.columnIndex, rowIndex = _ref3.rowIndex, cellRenderer = this.props.cellRenderer, rendered = cellRenderer({ + columnIndex: columnIndex, + rowIndex: rowIndex + }); + this._renderAndMount(), _reactDom2.default.unstable_renderSubtreeIntoContainer(this, rendered, this._div); + var measurements = { + height: clientHeight && this._div.clientHeight, + width: clientWidth && this._div.clientWidth + }; + return _reactDom2.default.unmountComponentAtNode(this._div), measurements; + } + }, { + key: "_renderAndMount", + value: function() { + this._div || (this._div = document.createElementNS("http://www.w3.org/1999/xhtml","div"), this._div.style.display = "inline-block", + this._div.style.position = "absolute", this._div.style.visibility = "hidden", this._div.style.zIndex = -1, + this._updateDivDimensions(this.props), this._containerNode = this._getContainerNode(this.props), + this._containerNode.appendChild(this._div)); + } + }, { + key: "_unmountContainer", + value: function() { + this._div && (this._containerNode.removeChild(this._div), this._div = null), this._containerNode = null; + } + }, { + key: "_updateDivDimensions", + value: function(props) { + var height = props.height, width = props.width; + height && height !== this._divHeight && (this._divHeight = height, this._div.style.height = height + "px"), + width && width !== this._divWidth && (this._divWidth = width, this._div.style.width = width + "px"); + } + } ]), CellMeasurer; + }(_react.Component); + exports.default = CellMeasurer; + }, /* 96 */ + /***/ + function(module, exports) { + module.exports = __WEBPACK_EXTERNAL_MODULE_96__; + }, /* 97 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + Object.defineProperty(exports, "__esModule", { + value: !0 + }); + var _classCallCheck2 = __webpack_require__(29), _classCallCheck3 = _interopRequireDefault(_classCallCheck2), _createClass2 = __webpack_require__(30), _createClass3 = _interopRequireDefault(_createClass2), CellSizeCache = function() { + function CellSizeCache() { + var _ref = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {}, _ref$uniformRowHeight = _ref.uniformRowHeight, uniformRowHeight = void 0 !== _ref$uniformRowHeight && _ref$uniformRowHeight, _ref$uniformColumnWid = _ref.uniformColumnWidth, uniformColumnWidth = void 0 !== _ref$uniformColumnWid && _ref$uniformColumnWid; + (0, _classCallCheck3.default)(this, CellSizeCache), this._uniformRowHeight = uniformRowHeight, + this._uniformColumnWidth = uniformColumnWidth, this._cachedColumnWidths = {}, this._cachedRowHeights = {}; + } + return (0, _createClass3.default)(CellSizeCache, [ { + key: "clearAllColumnWidths", + value: function() { + this._cachedColumnWidth = void 0, this._cachedColumnWidths = {}; + } + }, { + key: "clearAllRowHeights", + value: function() { + this._cachedRowHeight = void 0, this._cachedRowHeights = {}; + } + }, { + key: "clearColumnWidth", + value: function(index) { + this._cachedColumnWidth = void 0, delete this._cachedColumnWidths[index]; + } + }, { + key: "clearRowHeight", + value: function(index) { + this._cachedRowHeight = void 0, delete this._cachedRowHeights[index]; + } + }, { + key: "getColumnWidth", + value: function(index) { + return this._uniformColumnWidth ? this._cachedColumnWidth : this._cachedColumnWidths[index]; + } + }, { + key: "getRowHeight", + value: function(index) { + return this._uniformRowHeight ? this._cachedRowHeight : this._cachedRowHeights[index]; + } + }, { + key: "hasColumnWidth", + value: function(index) { + return this._uniformColumnWidth ? !!this._cachedColumnWidth : !!this._cachedColumnWidths[index]; + } + }, { + key: "hasRowHeight", + value: function(index) { + return this._uniformRowHeight ? !!this._cachedRowHeight : !!this._cachedRowHeights[index]; + } + }, { + key: "setColumnWidth", + value: function(index, width) { + this._cachedColumnWidth = width, this._cachedColumnWidths[index] = width; + } + }, { + key: "setRowHeight", + value: function(index, height) { + this._cachedRowHeight = height, this._cachedRowHeights[index] = height; + } + } ]), CellSizeCache; + }(); + exports.default = CellSizeCache; + }, /* 98 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + Object.defineProperty(exports, "__esModule", { + value: !0 + }), exports.Collection = exports.default = void 0; + var _Collection2 = __webpack_require__(99), _Collection3 = _interopRequireDefault(_Collection2); + exports.default = _Collection3.default, exports.Collection = _Collection3.default; + }, /* 99 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + function defaultCellGroupRenderer(_ref5) { + var cellCache = _ref5.cellCache, cellRenderer = _ref5.cellRenderer, cellSizeAndPositionGetter = _ref5.cellSizeAndPositionGetter, indices = _ref5.indices, isScrolling = _ref5.isScrolling; + return indices.map(function(index) { + var cellMetadata = cellSizeAndPositionGetter({ + index: index + }), cellRendererProps = { + index: index, + isScrolling: isScrolling, + key: index, + style: { + height: cellMetadata.height, + left: cellMetadata.x, + position: "absolute", + top: cellMetadata.y, + width: cellMetadata.width + } + }; + return isScrolling ? (index in cellCache || (cellCache[index] = cellRenderer(cellRendererProps)), + cellCache[index]) : cellRenderer(cellRendererProps); + }).filter(function(renderedCell) { + return !!renderedCell; + }); + } + Object.defineProperty(exports, "__esModule", { + value: !0 + }); + var _extends2 = __webpack_require__(100), _extends3 = _interopRequireDefault(_extends2), _objectWithoutProperties2 = __webpack_require__(105), _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2), _getPrototypeOf = __webpack_require__(3), _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf), _classCallCheck2 = __webpack_require__(29), _classCallCheck3 = _interopRequireDefault(_classCallCheck2), _createClass2 = __webpack_require__(30), _createClass3 = _interopRequireDefault(_createClass2), _possibleConstructorReturn2 = __webpack_require__(34), _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2), _inherits2 = __webpack_require__(81), _inherits3 = _interopRequireDefault(_inherits2), _react = __webpack_require__(89), _react2 = _interopRequireDefault(_react), _CollectionView = __webpack_require__(106), _CollectionView2 = _interopRequireDefault(_CollectionView), _calculateSizeAndPositionData2 = __webpack_require__(114), _calculateSizeAndPositionData3 = _interopRequireDefault(_calculateSizeAndPositionData2), _getUpdatedOffsetForIndex = __webpack_require__(117), _getUpdatedOffsetForIndex2 = _interopRequireDefault(_getUpdatedOffsetForIndex), _reactAddonsShallowCompare = __webpack_require__(90), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), Collection = function(_Component) { + function Collection(props, context) { + (0, _classCallCheck3.default)(this, Collection); + var _this = (0, _possibleConstructorReturn3.default)(this, (Collection.__proto__ || (0, + _getPrototypeOf2.default)(Collection)).call(this, props, context)); + return _this._cellMetadata = [], _this._lastRenderedCellIndices = [], _this._cellCache = [], + _this._isScrollingChange = _this._isScrollingChange.bind(_this), _this; + } + return (0, _inherits3.default)(Collection, _Component), (0, _createClass3.default)(Collection, [ { + key: "recomputeCellSizesAndPositions", + value: function() { + this._cellCache = [], this._collectionView.recomputeCellSizesAndPositions(); + } + }, { + key: "render", + value: function() { + var _this2 = this, props = (0, _objectWithoutProperties3.default)(this.props, []); + return _react2.default.createElement(_CollectionView2.default, (0, _extends3.default)({ + cellLayoutManager: this, + isScrollingChange: this._isScrollingChange, + ref: function(_ref) { + _this2._collectionView = _ref; + } + }, props)); + } + }, { + key: "shouldComponentUpdate", + value: function(nextProps, nextState) { + return (0, _reactAddonsShallowCompare2.default)(this, nextProps, nextState); + } + }, { + key: "calculateSizeAndPositionData", + value: function() { + var _props = this.props, cellCount = _props.cellCount, cellSizeAndPositionGetter = _props.cellSizeAndPositionGetter, sectionSize = _props.sectionSize, data = (0, + _calculateSizeAndPositionData3.default)({ + cellCount: cellCount, + cellSizeAndPositionGetter: cellSizeAndPositionGetter, + sectionSize: sectionSize + }); + this._cellMetadata = data.cellMetadata, this._sectionManager = data.sectionManager, + this._height = data.height, this._width = data.width; + } + }, { + key: "getLastRenderedIndices", + value: function() { + return this._lastRenderedCellIndices; + } + }, { + key: "getScrollPositionForCell", + value: function(_ref2) { + var align = _ref2.align, cellIndex = _ref2.cellIndex, height = _ref2.height, scrollLeft = _ref2.scrollLeft, scrollTop = _ref2.scrollTop, width = _ref2.width, cellCount = this.props.cellCount; + if (cellIndex >= 0 && cellIndex < cellCount) { + var cellMetadata = this._cellMetadata[cellIndex]; + scrollLeft = (0, _getUpdatedOffsetForIndex2.default)({ + align: align, + cellOffset: cellMetadata.x, + cellSize: cellMetadata.width, + containerSize: width, + currentOffset: scrollLeft, + targetIndex: cellIndex + }), scrollTop = (0, _getUpdatedOffsetForIndex2.default)({ + align: align, + cellOffset: cellMetadata.y, + cellSize: cellMetadata.height, + containerSize: height, + currentOffset: scrollTop, + targetIndex: cellIndex + }); + } + return { + scrollLeft: scrollLeft, + scrollTop: scrollTop + }; + } + }, { + key: "getTotalSize", + value: function() { + return { + height: this._height, + width: this._width + }; + } + }, { + key: "cellRenderers", + value: function(_ref3) { + var _this3 = this, height = _ref3.height, isScrolling = _ref3.isScrolling, width = _ref3.width, x = _ref3.x, y = _ref3.y, _props2 = this.props, cellGroupRenderer = _props2.cellGroupRenderer, cellRenderer = _props2.cellRenderer; + return this._lastRenderedCellIndices = this._sectionManager.getCellIndices({ + height: height, + width: width, + x: x, + y: y + }), cellGroupRenderer({ + cellCache: this._cellCache, + cellRenderer: cellRenderer, + cellSizeAndPositionGetter: function(_ref4) { + var index = _ref4.index; + return _this3._sectionManager.getCellMetadata({ + index: index + }); + }, + indices: this._lastRenderedCellIndices, + isScrolling: isScrolling + }); + } + }, { + key: "_isScrollingChange", + value: function(isScrolling) { + isScrolling || (this._cellCache = []); + } + } ]), Collection; + }(_react.Component); + Collection.defaultProps = { + "aria-label": "grid", + cellGroupRenderer: defaultCellGroupRenderer + }, exports.default = Collection; + }, /* 100 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + exports.__esModule = !0; + var _assign = __webpack_require__(101), _assign2 = _interopRequireDefault(_assign); + exports.default = _assign2.default || function(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + for (var key in source) Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]); + } + return target; + }; + }, /* 101 */ + /***/ + function(module, exports, __webpack_require__) { + module.exports = { + default: __webpack_require__(102), + __esModule: !0 + }; + }, /* 102 */ + /***/ + function(module, exports, __webpack_require__) { + __webpack_require__(103), module.exports = __webpack_require__(16).Object.assign; + }, /* 103 */ + /***/ + function(module, exports, __webpack_require__) { + // 19.1.3.1 Object.assign(target, source) + var $export = __webpack_require__(15); + $export($export.S + $export.F, "Object", { + assign: __webpack_require__(104) + }); + }, /* 104 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + // 19.1.2.1 Object.assign(target, source, ...) + var getKeys = __webpack_require__(48), gOPS = __webpack_require__(72), pIE = __webpack_require__(73), toObject = __webpack_require__(6), IObject = __webpack_require__(51), $assign = Object.assign; + // should work with symbols and should have deterministic property order (V8 bug) + module.exports = !$assign || __webpack_require__(25)(function() { + var A = {}, B = {}, S = Symbol(), K = "abcdefghijklmnopqrst"; + return A[S] = 7, K.split("").forEach(function(k) { + B[k] = k; + }), 7 != $assign({}, A)[S] || Object.keys($assign({}, B)).join("") != K; + }) ? function(target, source) { + for (// eslint-disable-line no-unused-vars + var T = toObject(target), aLen = arguments.length, index = 1, getSymbols = gOPS.f, isEnum = pIE.f; aLen > index; ) for (var key, S = IObject(arguments[index++]), keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S), length = keys.length, j = 0; length > j; ) isEnum.call(S, key = keys[j++]) && (T[key] = S[key]); + return T; + } : $assign; + }, /* 105 */ + /***/ + function(module, exports) { + "use strict"; + exports.__esModule = !0, exports.default = function(obj, keys) { + var target = {}; + for (var i in obj) keys.indexOf(i) >= 0 || Object.prototype.hasOwnProperty.call(obj, i) && (target[i] = obj[i]); + return target; + }; + }, /* 106 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + Object.defineProperty(exports, "__esModule", { + value: !0 + }); + var _extends2 = __webpack_require__(100), _extends3 = _interopRequireDefault(_extends2), _getPrototypeOf = __webpack_require__(3), _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf), _classCallCheck2 = __webpack_require__(29), _classCallCheck3 = _interopRequireDefault(_classCallCheck2), _createClass2 = __webpack_require__(30), _createClass3 = _interopRequireDefault(_createClass2), _possibleConstructorReturn2 = __webpack_require__(34), _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2), _inherits2 = __webpack_require__(81), _inherits3 = _interopRequireDefault(_inherits2), _react = __webpack_require__(89), _react2 = _interopRequireDefault(_react), _classnames = __webpack_require__(107), _classnames2 = _interopRequireDefault(_classnames), _createCallbackMemoizer = __webpack_require__(108), _createCallbackMemoizer2 = _interopRequireDefault(_createCallbackMemoizer), _scrollbarSize = __webpack_require__(112), _scrollbarSize2 = _interopRequireDefault(_scrollbarSize), _reactAddonsShallowCompare = __webpack_require__(90), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), IS_SCROLLING_TIMEOUT = 150, SCROLL_POSITION_CHANGE_REASONS = { + OBSERVED: "observed", + REQUESTED: "requested" + }, CollectionView = function(_Component) { + function CollectionView(props, context) { + (0, _classCallCheck3.default)(this, CollectionView); + var _this = (0, _possibleConstructorReturn3.default)(this, (CollectionView.__proto__ || (0, + _getPrototypeOf2.default)(CollectionView)).call(this, props, context)); + return _this.state = { + calculateSizeAndPositionDataOnNextUpdate: !1, + isScrolling: !1, + scrollLeft: 0, + scrollTop: 0 + }, _this._onSectionRenderedMemoizer = (0, _createCallbackMemoizer2.default)(), _this._onScrollMemoizer = (0, + _createCallbackMemoizer2.default)(!1), _this._invokeOnSectionRenderedHelper = _this._invokeOnSectionRenderedHelper.bind(_this), + _this._onScroll = _this._onScroll.bind(_this), _this._updateScrollPositionForScrollToCell = _this._updateScrollPositionForScrollToCell.bind(_this), + _this; + } + return (0, _inherits3.default)(CollectionView, _Component), (0, _createClass3.default)(CollectionView, [ { + key: "recomputeCellSizesAndPositions", + value: function() { + this.setState({ + calculateSizeAndPositionDataOnNextUpdate: !0 + }); + } + }, { + key: "componentDidMount", + value: function() { + var _props = this.props, cellLayoutManager = _props.cellLayoutManager, scrollLeft = _props.scrollLeft, scrollToCell = _props.scrollToCell, scrollTop = _props.scrollTop; + this._scrollbarSizeMeasured || (this._scrollbarSize = (0, _scrollbarSize2.default)(), + this._scrollbarSizeMeasured = !0, this.setState({})), scrollToCell >= 0 ? this._updateScrollPositionForScrollToCell() : (scrollLeft >= 0 || scrollTop >= 0) && this._setScrollPosition({ + scrollLeft: scrollLeft, + scrollTop: scrollTop + }), this._invokeOnSectionRenderedHelper(); + var _cellLayoutManager$ge = cellLayoutManager.getTotalSize(), totalHeight = _cellLayoutManager$ge.height, totalWidth = _cellLayoutManager$ge.width; + this._invokeOnScrollMemoizer({ + scrollLeft: scrollLeft || 0, + scrollTop: scrollTop || 0, + totalHeight: totalHeight, + totalWidth: totalWidth + }); + } + }, { + key: "componentDidUpdate", + value: function(prevProps, prevState) { + var _props2 = this.props, height = _props2.height, scrollToAlignment = _props2.scrollToAlignment, scrollToCell = _props2.scrollToCell, width = _props2.width, _state = this.state, scrollLeft = _state.scrollLeft, scrollPositionChangeReason = _state.scrollPositionChangeReason, scrollTop = _state.scrollTop; + scrollPositionChangeReason === SCROLL_POSITION_CHANGE_REASONS.REQUESTED && (scrollLeft >= 0 && scrollLeft !== prevState.scrollLeft && scrollLeft !== this._scrollingContainer.scrollLeft && (this._scrollingContainer.scrollLeft = scrollLeft), + scrollTop >= 0 && scrollTop !== prevState.scrollTop && scrollTop !== this._scrollingContainer.scrollTop && (this._scrollingContainer.scrollTop = scrollTop)), + height === prevProps.height && scrollToAlignment === prevProps.scrollToAlignment && scrollToCell === prevProps.scrollToCell && width === prevProps.width || this._updateScrollPositionForScrollToCell(), + this._invokeOnSectionRenderedHelper(); + } + }, { + key: "componentWillMount", + value: function() { + var cellLayoutManager = this.props.cellLayoutManager; + cellLayoutManager.calculateSizeAndPositionData(), this._scrollbarSize = (0, _scrollbarSize2.default)(), + void 0 === this._scrollbarSize ? (this._scrollbarSizeMeasured = !1, this._scrollbarSize = 0) : this._scrollbarSizeMeasured = !0; + } + }, { + key: "componentWillUnmount", + value: function() { + this._disablePointerEventsTimeoutId && clearTimeout(this._disablePointerEventsTimeoutId); + } + }, { + key: "componentWillUpdate", + value: function(nextProps, nextState) { + 0 !== nextProps.cellCount || 0 === nextState.scrollLeft && 0 === nextState.scrollTop ? nextProps.scrollLeft === this.props.scrollLeft && nextProps.scrollTop === this.props.scrollTop || this._setScrollPosition({ + scrollLeft: nextProps.scrollLeft, + scrollTop: nextProps.scrollTop + }) : this._setScrollPosition({ + scrollLeft: 0, + scrollTop: 0 + }), (nextProps.cellCount !== this.props.cellCount || nextProps.cellLayoutManager !== this.props.cellLayoutManager || nextState.calculateSizeAndPositionDataOnNextUpdate) && nextProps.cellLayoutManager.calculateSizeAndPositionData(), + nextState.calculateSizeAndPositionDataOnNextUpdate && this.setState({ + calculateSizeAndPositionDataOnNextUpdate: !1 + }); + } + }, { + key: "render", + value: function() { + var _this2 = this, _props3 = this.props, autoHeight = _props3.autoHeight, cellCount = _props3.cellCount, cellLayoutManager = _props3.cellLayoutManager, className = _props3.className, height = _props3.height, horizontalOverscanSize = _props3.horizontalOverscanSize, id = _props3.id, noContentRenderer = _props3.noContentRenderer, style = _props3.style, verticalOverscanSize = _props3.verticalOverscanSize, width = _props3.width, _state2 = this.state, isScrolling = _state2.isScrolling, scrollLeft = _state2.scrollLeft, scrollTop = _state2.scrollTop, _cellLayoutManager$ge2 = cellLayoutManager.getTotalSize(), totalHeight = _cellLayoutManager$ge2.height, totalWidth = _cellLayoutManager$ge2.width, left = Math.max(0, scrollLeft - horizontalOverscanSize), top = Math.max(0, scrollTop - verticalOverscanSize), right = Math.min(totalWidth, scrollLeft + width + horizontalOverscanSize), bottom = Math.min(totalHeight, scrollTop + height + verticalOverscanSize), childrenToDisplay = height > 0 && width > 0 ? cellLayoutManager.cellRenderers({ + height: bottom - top, + isScrolling: isScrolling, + width: right - left, + x: left, + y: top + }) : [], collectionStyle = { + boxSizing: "border-box", + height: autoHeight ? "auto" : height, + overflow: "auto", + position: "relative", + WebkitOverflowScrolling: "touch", + width: width, + willChange: "transform" + }, verticalScrollBarSize = totalHeight > height ? this._scrollbarSize : 0, horizontalScrollBarSize = totalWidth > width ? this._scrollbarSize : 0; + return totalWidth + verticalScrollBarSize <= width && (collectionStyle.overflowX = "hidden"), + totalHeight + horizontalScrollBarSize <= height && (collectionStyle.overflowY = "hidden"), + _react2.default.createElement("div", { + ref: function(_ref) { + _this2._scrollingContainer = _ref; + }, + "aria-label": this.props["aria-label"], + className: (0, _classnames2.default)("ReactVirtualized__Collection", className), + id: id, + onScroll: this._onScroll, + role: "grid", + style: (0, _extends3.default)({}, collectionStyle, style), + tabIndex: 0 + }, cellCount > 0 && _react2.default.createElement("div", { + className: "ReactVirtualized__Collection__innerScrollContainer", + style: { + height: totalHeight, + maxHeight: totalHeight, + maxWidth: totalWidth, + overflow: "hidden", + pointerEvents: isScrolling ? "none" : "", + width: totalWidth + } + }, childrenToDisplay), 0 === cellCount && noContentRenderer()); + } + }, { + key: "shouldComponentUpdate", + value: function(nextProps, nextState) { + return (0, _reactAddonsShallowCompare2.default)(this, nextProps, nextState); + } + }, { + key: "_enablePointerEventsAfterDelay", + value: function() { + var _this3 = this; + this._disablePointerEventsTimeoutId && clearTimeout(this._disablePointerEventsTimeoutId), + this._disablePointerEventsTimeoutId = setTimeout(function() { + var isScrollingChange = _this3.props.isScrollingChange; + isScrollingChange(!1), _this3._disablePointerEventsTimeoutId = null, _this3.setState({ + isScrolling: !1 + }); + }, IS_SCROLLING_TIMEOUT); + } + }, { + key: "_invokeOnSectionRenderedHelper", + value: function() { + var _props4 = this.props, cellLayoutManager = _props4.cellLayoutManager, onSectionRendered = _props4.onSectionRendered; + this._onSectionRenderedMemoizer({ + callback: onSectionRendered, + indices: { + indices: cellLayoutManager.getLastRenderedIndices() + } + }); + } + }, { + key: "_invokeOnScrollMemoizer", + value: function(_ref2) { + var _this4 = this, scrollLeft = _ref2.scrollLeft, scrollTop = _ref2.scrollTop, totalHeight = _ref2.totalHeight, totalWidth = _ref2.totalWidth; + this._onScrollMemoizer({ + callback: function(_ref3) { + var scrollLeft = _ref3.scrollLeft, scrollTop = _ref3.scrollTop, _props5 = _this4.props, height = _props5.height, onScroll = _props5.onScroll, width = _props5.width; + onScroll({ + clientHeight: height, + clientWidth: width, + scrollHeight: totalHeight, + scrollLeft: scrollLeft, + scrollTop: scrollTop, + scrollWidth: totalWidth + }); + }, + indices: { + scrollLeft: scrollLeft, + scrollTop: scrollTop + } + }); + } + }, { + key: "_setScrollPosition", + value: function(_ref4) { + var scrollLeft = _ref4.scrollLeft, scrollTop = _ref4.scrollTop, newState = { + scrollPositionChangeReason: SCROLL_POSITION_CHANGE_REASONS.REQUESTED + }; + scrollLeft >= 0 && (newState.scrollLeft = scrollLeft), scrollTop >= 0 && (newState.scrollTop = scrollTop), + (scrollLeft >= 0 && scrollLeft !== this.state.scrollLeft || scrollTop >= 0 && scrollTop !== this.state.scrollTop) && this.setState(newState); + } + }, { + key: "_updateScrollPositionForScrollToCell", + value: function() { + var _props6 = this.props, cellLayoutManager = _props6.cellLayoutManager, height = _props6.height, scrollToAlignment = _props6.scrollToAlignment, scrollToCell = _props6.scrollToCell, width = _props6.width, _state3 = this.state, scrollLeft = _state3.scrollLeft, scrollTop = _state3.scrollTop; + if (scrollToCell >= 0) { + var scrollPosition = cellLayoutManager.getScrollPositionForCell({ + align: scrollToAlignment, + cellIndex: scrollToCell, + height: height, + scrollLeft: scrollLeft, + scrollTop: scrollTop, + width: width + }); + scrollPosition.scrollLeft === scrollLeft && scrollPosition.scrollTop === scrollTop || this._setScrollPosition(scrollPosition); + } + } + }, { + key: "_onScroll", + value: function(event) { + if (event.target === this._scrollingContainer) { + this._enablePointerEventsAfterDelay(); + var _props7 = this.props, cellLayoutManager = _props7.cellLayoutManager, height = _props7.height, isScrollingChange = _props7.isScrollingChange, width = _props7.width, scrollbarSize = this._scrollbarSize, _cellLayoutManager$ge3 = cellLayoutManager.getTotalSize(), totalHeight = _cellLayoutManager$ge3.height, totalWidth = _cellLayoutManager$ge3.width, scrollLeft = Math.max(0, Math.min(totalWidth - width + scrollbarSize, event.target.scrollLeft)), scrollTop = Math.max(0, Math.min(totalHeight - height + scrollbarSize, event.target.scrollTop)); + if (this.state.scrollLeft !== scrollLeft || this.state.scrollTop !== scrollTop) { + var scrollPositionChangeReason = event.cancelable ? SCROLL_POSITION_CHANGE_REASONS.OBSERVED : SCROLL_POSITION_CHANGE_REASONS.REQUESTED; + this.state.isScrolling || isScrollingChange(!0), this.setState({ + isScrolling: !0, + scrollLeft: scrollLeft, + scrollPositionChangeReason: scrollPositionChangeReason, + scrollTop: scrollTop + }); + } + this._invokeOnScrollMemoizer({ + scrollLeft: scrollLeft, + scrollTop: scrollTop, + totalWidth: totalWidth, + totalHeight: totalHeight + }); + } + } + } ]), CollectionView; + }(_react.Component); + CollectionView.defaultProps = { + "aria-label": "grid", + horizontalOverscanSize: 0, + noContentRenderer: function() { + return null; + }, + onScroll: function() { + return null; + }, + onSectionRendered: function() { + return null; + }, + scrollToAlignment: "auto", + style: {}, + verticalOverscanSize: 0 + }, exports.default = CollectionView; + }, /* 107 */ + /***/ + function(module, exports, __webpack_require__) { + var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__; + /*! + Copyright (c) 2016 Jed Watson. + Licensed under the MIT License (MIT), see + http://jedwatson.github.io/classnames + */ + /* global define */ + !function() { + "use strict"; + function classNames() { + for (var classes = [], i = 0; i < arguments.length; i++) { + var arg = arguments[i]; + if (arg) { + var argType = typeof arg; + if ("string" === argType || "number" === argType) classes.push(arg); else if (Array.isArray(arg)) classes.push(classNames.apply(null, arg)); else if ("object" === argType) for (var key in arg) hasOwn.call(arg, key) && arg[key] && classes.push(key); + } + } + return classes.join(" "); + } + var hasOwn = {}.hasOwnProperty; + "undefined" != typeof module && module.exports ? module.exports = classNames : (__WEBPACK_AMD_DEFINE_ARRAY__ = [], + __WEBPACK_AMD_DEFINE_RESULT__ = function() { + return classNames; + }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), // register as 'classnames', consistent with npm package name + !(void 0 !== __WEBPACK_AMD_DEFINE_RESULT__ && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))); + }(); + }, /* 108 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + function createCallbackMemoizer() { + var requireAllKeys = !(arguments.length > 0 && void 0 !== arguments[0]) || arguments[0], cachedIndices = {}; + return function(_ref) { + var callback = _ref.callback, indices = _ref.indices, keys = (0, _keys2.default)(indices), allInitialized = !requireAllKeys || keys.every(function(key) { + var value = indices[key]; + return Array.isArray(value) ? value.length > 0 : value >= 0; + }), indexChanged = keys.length !== (0, _keys2.default)(cachedIndices).length || keys.some(function(key) { + var cachedValue = cachedIndices[key], value = indices[key]; + return Array.isArray(value) ? cachedValue.join(",") !== value.join(",") : cachedValue !== value; + }); + cachedIndices = indices, allInitialized && indexChanged && callback(indices); + }; + } + Object.defineProperty(exports, "__esModule", { + value: !0 + }); + var _keys = __webpack_require__(109), _keys2 = _interopRequireDefault(_keys); + exports.default = createCallbackMemoizer; + }, /* 109 */ + /***/ + function(module, exports, __webpack_require__) { + module.exports = { + default: __webpack_require__(110), + __esModule: !0 + }; + }, /* 110 */ + /***/ + function(module, exports, __webpack_require__) { + __webpack_require__(111), module.exports = __webpack_require__(16).Object.keys; + }, /* 111 */ + /***/ + function(module, exports, __webpack_require__) { + // 19.1.2.14 Object.keys(O) + var toObject = __webpack_require__(6), $keys = __webpack_require__(48); + __webpack_require__(14)("keys", function() { + return function(it) { + return $keys(toObject(it)); + }; + }); + }, /* 112 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + var size, canUseDOM = __webpack_require__(113); + module.exports = function(recalc) { + if ((!size || recalc) && canUseDOM) { + var scrollDiv = document.createElementNS("http://www.w3.org/1999/xhtml","div"); + scrollDiv.style.position = "absolute", scrollDiv.style.top = "-9999px", scrollDiv.style.width = "50px", + scrollDiv.style.height = "50px", scrollDiv.style.overflow = "scroll", document.firstElementChild.appendChild(scrollDiv), + size = scrollDiv.offsetWidth - scrollDiv.clientWidth, document.firstElementChild.removeChild(scrollDiv); + } + return size; + }; + }, /* 113 */ + /***/ + function(module, exports) { + "use strict"; + module.exports = !("undefined" == typeof window || !window.document || !window.document.createElement); + }, /* 114 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + function calculateSizeAndPositionData(_ref) { + for (var cellCount = _ref.cellCount, cellSizeAndPositionGetter = _ref.cellSizeAndPositionGetter, sectionSize = _ref.sectionSize, cellMetadata = [], sectionManager = new _SectionManager2.default(sectionSize), height = 0, width = 0, index = 0; index < cellCount; index++) { + var cellMetadatum = cellSizeAndPositionGetter({ + index: index + }); + if (null == cellMetadatum.height || isNaN(cellMetadatum.height) || null == cellMetadatum.width || isNaN(cellMetadatum.width) || null == cellMetadatum.x || isNaN(cellMetadatum.x) || null == cellMetadatum.y || isNaN(cellMetadatum.y)) throw Error("Invalid metadata returned for cell " + index + ":\n x:" + cellMetadatum.x + ", y:" + cellMetadatum.y + ", width:" + cellMetadatum.width + ", height:" + cellMetadatum.height); + height = Math.max(height, cellMetadatum.y + cellMetadatum.height), width = Math.max(width, cellMetadatum.x + cellMetadatum.width), + cellMetadata[index] = cellMetadatum, sectionManager.registerCell({ + cellMetadatum: cellMetadatum, + index: index + }); + } + return { + cellMetadata: cellMetadata, + height: height, + sectionManager: sectionManager, + width: width + }; + } + Object.defineProperty(exports, "__esModule", { + value: !0 + }), exports.default = calculateSizeAndPositionData; + var _SectionManager = __webpack_require__(115), _SectionManager2 = _interopRequireDefault(_SectionManager); + }, /* 115 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + Object.defineProperty(exports, "__esModule", { + value: !0 + }); + var _keys = __webpack_require__(109), _keys2 = _interopRequireDefault(_keys), _classCallCheck2 = __webpack_require__(29), _classCallCheck3 = _interopRequireDefault(_classCallCheck2), _createClass2 = __webpack_require__(30), _createClass3 = _interopRequireDefault(_createClass2), _Section = __webpack_require__(116), _Section2 = _interopRequireDefault(_Section), SECTION_SIZE = 100, SectionManager = function() { + function SectionManager() { + var sectionSize = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : SECTION_SIZE; + (0, _classCallCheck3.default)(this, SectionManager), this._sectionSize = sectionSize, + this._cellMetadata = [], this._sections = {}; + } + return (0, _createClass3.default)(SectionManager, [ { + key: "getCellIndices", + value: function(_ref) { + var height = _ref.height, width = _ref.width, x = _ref.x, y = _ref.y, indices = {}; + return this.getSections({ + height: height, + width: width, + x: x, + y: y + }).forEach(function(section) { + return section.getCellIndices().forEach(function(index) { + indices[index] = index; + }); + }), (0, _keys2.default)(indices).map(function(index) { + return indices[index]; + }); + } + }, { + key: "getCellMetadata", + value: function(_ref2) { + var index = _ref2.index; + return this._cellMetadata[index]; + } + }, { + key: "getSections", + value: function(_ref3) { + for (var height = _ref3.height, width = _ref3.width, x = _ref3.x, y = _ref3.y, sectionXStart = Math.floor(x / this._sectionSize), sectionXStop = Math.floor((x + width - 1) / this._sectionSize), sectionYStart = Math.floor(y / this._sectionSize), sectionYStop = Math.floor((y + height - 1) / this._sectionSize), sections = [], sectionX = sectionXStart; sectionX <= sectionXStop; sectionX++) for (var sectionY = sectionYStart; sectionY <= sectionYStop; sectionY++) { + var key = sectionX + "." + sectionY; + this._sections[key] || (this._sections[key] = new _Section2.default({ + height: this._sectionSize, + width: this._sectionSize, + x: sectionX * this._sectionSize, + y: sectionY * this._sectionSize + })), sections.push(this._sections[key]); + } + return sections; + } + }, { + key: "getTotalSectionCount", + value: function() { + return (0, _keys2.default)(this._sections).length; + } + }, { + key: "toString", + value: function() { + var _this = this; + return (0, _keys2.default)(this._sections).map(function(index) { + return _this._sections[index].toString(); + }); + } + }, { + key: "registerCell", + value: function(_ref4) { + var cellMetadatum = _ref4.cellMetadatum, index = _ref4.index; + this._cellMetadata[index] = cellMetadatum, this.getSections(cellMetadatum).forEach(function(section) { + return section.addCellIndex({ + index: index + }); + }); + } + } ]), SectionManager; + }(); + exports.default = SectionManager; + }, /* 116 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + Object.defineProperty(exports, "__esModule", { + value: !0 + }); + var _classCallCheck2 = __webpack_require__(29), _classCallCheck3 = _interopRequireDefault(_classCallCheck2), _createClass2 = __webpack_require__(30), _createClass3 = _interopRequireDefault(_createClass2), Section = function() { + function Section(_ref) { + var height = _ref.height, width = _ref.width, x = _ref.x, y = _ref.y; + (0, _classCallCheck3.default)(this, Section), this.height = height, this.width = width, + this.x = x, this.y = y, this._indexMap = {}, this._indices = []; + } + return (0, _createClass3.default)(Section, [ { + key: "addCellIndex", + value: function(_ref2) { + var index = _ref2.index; + this._indexMap[index] || (this._indexMap[index] = !0, this._indices.push(index)); + } + }, { + key: "getCellIndices", + value: function() { + return this._indices; + } + }, { + key: "toString", + value: function() { + return this.x + "," + this.y + " " + this.width + "x" + this.height; + } + } ]), Section; + }(); + exports.default = Section; + }, /* 117 */ + /***/ + function(module, exports) { + "use strict"; + function getUpdatedOffsetForIndex(_ref) { + var _ref$align = _ref.align, align = void 0 === _ref$align ? "auto" : _ref$align, cellOffset = _ref.cellOffset, cellSize = _ref.cellSize, containerSize = _ref.containerSize, currentOffset = _ref.currentOffset, maxOffset = cellOffset, minOffset = maxOffset - containerSize + cellSize; + switch (align) { + case "start": + return maxOffset; + + case "end": + return minOffset; + + case "center": + return maxOffset - (containerSize - cellSize) / 2; + + default: + return Math.max(minOffset, Math.min(maxOffset, currentOffset)); + } + } + Object.defineProperty(exports, "__esModule", { + value: !0 + }), exports.default = getUpdatedOffsetForIndex; + }, /* 118 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + Object.defineProperty(exports, "__esModule", { + value: !0 + }), exports.ColumnSizer = exports.default = void 0; + var _ColumnSizer2 = __webpack_require__(119), _ColumnSizer3 = _interopRequireDefault(_ColumnSizer2); + exports.default = _ColumnSizer3.default, exports.ColumnSizer = _ColumnSizer3.default; + }, /* 119 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + Object.defineProperty(exports, "__esModule", { + value: !0 + }); + var _getPrototypeOf = __webpack_require__(3), _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf), _classCallCheck2 = __webpack_require__(29), _classCallCheck3 = _interopRequireDefault(_classCallCheck2), _createClass2 = __webpack_require__(30), _createClass3 = _interopRequireDefault(_createClass2), _possibleConstructorReturn2 = __webpack_require__(34), _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2), _inherits2 = __webpack_require__(81), _inherits3 = _interopRequireDefault(_inherits2), _react = __webpack_require__(89), _reactAddonsShallowCompare = __webpack_require__(90), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), _Grid = __webpack_require__(120), _Grid2 = _interopRequireDefault(_Grid), ColumnSizer = function(_Component) { + function ColumnSizer(props, context) { + (0, _classCallCheck3.default)(this, ColumnSizer); + var _this = (0, _possibleConstructorReturn3.default)(this, (ColumnSizer.__proto__ || (0, + _getPrototypeOf2.default)(ColumnSizer)).call(this, props, context)); + return _this._registerChild = _this._registerChild.bind(_this), _this; + } + return (0, _inherits3.default)(ColumnSizer, _Component), (0, _createClass3.default)(ColumnSizer, [ { + key: "componentDidUpdate", + value: function(prevProps, prevState) { + var _props = this.props, columnMaxWidth = _props.columnMaxWidth, columnMinWidth = _props.columnMinWidth, columnCount = _props.columnCount, width = _props.width; + columnMaxWidth === prevProps.columnMaxWidth && columnMinWidth === prevProps.columnMinWidth && columnCount === prevProps.columnCount && width === prevProps.width || this._registeredChild && this._registeredChild.recomputeGridSize(); + } + }, { + key: "render", + value: function() { + var _props2 = this.props, children = _props2.children, columnMaxWidth = _props2.columnMaxWidth, columnMinWidth = _props2.columnMinWidth, columnCount = _props2.columnCount, width = _props2.width, safeColumnMinWidth = columnMinWidth || 1, safeColumnMaxWidth = columnMaxWidth ? Math.min(columnMaxWidth, width) : width, columnWidth = width / columnCount; + columnWidth = Math.max(safeColumnMinWidth, columnWidth), columnWidth = Math.min(safeColumnMaxWidth, columnWidth), + columnWidth = Math.floor(columnWidth); + var adjustedWidth = Math.min(width, columnWidth * columnCount); + return children({ + adjustedWidth: adjustedWidth, + getColumnWidth: function() { + return columnWidth; + }, + registerChild: this._registerChild + }); + } + }, { + key: "shouldComponentUpdate", + value: function(nextProps, nextState) { + return (0, _reactAddonsShallowCompare2.default)(this, nextProps, nextState); + } + }, { + key: "_registerChild", + value: function(child) { + if (null !== child && !(child instanceof _Grid2.default)) throw Error("Unexpected child type registered; only Grid children are supported."); + this._registeredChild = child, this._registeredChild && this._registeredChild.recomputeGridSize(); + } + } ]), ColumnSizer; + }(_react.Component); + exports.default = ColumnSizer; + }, /* 120 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + Object.defineProperty(exports, "__esModule", { + value: !0 + }), exports.defaultCellRangeRenderer = exports.Grid = exports.default = void 0; + var _Grid2 = __webpack_require__(121), _Grid3 = _interopRequireDefault(_Grid2), _defaultCellRangeRenderer2 = __webpack_require__(127), _defaultCellRangeRenderer3 = _interopRequireDefault(_defaultCellRangeRenderer2); + exports.default = _Grid3.default, exports.Grid = _Grid3.default, exports.defaultCellRangeRenderer = _defaultCellRangeRenderer3.default; + }, /* 121 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + Object.defineProperty(exports, "__esModule", { + value: !0 + }), exports.DEFAULT_SCROLLING_RESET_TIME_INTERVAL = void 0; + var _extends2 = __webpack_require__(100), _extends3 = _interopRequireDefault(_extends2), _getPrototypeOf = __webpack_require__(3), _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf), _classCallCheck2 = __webpack_require__(29), _classCallCheck3 = _interopRequireDefault(_classCallCheck2), _createClass2 = __webpack_require__(30), _createClass3 = _interopRequireDefault(_createClass2), _possibleConstructorReturn2 = __webpack_require__(34), _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2), _inherits2 = __webpack_require__(81), _inherits3 = _interopRequireDefault(_inherits2), _react = __webpack_require__(89), _react2 = _interopRequireDefault(_react), _classnames = __webpack_require__(107), _classnames2 = _interopRequireDefault(_classnames), _calculateSizeAndPositionDataAndUpdateScrollOffset = __webpack_require__(122), _calculateSizeAndPositionDataAndUpdateScrollOffset2 = _interopRequireDefault(_calculateSizeAndPositionDataAndUpdateScrollOffset), _ScalingCellSizeAndPositionManager = __webpack_require__(123), _ScalingCellSizeAndPositionManager2 = _interopRequireDefault(_ScalingCellSizeAndPositionManager), _createCallbackMemoizer = __webpack_require__(108), _createCallbackMemoizer2 = _interopRequireDefault(_createCallbackMemoizer), _getOverscanIndices = __webpack_require__(125), _getOverscanIndices2 = _interopRequireDefault(_getOverscanIndices), _scrollbarSize = __webpack_require__(112), _scrollbarSize2 = _interopRequireDefault(_scrollbarSize), _reactAddonsShallowCompare = __webpack_require__(90), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), _updateScrollIndexHelper = __webpack_require__(126), _updateScrollIndexHelper2 = _interopRequireDefault(_updateScrollIndexHelper), _defaultCellRangeRenderer = __webpack_require__(127), _defaultCellRangeRenderer2 = _interopRequireDefault(_defaultCellRangeRenderer), DEFAULT_SCROLLING_RESET_TIME_INTERVAL = exports.DEFAULT_SCROLLING_RESET_TIME_INTERVAL = 150, SCROLL_POSITION_CHANGE_REASONS = { + OBSERVED: "observed", + REQUESTED: "requested" + }, Grid = function(_Component) { + function Grid(props, context) { + (0, _classCallCheck3.default)(this, Grid); + var _this = (0, _possibleConstructorReturn3.default)(this, (Grid.__proto__ || (0, + _getPrototypeOf2.default)(Grid)).call(this, props, context)); + return _this.state = { + isScrolling: !1, + scrollDirectionHorizontal: _getOverscanIndices.SCROLL_DIRECTION_FIXED, + scrollDirectionVertical: _getOverscanIndices.SCROLL_DIRECTION_FIXED, + scrollLeft: 0, + scrollTop: 0 + }, _this._onGridRenderedMemoizer = (0, _createCallbackMemoizer2.default)(), _this._onScrollMemoizer = (0, + _createCallbackMemoizer2.default)(!1), _this._enablePointerEventsAfterDelayCallback = _this._enablePointerEventsAfterDelayCallback.bind(_this), + _this._invokeOnGridRenderedHelper = _this._invokeOnGridRenderedHelper.bind(_this), + _this._onScroll = _this._onScroll.bind(_this), _this._updateScrollLeftForScrollToColumn = _this._updateScrollLeftForScrollToColumn.bind(_this), + _this._updateScrollTopForScrollToRow = _this._updateScrollTopForScrollToRow.bind(_this), + _this._columnWidthGetter = _this._wrapSizeGetter(props.columnWidth), _this._rowHeightGetter = _this._wrapSizeGetter(props.rowHeight), + _this._columnSizeAndPositionManager = new _ScalingCellSizeAndPositionManager2.default({ + cellCount: props.columnCount, + cellSizeGetter: function(index) { + return _this._columnWidthGetter(index); + }, + estimatedCellSize: _this._getEstimatedColumnSize(props) + }), _this._rowSizeAndPositionManager = new _ScalingCellSizeAndPositionManager2.default({ + cellCount: props.rowCount, + cellSizeGetter: function(index) { + return _this._rowHeightGetter(index); + }, + estimatedCellSize: _this._getEstimatedRowSize(props) + }), _this._cellCache = {}, _this; + } + return (0, _inherits3.default)(Grid, _Component), (0, _createClass3.default)(Grid, [ { + key: "measureAllCells", + value: function() { + var _props = this.props, columnCount = _props.columnCount, rowCount = _props.rowCount; + this._columnSizeAndPositionManager.getSizeAndPositionOfCell(columnCount - 1), this._rowSizeAndPositionManager.getSizeAndPositionOfCell(rowCount - 1); + } + }, { + key: "recomputeGridSize", + value: function() { + var _ref = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {}, _ref$columnIndex = _ref.columnIndex, columnIndex = void 0 === _ref$columnIndex ? 0 : _ref$columnIndex, _ref$rowIndex = _ref.rowIndex, rowIndex = void 0 === _ref$rowIndex ? 0 : _ref$rowIndex; + this._columnSizeAndPositionManager.resetCell(columnIndex), this._rowSizeAndPositionManager.resetCell(rowIndex), + this._cellCache = {}, this.forceUpdate(); + } + }, { + key: "componentDidMount", + value: function() { + var _props2 = this.props, scrollLeft = _props2.scrollLeft, scrollToColumn = _props2.scrollToColumn, scrollTop = _props2.scrollTop, scrollToRow = _props2.scrollToRow; + this._scrollbarSizeMeasured || (this._scrollbarSize = (0, _scrollbarSize2.default)(), + this._scrollbarSizeMeasured = !0, this.setState({})), (scrollLeft >= 0 || scrollTop >= 0) && this._setScrollPosition({ + scrollLeft: scrollLeft, + scrollTop: scrollTop + }), (scrollToColumn >= 0 || scrollToRow >= 0) && (this._updateScrollLeftForScrollToColumn(), + this._updateScrollTopForScrollToRow()), this._invokeOnGridRenderedHelper(), this._invokeOnScrollMemoizer({ + scrollLeft: scrollLeft || 0, + scrollTop: scrollTop || 0, + totalColumnsWidth: this._columnSizeAndPositionManager.getTotalSize(), + totalRowsHeight: this._rowSizeAndPositionManager.getTotalSize() + }); + } + }, { + key: "componentDidUpdate", + value: function(prevProps, prevState) { + var _this2 = this, _props3 = this.props, autoHeight = _props3.autoHeight, columnCount = _props3.columnCount, height = _props3.height, rowCount = _props3.rowCount, scrollToAlignment = _props3.scrollToAlignment, scrollToColumn = _props3.scrollToColumn, scrollToRow = _props3.scrollToRow, width = _props3.width, _state = this.state, scrollLeft = _state.scrollLeft, scrollPositionChangeReason = _state.scrollPositionChangeReason, scrollTop = _state.scrollTop, columnOrRowCountJustIncreasedFromZero = columnCount > 0 && 0 === prevProps.columnCount || rowCount > 0 && 0 === prevProps.rowCount; + if (scrollPositionChangeReason === SCROLL_POSITION_CHANGE_REASONS.REQUESTED && (scrollLeft >= 0 && (scrollLeft !== prevState.scrollLeft && scrollLeft !== this._scrollingContainer.scrollLeft || columnOrRowCountJustIncreasedFromZero) && (this._scrollingContainer.scrollLeft = scrollLeft), + !autoHeight && scrollTop >= 0 && (scrollTop !== prevState.scrollTop && scrollTop !== this._scrollingContainer.scrollTop || columnOrRowCountJustIncreasedFromZero) && (this._scrollingContainer.scrollTop = scrollTop)), + (0, _updateScrollIndexHelper2.default)({ + cellSizeAndPositionManager: this._columnSizeAndPositionManager, + previousCellsCount: prevProps.columnCount, + previousCellSize: prevProps.columnWidth, + previousScrollToAlignment: prevProps.scrollToAlignment, + previousScrollToIndex: prevProps.scrollToColumn, + previousSize: prevProps.width, + scrollOffset: scrollLeft, + scrollToAlignment: scrollToAlignment, + scrollToIndex: scrollToColumn, + size: width, + updateScrollIndexCallback: function(scrollToColumn) { + return _this2._updateScrollLeftForScrollToColumn((0, _extends3.default)({}, _this2.props, { + scrollToColumn: scrollToColumn + })); + } + }), (0, _updateScrollIndexHelper2.default)({ + cellSizeAndPositionManager: this._rowSizeAndPositionManager, + previousCellsCount: prevProps.rowCount, + previousCellSize: prevProps.rowHeight, + previousScrollToAlignment: prevProps.scrollToAlignment, + previousScrollToIndex: prevProps.scrollToRow, + previousSize: prevProps.height, + scrollOffset: scrollTop, + scrollToAlignment: scrollToAlignment, + scrollToIndex: scrollToRow, + size: height, + updateScrollIndexCallback: function(scrollToRow) { + return _this2._updateScrollTopForScrollToRow((0, _extends3.default)({}, _this2.props, { + scrollToRow: scrollToRow + })); + } + }), this._invokeOnGridRenderedHelper(), scrollLeft !== prevState.scrollLeft || scrollTop !== prevState.scrollTop) { + var totalRowsHeight = this._rowSizeAndPositionManager.getTotalSize(), totalColumnsWidth = this._columnSizeAndPositionManager.getTotalSize(); + this._invokeOnScrollMemoizer({ + scrollLeft: scrollLeft, + scrollTop: scrollTop, + totalColumnsWidth: totalColumnsWidth, + totalRowsHeight: totalRowsHeight + }); + } + } + }, { + key: "componentWillMount", + value: function() { + this._scrollbarSize = (0, _scrollbarSize2.default)(), void 0 === this._scrollbarSize ? (this._scrollbarSizeMeasured = !1, + this._scrollbarSize = 0) : this._scrollbarSizeMeasured = !0, this._calculateChildrenToRender(); + } + }, { + key: "componentWillUnmount", + value: function() { + this._disablePointerEventsTimeoutId && clearTimeout(this._disablePointerEventsTimeoutId); + } + }, { + key: "componentWillUpdate", + value: function(nextProps, nextState) { + var _this3 = this; + 0 === nextProps.columnCount && 0 !== nextState.scrollLeft || 0 === nextProps.rowCount && 0 !== nextState.scrollTop ? this._setScrollPosition({ + scrollLeft: 0, + scrollTop: 0 + }) : nextProps.scrollLeft === this.props.scrollLeft && nextProps.scrollTop === this.props.scrollTop || this._setScrollPosition({ + scrollLeft: nextProps.scrollLeft, + scrollTop: nextProps.scrollTop + }), this._columnWidthGetter = this._wrapSizeGetter(nextProps.columnWidth), this._rowHeightGetter = this._wrapSizeGetter(nextProps.rowHeight), + this._columnSizeAndPositionManager.configure({ + cellCount: nextProps.columnCount, + estimatedCellSize: this._getEstimatedColumnSize(nextProps) + }), this._rowSizeAndPositionManager.configure({ + cellCount: nextProps.rowCount, + estimatedCellSize: this._getEstimatedRowSize(nextProps) + }), (0, _calculateSizeAndPositionDataAndUpdateScrollOffset2.default)({ + cellCount: this.props.columnCount, + cellSize: this.props.columnWidth, + computeMetadataCallback: function() { + return _this3._columnSizeAndPositionManager.resetCell(0); + }, + computeMetadataCallbackProps: nextProps, + nextCellsCount: nextProps.columnCount, + nextCellSize: nextProps.columnWidth, + nextScrollToIndex: nextProps.scrollToColumn, + scrollToIndex: this.props.scrollToColumn, + updateScrollOffsetForScrollToIndex: function() { + return _this3._updateScrollLeftForScrollToColumn(nextProps, nextState); + } + }), (0, _calculateSizeAndPositionDataAndUpdateScrollOffset2.default)({ + cellCount: this.props.rowCount, + cellSize: this.props.rowHeight, + computeMetadataCallback: function() { + return _this3._rowSizeAndPositionManager.resetCell(0); + }, + computeMetadataCallbackProps: nextProps, + nextCellsCount: nextProps.rowCount, + nextCellSize: nextProps.rowHeight, + nextScrollToIndex: nextProps.scrollToRow, + scrollToIndex: this.props.scrollToRow, + updateScrollOffsetForScrollToIndex: function() { + return _this3._updateScrollTopForScrollToRow(nextProps, nextState); + } + }), this._calculateChildrenToRender(nextProps, nextState); + } + }, { + key: "render", + value: function() { + var _this4 = this, _props4 = this.props, autoContainerWidth = _props4.autoContainerWidth, autoHeight = _props4.autoHeight, className = _props4.className, containerStyle = _props4.containerStyle, height = _props4.height, id = _props4.id, noContentRenderer = _props4.noContentRenderer, style = _props4.style, tabIndex = _props4.tabIndex, width = _props4.width, isScrolling = this.state.isScrolling, gridStyle = { + boxSizing: "border-box", + height: autoHeight ? "auto" : height, + position: "relative", + width: width, + WebkitOverflowScrolling: "touch", + willChange: "transform" + }, totalColumnsWidth = this._columnSizeAndPositionManager.getTotalSize(), totalRowsHeight = this._rowSizeAndPositionManager.getTotalSize(), verticalScrollBarSize = totalRowsHeight > height ? this._scrollbarSize : 0, horizontalScrollBarSize = totalColumnsWidth > width ? this._scrollbarSize : 0; + gridStyle.overflowX = totalColumnsWidth + verticalScrollBarSize <= width ? "hidden" : "auto", + gridStyle.overflowY = totalRowsHeight + horizontalScrollBarSize <= height ? "hidden" : "auto"; + var childrenToDisplay = this._childrenToDisplay, showNoContentRenderer = 0 === childrenToDisplay.length && height > 0 && width > 0; + return _react2.default.createElement("div", { + ref: function(_ref2) { + _this4._scrollingContainer = _ref2; + }, + "aria-label": this.props["aria-label"], + className: (0, _classnames2.default)("ReactVirtualized__Grid", className), + id: id, + onScroll: this._onScroll, + role: "grid", + style: (0, _extends3.default)({}, gridStyle, style), + tabIndex: tabIndex + }, childrenToDisplay.length > 0 && _react2.default.createElement("div", { + className: "ReactVirtualized__Grid__innerScrollContainer", + style: (0, _extends3.default)({ + width: autoContainerWidth ? "auto" : totalColumnsWidth, + height: totalRowsHeight, + maxWidth: totalColumnsWidth, + maxHeight: totalRowsHeight, + overflow: "hidden", + pointerEvents: isScrolling ? "none" : "" + }, containerStyle) + }, childrenToDisplay), showNoContentRenderer && noContentRenderer()); + } + }, { + key: "shouldComponentUpdate", + value: function(nextProps, nextState) { + return (0, _reactAddonsShallowCompare2.default)(this, nextProps, nextState); + } + }, { + key: "_calculateChildrenToRender", + value: function() { + var props = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : this.props, state = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : this.state, cellRenderer = props.cellRenderer, cellRangeRenderer = props.cellRangeRenderer, columnCount = props.columnCount, height = props.height, overscanColumnCount = props.overscanColumnCount, overscanRowCount = props.overscanRowCount, rowCount = props.rowCount, width = props.width, isScrolling = state.isScrolling, scrollDirectionHorizontal = state.scrollDirectionHorizontal, scrollDirectionVertical = state.scrollDirectionVertical, scrollLeft = state.scrollLeft, scrollTop = state.scrollTop; + if (this._childrenToDisplay = [], height > 0 && width > 0) { + var visibleColumnIndices = this._columnSizeAndPositionManager.getVisibleCellRange({ + containerSize: width, + offset: scrollLeft + }), visibleRowIndices = this._rowSizeAndPositionManager.getVisibleCellRange({ + containerSize: height, + offset: scrollTop + }), horizontalOffsetAdjustment = this._columnSizeAndPositionManager.getOffsetAdjustment({ + containerSize: width, + offset: scrollLeft + }), verticalOffsetAdjustment = this._rowSizeAndPositionManager.getOffsetAdjustment({ + containerSize: height, + offset: scrollTop + }); + this._renderedColumnStartIndex = visibleColumnIndices.start, this._renderedColumnStopIndex = visibleColumnIndices.stop, + this._renderedRowStartIndex = visibleRowIndices.start, this._renderedRowStopIndex = visibleRowIndices.stop; + var overscanColumnIndices = (0, _getOverscanIndices2.default)({ + cellCount: columnCount, + overscanCellsCount: overscanColumnCount, + scrollDirection: scrollDirectionHorizontal, + startIndex: this._renderedColumnStartIndex, + stopIndex: this._renderedColumnStopIndex + }), overscanRowIndices = (0, _getOverscanIndices2.default)({ + cellCount: rowCount, + overscanCellsCount: overscanRowCount, + scrollDirection: scrollDirectionVertical, + startIndex: this._renderedRowStartIndex, + stopIndex: this._renderedRowStopIndex + }); + this._columnStartIndex = overscanColumnIndices.overscanStartIndex, this._columnStopIndex = overscanColumnIndices.overscanStopIndex, + this._rowStartIndex = overscanRowIndices.overscanStartIndex, this._rowStopIndex = overscanRowIndices.overscanStopIndex, + this._childrenToDisplay = cellRangeRenderer({ + cellCache: this._cellCache, + cellRenderer: cellRenderer, + columnSizeAndPositionManager: this._columnSizeAndPositionManager, + columnStartIndex: this._columnStartIndex, + columnStopIndex: this._columnStopIndex, + horizontalOffsetAdjustment: horizontalOffsetAdjustment, + isScrolling: isScrolling, + rowSizeAndPositionManager: this._rowSizeAndPositionManager, + rowStartIndex: this._rowStartIndex, + rowStopIndex: this._rowStopIndex, + scrollLeft: scrollLeft, + scrollTop: scrollTop, + verticalOffsetAdjustment: verticalOffsetAdjustment, + visibleColumnIndices: visibleColumnIndices, + visibleRowIndices: visibleRowIndices + }); + } + } + }, { + key: "_enablePointerEventsAfterDelay", + value: function() { + var scrollingResetTimeInterval = this.props.scrollingResetTimeInterval; + this._disablePointerEventsTimeoutId && clearTimeout(this._disablePointerEventsTimeoutId), + this._disablePointerEventsTimeoutId = setTimeout(this._enablePointerEventsAfterDelayCallback, scrollingResetTimeInterval); + } + }, { + key: "_enablePointerEventsAfterDelayCallback", + value: function() { + this._disablePointerEventsTimeoutId = null, this._cellCache = {}, this.setState({ + isScrolling: !1, + scrollDirectionHorizontal: _getOverscanIndices.SCROLL_DIRECTION_FIXED, + scrollDirectionVertical: _getOverscanIndices.SCROLL_DIRECTION_FIXED + }); + } + }, { + key: "_getEstimatedColumnSize", + value: function(props) { + return "number" == typeof props.columnWidth ? props.columnWidth : props.estimatedColumnSize; + } + }, { + key: "_getEstimatedRowSize", + value: function(props) { + return "number" == typeof props.rowHeight ? props.rowHeight : props.estimatedRowSize; + } + }, { + key: "_invokeOnGridRenderedHelper", + value: function() { + var onSectionRendered = this.props.onSectionRendered; + this._onGridRenderedMemoizer({ + callback: onSectionRendered, + indices: { + columnOverscanStartIndex: this._columnStartIndex, + columnOverscanStopIndex: this._columnStopIndex, + columnStartIndex: this._renderedColumnStartIndex, + columnStopIndex: this._renderedColumnStopIndex, + rowOverscanStartIndex: this._rowStartIndex, + rowOverscanStopIndex: this._rowStopIndex, + rowStartIndex: this._renderedRowStartIndex, + rowStopIndex: this._renderedRowStopIndex + } + }); + } + }, { + key: "_invokeOnScrollMemoizer", + value: function(_ref3) { + var _this5 = this, scrollLeft = _ref3.scrollLeft, scrollTop = _ref3.scrollTop, totalColumnsWidth = _ref3.totalColumnsWidth, totalRowsHeight = _ref3.totalRowsHeight; + this._onScrollMemoizer({ + callback: function(_ref4) { + var scrollLeft = _ref4.scrollLeft, scrollTop = _ref4.scrollTop, _props5 = _this5.props, height = _props5.height, onScroll = _props5.onScroll, width = _props5.width; + onScroll({ + clientHeight: height, + clientWidth: width, + scrollHeight: totalRowsHeight, + scrollLeft: scrollLeft, + scrollTop: scrollTop, + scrollWidth: totalColumnsWidth + }); + }, + indices: { + scrollLeft: scrollLeft, + scrollTop: scrollTop + } + }); + } + }, { + key: "_setScrollPosition", + value: function(_ref5) { + var scrollLeft = _ref5.scrollLeft, scrollTop = _ref5.scrollTop, newState = { + scrollPositionChangeReason: SCROLL_POSITION_CHANGE_REASONS.REQUESTED + }; + scrollLeft >= 0 && (newState.scrollLeft = scrollLeft), scrollTop >= 0 && (newState.scrollTop = scrollTop), + (scrollLeft >= 0 && scrollLeft !== this.state.scrollLeft || scrollTop >= 0 && scrollTop !== this.state.scrollTop) && this.setState(newState); + } + }, { + key: "_wrapPropertyGetter", + value: function(value) { + return value instanceof Function ? value : function() { + return value; + }; + } + }, { + key: "_wrapSizeGetter", + value: function(size) { + return this._wrapPropertyGetter(size); + } + }, { + key: "_updateScrollLeftForScrollToColumn", + value: function() { + var props = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : this.props, state = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : this.state, columnCount = props.columnCount, scrollToAlignment = props.scrollToAlignment, scrollToColumn = props.scrollToColumn, width = props.width, scrollLeft = state.scrollLeft; + if (scrollToColumn >= 0 && columnCount > 0) { + var targetIndex = Math.max(0, Math.min(columnCount - 1, scrollToColumn)), calculatedScrollLeft = this._columnSizeAndPositionManager.getUpdatedOffsetForIndex({ + align: scrollToAlignment, + containerSize: width, + currentOffset: scrollLeft, + targetIndex: targetIndex + }); + scrollLeft !== calculatedScrollLeft && this._setScrollPosition({ + scrollLeft: calculatedScrollLeft + }); + } + } + }, { + key: "_updateScrollTopForScrollToRow", + value: function() { + var props = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : this.props, state = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : this.state, height = props.height, rowCount = props.rowCount, scrollToAlignment = props.scrollToAlignment, scrollToRow = props.scrollToRow, scrollTop = state.scrollTop; + if (scrollToRow >= 0 && rowCount > 0) { + var targetIndex = Math.max(0, Math.min(rowCount - 1, scrollToRow)), calculatedScrollTop = this._rowSizeAndPositionManager.getUpdatedOffsetForIndex({ + align: scrollToAlignment, + containerSize: height, + currentOffset: scrollTop, + targetIndex: targetIndex + }); + scrollTop !== calculatedScrollTop && this._setScrollPosition({ + scrollTop: calculatedScrollTop + }); + } + } + }, { + key: "_onScroll", + value: function(event) { + if (event.target === this._scrollingContainer) { + this._enablePointerEventsAfterDelay(); + var _props6 = this.props, height = _props6.height, width = _props6.width, scrollbarSize = this._scrollbarSize, totalRowsHeight = this._rowSizeAndPositionManager.getTotalSize(), totalColumnsWidth = this._columnSizeAndPositionManager.getTotalSize(), scrollLeft = Math.min(Math.max(0, totalColumnsWidth - width + scrollbarSize), event.target.scrollLeft), scrollTop = Math.min(Math.max(0, totalRowsHeight - height + scrollbarSize), event.target.scrollTop); + if (this.state.scrollLeft !== scrollLeft || this.state.scrollTop !== scrollTop) { + var scrollDirectionVertical = scrollTop > this.state.scrollTop ? _getOverscanIndices.SCROLL_DIRECTION_FORWARD : _getOverscanIndices.SCROLL_DIRECTION_BACKWARD, scrollDirectionHorizontal = scrollLeft > this.state.scrollLeft ? _getOverscanIndices.SCROLL_DIRECTION_FORWARD : _getOverscanIndices.SCROLL_DIRECTION_BACKWARD; + this.setState({ + isScrolling: !0, + scrollDirectionHorizontal: scrollDirectionHorizontal, + scrollDirectionVertical: scrollDirectionVertical, + scrollLeft: scrollLeft, + scrollPositionChangeReason: SCROLL_POSITION_CHANGE_REASONS.OBSERVED, + scrollTop: scrollTop + }); + } + this._invokeOnScrollMemoizer({ + scrollLeft: scrollLeft, + scrollTop: scrollTop, + totalColumnsWidth: totalColumnsWidth, + totalRowsHeight: totalRowsHeight + }); + } + } + } ]), Grid; + }(_react.Component); + Grid.defaultProps = { + "aria-label": "grid", + cellRangeRenderer: _defaultCellRangeRenderer2.default, + estimatedColumnSize: 100, + estimatedRowSize: 30, + noContentRenderer: function() { + return null; + }, + onScroll: function() { + return null; + }, + onSectionRendered: function() { + return null; + }, + overscanColumnCount: 0, + overscanRowCount: 10, + scrollingResetTimeInterval: DEFAULT_SCROLLING_RESET_TIME_INTERVAL, + scrollToAlignment: "auto", + style: {}, + tabIndex: 0 + }, exports.default = Grid; + }, /* 122 */ + /***/ + function(module, exports) { + "use strict"; + function calculateSizeAndPositionDataAndUpdateScrollOffset(_ref) { + var cellCount = _ref.cellCount, cellSize = _ref.cellSize, computeMetadataCallback = _ref.computeMetadataCallback, computeMetadataCallbackProps = _ref.computeMetadataCallbackProps, nextCellsCount = _ref.nextCellsCount, nextCellSize = _ref.nextCellSize, nextScrollToIndex = _ref.nextScrollToIndex, scrollToIndex = _ref.scrollToIndex, updateScrollOffsetForScrollToIndex = _ref.updateScrollOffsetForScrollToIndex; + cellCount === nextCellsCount && ("number" != typeof cellSize && "number" != typeof nextCellSize || cellSize === nextCellSize) || (computeMetadataCallback(computeMetadataCallbackProps), + scrollToIndex >= 0 && scrollToIndex === nextScrollToIndex && updateScrollOffsetForScrollToIndex()); + } + Object.defineProperty(exports, "__esModule", { + value: !0 + }), exports.default = calculateSizeAndPositionDataAndUpdateScrollOffset; + }, /* 123 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + Object.defineProperty(exports, "__esModule", { + value: !0 + }), exports.DEFAULT_MAX_SCROLL_SIZE = void 0; + var _objectWithoutProperties2 = __webpack_require__(105), _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2), _classCallCheck2 = __webpack_require__(29), _classCallCheck3 = _interopRequireDefault(_classCallCheck2), _createClass2 = __webpack_require__(30), _createClass3 = _interopRequireDefault(_createClass2), _CellSizeAndPositionManager = __webpack_require__(124), _CellSizeAndPositionManager2 = _interopRequireDefault(_CellSizeAndPositionManager), DEFAULT_MAX_SCROLL_SIZE = exports.DEFAULT_MAX_SCROLL_SIZE = 15e5, ScalingCellSizeAndPositionManager = function() { + function ScalingCellSizeAndPositionManager(_ref) { + var _ref$maxScrollSize = _ref.maxScrollSize, maxScrollSize = void 0 === _ref$maxScrollSize ? DEFAULT_MAX_SCROLL_SIZE : _ref$maxScrollSize, params = (0, + _objectWithoutProperties3.default)(_ref, [ "maxScrollSize" ]); + (0, _classCallCheck3.default)(this, ScalingCellSizeAndPositionManager), this._cellSizeAndPositionManager = new _CellSizeAndPositionManager2.default(params), + this._maxScrollSize = maxScrollSize; + } + return (0, _createClass3.default)(ScalingCellSizeAndPositionManager, [ { + key: "configure", + value: function(params) { + this._cellSizeAndPositionManager.configure(params); + } + }, { + key: "getCellCount", + value: function() { + return this._cellSizeAndPositionManager.getCellCount(); + } + }, { + key: "getEstimatedCellSize", + value: function() { + return this._cellSizeAndPositionManager.getEstimatedCellSize(); + } + }, { + key: "getLastMeasuredIndex", + value: function() { + return this._cellSizeAndPositionManager.getLastMeasuredIndex(); + } + }, { + key: "getOffsetAdjustment", + value: function(_ref2) { + var containerSize = _ref2.containerSize, offset = _ref2.offset, totalSize = this._cellSizeAndPositionManager.getTotalSize(), safeTotalSize = this.getTotalSize(), offsetPercentage = this._getOffsetPercentage({ + containerSize: containerSize, + offset: offset, + totalSize: safeTotalSize + }); + return Math.round(offsetPercentage * (safeTotalSize - totalSize)); + } + }, { + key: "getSizeAndPositionOfCell", + value: function(index) { + return this._cellSizeAndPositionManager.getSizeAndPositionOfCell(index); + } + }, { + key: "getSizeAndPositionOfLastMeasuredCell", + value: function() { + return this._cellSizeAndPositionManager.getSizeAndPositionOfLastMeasuredCell(); + } + }, { + key: "getTotalSize", + value: function() { + return Math.min(this._maxScrollSize, this._cellSizeAndPositionManager.getTotalSize()); + } + }, { + key: "getUpdatedOffsetForIndex", + value: function(_ref3) { + var _ref3$align = _ref3.align, align = void 0 === _ref3$align ? "auto" : _ref3$align, containerSize = _ref3.containerSize, currentOffset = _ref3.currentOffset, targetIndex = _ref3.targetIndex, totalSize = _ref3.totalSize; + currentOffset = this._safeOffsetToOffset({ + containerSize: containerSize, + offset: currentOffset + }); + var offset = this._cellSizeAndPositionManager.getUpdatedOffsetForIndex({ + align: align, + containerSize: containerSize, + currentOffset: currentOffset, + targetIndex: targetIndex, + totalSize: totalSize + }); + return this._offsetToSafeOffset({ + containerSize: containerSize, + offset: offset + }); + } + }, { + key: "getVisibleCellRange", + value: function(_ref4) { + var containerSize = _ref4.containerSize, offset = _ref4.offset; + return offset = this._safeOffsetToOffset({ + containerSize: containerSize, + offset: offset + }), this._cellSizeAndPositionManager.getVisibleCellRange({ + containerSize: containerSize, + offset: offset + }); + } + }, { + key: "resetCell", + value: function(index) { + this._cellSizeAndPositionManager.resetCell(index); + } + }, { + key: "_getOffsetPercentage", + value: function(_ref5) { + var containerSize = _ref5.containerSize, offset = _ref5.offset, totalSize = _ref5.totalSize; + return totalSize <= containerSize ? 0 : offset / (totalSize - containerSize); + } + }, { + key: "_offsetToSafeOffset", + value: function(_ref6) { + var containerSize = _ref6.containerSize, offset = _ref6.offset, totalSize = this._cellSizeAndPositionManager.getTotalSize(), safeTotalSize = this.getTotalSize(); + if (totalSize === safeTotalSize) return offset; + var offsetPercentage = this._getOffsetPercentage({ + containerSize: containerSize, + offset: offset, + totalSize: totalSize + }); + return Math.round(offsetPercentage * (safeTotalSize - containerSize)); + } + }, { + key: "_safeOffsetToOffset", + value: function(_ref7) { + var containerSize = _ref7.containerSize, offset = _ref7.offset, totalSize = this._cellSizeAndPositionManager.getTotalSize(), safeTotalSize = this.getTotalSize(); + if (totalSize === safeTotalSize) return offset; + var offsetPercentage = this._getOffsetPercentage({ + containerSize: containerSize, + offset: offset, + totalSize: safeTotalSize + }); + return Math.round(offsetPercentage * (totalSize - containerSize)); + } + } ]), ScalingCellSizeAndPositionManager; + }(); + exports.default = ScalingCellSizeAndPositionManager; + }, /* 124 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + Object.defineProperty(exports, "__esModule", { + value: !0 + }); + var _classCallCheck2 = __webpack_require__(29), _classCallCheck3 = _interopRequireDefault(_classCallCheck2), _createClass2 = __webpack_require__(30), _createClass3 = _interopRequireDefault(_createClass2), CellSizeAndPositionManager = function() { + function CellSizeAndPositionManager(_ref) { + var cellCount = _ref.cellCount, cellSizeGetter = _ref.cellSizeGetter, estimatedCellSize = _ref.estimatedCellSize; + (0, _classCallCheck3.default)(this, CellSizeAndPositionManager), this._cellSizeGetter = cellSizeGetter, + this._cellCount = cellCount, this._estimatedCellSize = estimatedCellSize, this._cellSizeAndPositionData = {}, + this._lastMeasuredIndex = -1; + } + return (0, _createClass3.default)(CellSizeAndPositionManager, [ { + key: "configure", + value: function(_ref2) { + var cellCount = _ref2.cellCount, estimatedCellSize = _ref2.estimatedCellSize; + this._cellCount = cellCount, this._estimatedCellSize = estimatedCellSize; + } + }, { + key: "getCellCount", + value: function() { + return this._cellCount; + } + }, { + key: "getEstimatedCellSize", + value: function() { + return this._estimatedCellSize; + } + }, { + key: "getLastMeasuredIndex", + value: function() { + return this._lastMeasuredIndex; + } + }, { + key: "getSizeAndPositionOfCell", + value: function(index) { + if (index < 0 || index >= this._cellCount) throw Error("Requested index " + index + " is outside of range 0.." + this._cellCount); + if (index > this._lastMeasuredIndex) { + for (var lastMeasuredCellSizeAndPosition = this.getSizeAndPositionOfLastMeasuredCell(), _offset = lastMeasuredCellSizeAndPosition.offset + lastMeasuredCellSizeAndPosition.size, i = this._lastMeasuredIndex + 1; i <= index; i++) { + var _size = this._cellSizeGetter({ + index: i + }); + if (null == _size || isNaN(_size)) throw Error("Invalid size returned for cell " + i + " of value " + _size); + this._cellSizeAndPositionData[i] = { + offset: _offset, + size: _size + }, _offset += _size; + } + this._lastMeasuredIndex = index; + } + return this._cellSizeAndPositionData[index]; + } + }, { + key: "getSizeAndPositionOfLastMeasuredCell", + value: function() { + return this._lastMeasuredIndex >= 0 ? this._cellSizeAndPositionData[this._lastMeasuredIndex] : { + offset: 0, + size: 0 + }; + } + }, { + key: "getTotalSize", + value: function() { + var lastMeasuredCellSizeAndPosition = this.getSizeAndPositionOfLastMeasuredCell(); + return lastMeasuredCellSizeAndPosition.offset + lastMeasuredCellSizeAndPosition.size + (this._cellCount - this._lastMeasuredIndex - 1) * this._estimatedCellSize; + } + }, { + key: "getUpdatedOffsetForIndex", + value: function(_ref3) { + var _ref3$align = _ref3.align, align = void 0 === _ref3$align ? "auto" : _ref3$align, containerSize = _ref3.containerSize, currentOffset = _ref3.currentOffset, targetIndex = _ref3.targetIndex; + if (containerSize <= 0) return 0; + var datum = this.getSizeAndPositionOfCell(targetIndex), maxOffset = datum.offset, minOffset = maxOffset - containerSize + datum.size, idealOffset = void 0; + switch (align) { + case "start": + idealOffset = maxOffset; + break; + + case "end": + idealOffset = minOffset; + break; + + case "center": + idealOffset = maxOffset - (containerSize - datum.size) / 2; + break; + + default: + idealOffset = Math.max(minOffset, Math.min(maxOffset, currentOffset)); + } + var totalSize = this.getTotalSize(); + return Math.max(0, Math.min(totalSize - containerSize, idealOffset)); + } + }, { + key: "getVisibleCellRange", + value: function(_ref4) { + var containerSize = _ref4.containerSize, offset = _ref4.offset, totalSize = this.getTotalSize(); + if (0 === totalSize) return {}; + var maxOffset = offset + containerSize, start = this._findNearestCell(offset), datum = this.getSizeAndPositionOfCell(start); + offset = datum.offset + datum.size; + for (var stop = start; offset < maxOffset && stop < this._cellCount - 1; ) stop++, + offset += this.getSizeAndPositionOfCell(stop).size; + return { + start: start, + stop: stop + }; + } + }, { + key: "resetCell", + value: function(index) { + this._lastMeasuredIndex = Math.min(this._lastMeasuredIndex, index - 1); + } + }, { + key: "_binarySearch", + value: function(_ref5) { + for (var high = _ref5.high, low = _ref5.low, offset = _ref5.offset, middle = void 0, currentOffset = void 0; low <= high; ) { + if (middle = low + Math.floor((high - low) / 2), currentOffset = this.getSizeAndPositionOfCell(middle).offset, + currentOffset === offset) return middle; + currentOffset < offset ? low = middle + 1 : currentOffset > offset && (high = middle - 1); + } + if (low > 0) return low - 1; + } + }, { + key: "_exponentialSearch", + value: function(_ref6) { + for (var index = _ref6.index, offset = _ref6.offset, interval = 1; index < this._cellCount && this.getSizeAndPositionOfCell(index).offset < offset; ) index += interval, + interval *= 2; + return this._binarySearch({ + high: Math.min(index, this._cellCount - 1), + low: Math.floor(index / 2), + offset: offset + }); + } + }, { + key: "_findNearestCell", + value: function(offset) { + if (isNaN(offset)) throw Error("Invalid offset " + offset + " specified"); + offset = Math.max(0, offset); + var lastMeasuredCellSizeAndPosition = this.getSizeAndPositionOfLastMeasuredCell(), lastMeasuredIndex = Math.max(0, this._lastMeasuredIndex); + return lastMeasuredCellSizeAndPosition.offset >= offset ? this._binarySearch({ + high: lastMeasuredIndex, + low: 0, + offset: offset + }) : this._exponentialSearch({ + index: lastMeasuredIndex, + offset: offset + }); + } + } ]), CellSizeAndPositionManager; + }(); + exports.default = CellSizeAndPositionManager; + }, /* 125 */ + /***/ + function(module, exports) { + "use strict"; + function getOverscanIndices(_ref) { + var cellCount = _ref.cellCount, overscanCellsCount = _ref.overscanCellsCount, scrollDirection = _ref.scrollDirection, startIndex = _ref.startIndex, stopIndex = _ref.stopIndex, overscanStartIndex = void 0, overscanStopIndex = void 0; + return scrollDirection === SCROLL_DIRECTION_FORWARD ? (overscanStartIndex = startIndex, + overscanStopIndex = stopIndex + 2 * overscanCellsCount) : scrollDirection === SCROLL_DIRECTION_BACKWARD ? (overscanStartIndex = startIndex - 2 * overscanCellsCount, + overscanStopIndex = stopIndex) : (overscanStartIndex = startIndex - overscanCellsCount, + overscanStopIndex = stopIndex + overscanCellsCount), { + overscanStartIndex: Math.max(0, overscanStartIndex), + overscanStopIndex: Math.min(cellCount - 1, overscanStopIndex) + }; + } + Object.defineProperty(exports, "__esModule", { + value: !0 + }), exports.default = getOverscanIndices; + var SCROLL_DIRECTION_BACKWARD = exports.SCROLL_DIRECTION_BACKWARD = -1, SCROLL_DIRECTION_FORWARD = (exports.SCROLL_DIRECTION_FIXED = 0, + exports.SCROLL_DIRECTION_FORWARD = 1); + }, /* 126 */ + /***/ + function(module, exports) { + "use strict"; + function updateScrollIndexHelper(_ref) { + var cellSize = _ref.cellSize, cellSizeAndPositionManager = _ref.cellSizeAndPositionManager, previousCellsCount = _ref.previousCellsCount, previousCellSize = _ref.previousCellSize, previousScrollToAlignment = _ref.previousScrollToAlignment, previousScrollToIndex = _ref.previousScrollToIndex, previousSize = _ref.previousSize, scrollOffset = _ref.scrollOffset, scrollToAlignment = _ref.scrollToAlignment, scrollToIndex = _ref.scrollToIndex, size = _ref.size, updateScrollIndexCallback = _ref.updateScrollIndexCallback, cellCount = cellSizeAndPositionManager.getCellCount(), hasScrollToIndex = scrollToIndex >= 0 && scrollToIndex < cellCount, sizeHasChanged = size !== previousSize || !previousCellSize || "number" == typeof cellSize && cellSize !== previousCellSize; + hasScrollToIndex && (sizeHasChanged || scrollToAlignment !== previousScrollToAlignment || scrollToIndex !== previousScrollToIndex) ? updateScrollIndexCallback(scrollToIndex) : !hasScrollToIndex && cellCount > 0 && (size < previousSize || cellCount < previousCellsCount) && scrollOffset > cellSizeAndPositionManager.getTotalSize() - size && updateScrollIndexCallback(cellCount - 1); + } + Object.defineProperty(exports, "__esModule", { + value: !0 + }), exports.default = updateScrollIndexHelper; + }, /* 127 */ + /***/ + function(module, exports) { + "use strict"; + function defaultCellRangeRenderer(_ref) { + for (var cellCache = _ref.cellCache, cellRenderer = _ref.cellRenderer, columnSizeAndPositionManager = _ref.columnSizeAndPositionManager, columnStartIndex = _ref.columnStartIndex, columnStopIndex = _ref.columnStopIndex, horizontalOffsetAdjustment = _ref.horizontalOffsetAdjustment, isScrolling = _ref.isScrolling, rowSizeAndPositionManager = _ref.rowSizeAndPositionManager, rowStartIndex = _ref.rowStartIndex, rowStopIndex = _ref.rowStopIndex, verticalOffsetAdjustment = (_ref.scrollLeft, + _ref.scrollTop, _ref.verticalOffsetAdjustment), visibleColumnIndices = _ref.visibleColumnIndices, visibleRowIndices = _ref.visibleRowIndices, renderedCells = [], rowIndex = rowStartIndex; rowIndex <= rowStopIndex; rowIndex++) for (var rowDatum = rowSizeAndPositionManager.getSizeAndPositionOfCell(rowIndex), columnIndex = columnStartIndex; columnIndex <= columnStopIndex; columnIndex++) { + var columnDatum = columnSizeAndPositionManager.getSizeAndPositionOfCell(columnIndex), isVisible = columnIndex >= visibleColumnIndices.start && columnIndex <= visibleColumnIndices.stop && rowIndex >= visibleRowIndices.start && rowIndex <= visibleRowIndices.stop, key = rowIndex + "-" + columnIndex, style = { + height: rowDatum.size, + left: columnDatum.offset + horizontalOffsetAdjustment, + position: "absolute", + top: rowDatum.offset + verticalOffsetAdjustment, + width: columnDatum.size + }, cellRendererParams = { + columnIndex: columnIndex, + isScrolling: isScrolling, + isVisible: isVisible, + key: key, + rowIndex: rowIndex, + style: style + }, renderedCell = void 0; + !isScrolling || horizontalOffsetAdjustment || verticalOffsetAdjustment ? renderedCell = cellRenderer(cellRendererParams) : (cellCache[key] || (cellCache[key] = cellRenderer(cellRendererParams)), + renderedCell = cellCache[key]), null != renderedCell && renderedCell !== !1 && renderedCells.push(renderedCell); + } + return renderedCells; + } + Object.defineProperty(exports, "__esModule", { + value: !0 + }), exports.default = defaultCellRangeRenderer; + }, /* 128 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + Object.defineProperty(exports, "__esModule", { + value: !0 + }), exports.SortIndicator = exports.SortDirection = exports.Column = exports.Table = exports.defaultRowRenderer = exports.defaultHeaderRenderer = exports.defaultCellRenderer = exports.defaultCellDataGetter = exports.default = void 0; + var _Table2 = __webpack_require__(129), _Table3 = _interopRequireDefault(_Table2), _defaultCellDataGetter2 = __webpack_require__(135), _defaultCellDataGetter3 = _interopRequireDefault(_defaultCellDataGetter2), _defaultCellRenderer2 = __webpack_require__(134), _defaultCellRenderer3 = _interopRequireDefault(_defaultCellRenderer2), _defaultHeaderRenderer2 = __webpack_require__(131), _defaultHeaderRenderer3 = _interopRequireDefault(_defaultHeaderRenderer2), _defaultRowRenderer2 = __webpack_require__(136), _defaultRowRenderer3 = _interopRequireDefault(_defaultRowRenderer2), _Column2 = __webpack_require__(130), _Column3 = _interopRequireDefault(_Column2), _SortDirection2 = __webpack_require__(133), _SortDirection3 = _interopRequireDefault(_SortDirection2), _SortIndicator2 = __webpack_require__(132), _SortIndicator3 = _interopRequireDefault(_SortIndicator2); + exports.default = _Table3.default, exports.defaultCellDataGetter = _defaultCellDataGetter3.default, + exports.defaultCellRenderer = _defaultCellRenderer3.default, exports.defaultHeaderRenderer = _defaultHeaderRenderer3.default, + exports.defaultRowRenderer = _defaultRowRenderer3.default, exports.Table = _Table3.default, + exports.Column = _Column3.default, exports.SortDirection = _SortDirection3.default, + exports.SortIndicator = _SortIndicator3.default; + }, /* 129 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + Object.defineProperty(exports, "__esModule", { + value: !0 + }); + var _extends2 = __webpack_require__(100), _extends3 = _interopRequireDefault(_extends2), _getPrototypeOf = __webpack_require__(3), _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf), _classCallCheck2 = __webpack_require__(29), _classCallCheck3 = _interopRequireDefault(_classCallCheck2), _createClass2 = __webpack_require__(30), _createClass3 = _interopRequireDefault(_createClass2), _possibleConstructorReturn2 = __webpack_require__(34), _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2), _inherits2 = __webpack_require__(81), _inherits3 = _interopRequireDefault(_inherits2), _classnames = __webpack_require__(107), _classnames2 = _interopRequireDefault(_classnames), _Column = __webpack_require__(130), _react = (_interopRequireDefault(_Column), + __webpack_require__(89)), _react2 = _interopRequireDefault(_react), _reactDom = __webpack_require__(96), _reactAddonsShallowCompare = __webpack_require__(90), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), _Grid = __webpack_require__(120), _Grid2 = _interopRequireDefault(_Grid), _defaultRowRenderer = __webpack_require__(136), _defaultRowRenderer2 = _interopRequireDefault(_defaultRowRenderer), _SortDirection = __webpack_require__(133), _SortDirection2 = _interopRequireDefault(_SortDirection), Table = function(_Component) { + function Table(props) { + (0, _classCallCheck3.default)(this, Table); + var _this = (0, _possibleConstructorReturn3.default)(this, (Table.__proto__ || (0, + _getPrototypeOf2.default)(Table)).call(this, props)); + return _this.state = { + scrollbarWidth: 0 + }, _this._createColumn = _this._createColumn.bind(_this), _this._createRow = _this._createRow.bind(_this), + _this._onScroll = _this._onScroll.bind(_this), _this._onSectionRendered = _this._onSectionRendered.bind(_this), + _this; + } + return (0, _inherits3.default)(Table, _Component), (0, _createClass3.default)(Table, [ { + key: "forceUpdateGrid", + value: function() { + this.Grid.forceUpdate(); + } + }, { + key: "measureAllRows", + value: function() { + this.Grid.measureAllCells(); + } + }, { + key: "recomputeRowHeights", + value: function() { + var index = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : 0; + this.Grid.recomputeGridSize({ + rowIndex: index + }), this.forceUpdateGrid(); + } + }, { + key: "componentDidMount", + value: function() { + this._setScrollbarWidth(); + } + }, { + key: "componentDidUpdate", + value: function() { + this._setScrollbarWidth(); + } + }, { + key: "render", + value: function() { + var _this2 = this, _props = this.props, children = _props.children, className = _props.className, disableHeader = _props.disableHeader, gridClassName = _props.gridClassName, gridStyle = _props.gridStyle, headerHeight = _props.headerHeight, height = _props.height, id = _props.id, noRowsRenderer = _props.noRowsRenderer, rowClassName = _props.rowClassName, rowStyle = _props.rowStyle, scrollToIndex = _props.scrollToIndex, style = _props.style, width = _props.width, scrollbarWidth = this.state.scrollbarWidth, availableRowsHeight = height - headerHeight, rowClass = rowClassName instanceof Function ? rowClassName({ + index: -1 + }) : rowClassName, rowStyleObject = rowStyle instanceof Function ? rowStyle({ + index: -1 + }) : rowStyle; + return this._cachedColumnStyles = [], _react2.default.Children.toArray(children).forEach(function(column, index) { + var flexStyles = _this2._getFlexStyleForColumn(column, column.props.style); + _this2._cachedColumnStyles[index] = (0, _extends3.default)({}, flexStyles, { + overflow: "hidden" + }); + }), _react2.default.createElement("div", { + className: (0, _classnames2.default)("ReactVirtualized__Table", className), + id: id, + style: style + }, !disableHeader && _react2.default.createElement("div", { + className: (0, _classnames2.default)("ReactVirtualized__Table__headerRow", rowClass), + style: (0, _extends3.default)({}, rowStyleObject, { + height: headerHeight, + overflow: "hidden", + paddingRight: scrollbarWidth, + width: width + }) + }, this._getRenderedHeaderRow()), _react2.default.createElement(_Grid2.default, (0, + _extends3.default)({}, this.props, { + autoContainerWidth: !0, + className: (0, _classnames2.default)("ReactVirtualized__Table__Grid", gridClassName), + cellRenderer: this._createRow, + columnWidth: width, + columnCount: 1, + height: availableRowsHeight, + id: void 0, + noContentRenderer: noRowsRenderer, + onScroll: this._onScroll, + onSectionRendered: this._onSectionRendered, + ref: function(_ref) { + _this2.Grid = _ref; + }, + scrollbarWidth: scrollbarWidth, + scrollToRow: scrollToIndex, + style: (0, _extends3.default)({}, gridStyle, { + overflowX: "hidden" + }) + }))); + } + }, { + key: "shouldComponentUpdate", + value: function(nextProps, nextState) { + return (0, _reactAddonsShallowCompare2.default)(this, nextProps, nextState); + } + }, { + key: "_createColumn", + value: function(_ref2) { + var column = _ref2.column, columnIndex = _ref2.columnIndex, isScrolling = _ref2.isScrolling, rowData = _ref2.rowData, rowIndex = _ref2.rowIndex, _column$props = column.props, cellDataGetter = _column$props.cellDataGetter, cellRenderer = _column$props.cellRenderer, className = _column$props.className, columnData = _column$props.columnData, dataKey = _column$props.dataKey, cellData = cellDataGetter({ + columnData: columnData, + dataKey: dataKey, + rowData: rowData + }), renderedCell = cellRenderer({ + cellData: cellData, + columnData: columnData, + dataKey: dataKey, + isScrolling: isScrolling, + rowData: rowData, + rowIndex: rowIndex + }), style = this._cachedColumnStyles[columnIndex], title = "string" == typeof renderedCell ? renderedCell : null; + return _react2.default.createElement("div", { + key: "Row" + rowIndex + "-Col" + columnIndex, + className: (0, _classnames2.default)("ReactVirtualized__Table__rowColumn", className), + style: style, + title: title + }, renderedCell); + } + }, { + key: "_createHeader", + value: function(_ref3) { + var column = _ref3.column, index = _ref3.index, _props2 = this.props, headerClassName = _props2.headerClassName, headerStyle = _props2.headerStyle, onHeaderClick = _props2.onHeaderClick, sort = _props2.sort, sortBy = _props2.sortBy, sortDirection = _props2.sortDirection, _column$props2 = column.props, dataKey = _column$props2.dataKey, disableSort = _column$props2.disableSort, headerRenderer = _column$props2.headerRenderer, label = _column$props2.label, columnData = _column$props2.columnData, sortEnabled = !disableSort && sort, classNames = (0, + _classnames2.default)("ReactVirtualized__Table__headerColumn", headerClassName, column.props.headerClassName, { + ReactVirtualized__Table__sortableHeaderColumn: sortEnabled + }), style = this._getFlexStyleForColumn(column, headerStyle), renderedHeader = headerRenderer({ + columnData: columnData, + dataKey: dataKey, + disableSort: disableSort, + label: label, + sortBy: sortBy, + sortDirection: sortDirection + }), a11yProps = {}; + return (sortEnabled || onHeaderClick) && !function() { + var newSortDirection = sortBy !== dataKey || sortDirection === _SortDirection2.default.DESC ? _SortDirection2.default.ASC : _SortDirection2.default.DESC, onClick = function() { + sortEnabled && sort({ + sortBy: dataKey, + sortDirection: newSortDirection + }), onHeaderClick && onHeaderClick({ + columnData: columnData, + dataKey: dataKey + }); + }, onKeyDown = function(event) { + "Enter" !== event.key && " " !== event.key || onClick(); + }; + a11yProps["aria-label"] = column.props["aria-label"] || label || dataKey, a11yProps.role = "rowheader", + a11yProps.tabIndex = 0, a11yProps.onClick = onClick, a11yProps.onKeyDown = onKeyDown; + }(), _react2.default.createElement("div", (0, _extends3.default)({}, a11yProps, { + key: "Header-Col" + index, + className: classNames, + style: style + }), renderedHeader); + } + }, { + key: "_createRow", + value: function(_ref4) { + var _this3 = this, index = _ref4.rowIndex, isScrolling = _ref4.isScrolling, key = _ref4.key, style = _ref4.style, _props3 = this.props, children = _props3.children, onRowClick = _props3.onRowClick, onRowDoubleClick = _props3.onRowDoubleClick, onRowMouseOver = _props3.onRowMouseOver, onRowMouseOut = _props3.onRowMouseOut, rowClassName = _props3.rowClassName, rowGetter = _props3.rowGetter, rowRenderer = _props3.rowRenderer, rowStyle = _props3.rowStyle, scrollbarWidth = this.state.scrollbarWidth, rowClass = rowClassName instanceof Function ? rowClassName({ + index: index + }) : rowClassName, rowStyleObject = rowStyle instanceof Function ? rowStyle({ + index: index + }) : rowStyle, rowData = rowGetter({ + index: index + }), columns = _react2.default.Children.toArray(children).map(function(column, columnIndex) { + return _this3._createColumn({ + column: column, + columnIndex: columnIndex, + isScrolling: isScrolling, + rowData: rowData, + rowIndex: index, + scrollbarWidth: scrollbarWidth + }); + }), className = (0, _classnames2.default)("ReactVirtualized__Table__row", rowClass), flattenedStyle = (0, + _extends3.default)({}, style, rowStyleObject, { + height: this._getRowHeight(index), + overflow: "hidden", + paddingRight: scrollbarWidth + }); + return rowRenderer({ + className: className, + columns: columns, + index: index, + isScrolling: isScrolling, + key: key, + onRowClick: onRowClick, + onRowDoubleClick: onRowDoubleClick, + onRowMouseOver: onRowMouseOver, + onRowMouseOut: onRowMouseOut, + rowData: rowData, + style: flattenedStyle + }); + } + }, { + key: "_getFlexStyleForColumn", + value: function(column) { + var customStyle = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {}, flexValue = column.props.flexGrow + " " + column.props.flexShrink + " " + column.props.width + "px", style = (0, + _extends3.default)({}, customStyle, { + flex: flexValue, + msFlex: flexValue, + WebkitFlex: flexValue + }); + return column.props.maxWidth && (style.maxWidth = column.props.maxWidth), column.props.minWidth && (style.minWidth = column.props.minWidth), + style; + } + }, { + key: "_getRenderedHeaderRow", + value: function() { + var _this4 = this, _props4 = this.props, children = _props4.children, disableHeader = _props4.disableHeader, items = disableHeader ? [] : _react2.default.Children.toArray(children); + return items.map(function(column, index) { + return _this4._createHeader({ + column: column, + index: index + }); + }); + } + }, { + key: "_getRowHeight", + value: function(rowIndex) { + var rowHeight = this.props.rowHeight; + return rowHeight instanceof Function ? rowHeight({ + index: rowIndex + }) : rowHeight; + } + }, { + key: "_onScroll", + value: function(_ref5) { + var clientHeight = _ref5.clientHeight, scrollHeight = _ref5.scrollHeight, scrollTop = _ref5.scrollTop, onScroll = this.props.onScroll; + onScroll({ + clientHeight: clientHeight, + scrollHeight: scrollHeight, + scrollTop: scrollTop + }); + } + }, { + key: "_onSectionRendered", + value: function(_ref6) { + var rowOverscanStartIndex = _ref6.rowOverscanStartIndex, rowOverscanStopIndex = _ref6.rowOverscanStopIndex, rowStartIndex = _ref6.rowStartIndex, rowStopIndex = _ref6.rowStopIndex, onRowsRendered = this.props.onRowsRendered; + onRowsRendered({ + overscanStartIndex: rowOverscanStartIndex, + overscanStopIndex: rowOverscanStopIndex, + startIndex: rowStartIndex, + stopIndex: rowStopIndex + }); + } + }, { + key: "_setScrollbarWidth", + value: function() { + var Grid = (0, _reactDom.findDOMNode)(this.Grid), clientWidth = Grid.clientWidth || 0, offsetWidth = Grid.offsetWidth || 0, scrollbarWidth = offsetWidth - clientWidth; + this.setState({ + scrollbarWidth: scrollbarWidth + }); + } + } ]), Table; + }(_react.Component); + Table.defaultProps = { + disableHeader: !1, + estimatedRowSize: 30, + headerHeight: 0, + headerStyle: {}, + noRowsRenderer: function() { + return null; + }, + onRowsRendered: function() { + return null; + }, + onScroll: function() { + return null; + }, + overscanRowCount: 10, + rowRenderer: _defaultRowRenderer2.default, + rowStyle: {}, + scrollToAlignment: "auto", + style: {} + }, exports.default = Table; + }, /* 130 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + Object.defineProperty(exports, "__esModule", { + value: !0 + }); + var _getPrototypeOf = __webpack_require__(3), _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf), _classCallCheck2 = __webpack_require__(29), _classCallCheck3 = _interopRequireDefault(_classCallCheck2), _possibleConstructorReturn2 = __webpack_require__(34), _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2), _inherits2 = __webpack_require__(81), _inherits3 = _interopRequireDefault(_inherits2), _react = __webpack_require__(89), _defaultHeaderRenderer = __webpack_require__(131), _defaultHeaderRenderer2 = _interopRequireDefault(_defaultHeaderRenderer), _defaultCellRenderer = __webpack_require__(134), _defaultCellRenderer2 = _interopRequireDefault(_defaultCellRenderer), _defaultCellDataGetter = __webpack_require__(135), _defaultCellDataGetter2 = _interopRequireDefault(_defaultCellDataGetter), Column = function(_Component) { + function Column() { + return (0, _classCallCheck3.default)(this, Column), (0, _possibleConstructorReturn3.default)(this, (Column.__proto__ || (0, + _getPrototypeOf2.default)(Column)).apply(this, arguments)); + } + return (0, _inherits3.default)(Column, _Component), Column; + }(_react.Component); + Column.defaultProps = { + cellDataGetter: _defaultCellDataGetter2.default, + cellRenderer: _defaultCellRenderer2.default, + flexGrow: 0, + flexShrink: 1, + headerRenderer: _defaultHeaderRenderer2.default, + style: {} + }, exports.default = Column; + }, /* 131 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + function defaultHeaderRenderer(_ref) { + var dataKey = (_ref.columnData, _ref.dataKey), label = (_ref.disableSort, _ref.label), sortBy = _ref.sortBy, sortDirection = _ref.sortDirection, showSortIndicator = sortBy === dataKey, children = [ _react2.default.createElement("span", { + className: "ReactVirtualized__Table__headerTruncatedText", + key: "label", + title: label + }, label) ]; + return showSortIndicator && children.push(_react2.default.createElement(_SortIndicator2.default, { + key: "SortIndicator", + sortDirection: sortDirection + })), children; + } + Object.defineProperty(exports, "__esModule", { + value: !0 + }), exports.default = defaultHeaderRenderer; + var _react = __webpack_require__(89), _react2 = _interopRequireDefault(_react), _SortIndicator = __webpack_require__(132), _SortIndicator2 = _interopRequireDefault(_SortIndicator); + }, /* 132 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + function SortIndicator(_ref) { + var sortDirection = _ref.sortDirection, classNames = (0, _classnames2.default)("ReactVirtualized__Table__sortableHeaderIcon", { + "ReactVirtualized__Table__sortableHeaderIcon--ASC": sortDirection === _SortDirection2.default.ASC, + "ReactVirtualized__Table__sortableHeaderIcon--DESC": sortDirection === _SortDirection2.default.DESC + }); + return _react2.default.createElement("svg", { + className: classNames, + width: 18, + height: 18, + viewBox: "0 0 24 24" + }, sortDirection === _SortDirection2.default.ASC ? _react2.default.createElement("path", { + d: "M7 14l5-5 5 5z" + }) : _react2.default.createElement("path", { + d: "M7 10l5 5 5-5z" + }), _react2.default.createElement("path", { + d: "M0 0h24v24H0z", + fill: "none" + })); + } + Object.defineProperty(exports, "__esModule", { + value: !0 + }), exports.default = SortIndicator; + var _react = __webpack_require__(89), _react2 = _interopRequireDefault(_react), _classnames = __webpack_require__(107), _classnames2 = _interopRequireDefault(_classnames), _SortDirection = __webpack_require__(133), _SortDirection2 = _interopRequireDefault(_SortDirection); + }, /* 133 */ + /***/ + function(module, exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { + value: !0 + }); + var SortDirection = { + ASC: "ASC", + DESC: "DESC" + }; + exports.default = SortDirection; + }, /* 134 */ + /***/ + function(module, exports) { + "use strict"; + function defaultCellRenderer(_ref) { + var cellData = _ref.cellData; + _ref.cellDataKey, _ref.columnData, _ref.rowData, _ref.rowIndex; + return null == cellData ? "" : String(cellData); + } + Object.defineProperty(exports, "__esModule", { + value: !0 + }), exports.default = defaultCellRenderer; + }, /* 135 */ + /***/ + function(module, exports) { + "use strict"; + function defaultCellDataGetter(_ref) { + var dataKey = (_ref.columnData, _ref.dataKey), rowData = _ref.rowData; + return rowData.get instanceof Function ? rowData.get(dataKey) : rowData[dataKey]; + } + Object.defineProperty(exports, "__esModule", { + value: !0 + }), exports.default = defaultCellDataGetter; + }, /* 136 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + function defaultRowRenderer(_ref) { + var className = _ref.className, columns = _ref.columns, index = _ref.index, key = (_ref.isScrolling, + _ref.key), onRowClick = _ref.onRowClick, onRowDoubleClick = _ref.onRowDoubleClick, onRowMouseOver = _ref.onRowMouseOver, onRowMouseOut = _ref.onRowMouseOut, style = (_ref.rowData, + _ref.style), a11yProps = {}; + return (onRowClick || onRowDoubleClick || onRowMouseOver || onRowMouseOut) && (a11yProps["aria-label"] = "row", + a11yProps.role = "row", a11yProps.tabIndex = 0, onRowClick && (a11yProps.onClick = function() { + return onRowClick({ + index: index + }); + }), onRowDoubleClick && (a11yProps.onDoubleClick = function() { + return onRowDoubleClick({ + index: index + }); + }), onRowMouseOut && (a11yProps.onMouseOut = function() { + return onRowMouseOut({ + index: index + }); + }), onRowMouseOver && (a11yProps.onMouseOver = function() { + return onRowMouseOver({ + index: index + }); + })), _react2.default.createElement("div", (0, _extends3.default)({}, a11yProps, { + className: className, + key: key, + style: style + }), columns); + } + Object.defineProperty(exports, "__esModule", { + value: !0 + }); + var _extends2 = __webpack_require__(100), _extends3 = _interopRequireDefault(_extends2); + exports.default = defaultRowRenderer; + var _react = __webpack_require__(89), _react2 = _interopRequireDefault(_react); + }, /* 137 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + Object.defineProperty(exports, "__esModule", { + value: !0 + }), exports.InfiniteLoader = exports.default = void 0; + var _InfiniteLoader2 = __webpack_require__(138), _InfiniteLoader3 = _interopRequireDefault(_InfiniteLoader2); + exports.default = _InfiniteLoader3.default, exports.InfiniteLoader = _InfiniteLoader3.default; + }, /* 138 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + function isRangeVisible(_ref2) { + var lastRenderedStartIndex = _ref2.lastRenderedStartIndex, lastRenderedStopIndex = _ref2.lastRenderedStopIndex, startIndex = _ref2.startIndex, stopIndex = _ref2.stopIndex; + return !(startIndex > lastRenderedStopIndex || stopIndex < lastRenderedStartIndex); + } + function scanForUnloadedRanges(_ref3) { + for (var isRowLoaded = _ref3.isRowLoaded, minimumBatchSize = _ref3.minimumBatchSize, rowCount = _ref3.rowCount, startIndex = _ref3.startIndex, stopIndex = _ref3.stopIndex, unloadedRanges = [], rangeStartIndex = null, rangeStopIndex = null, index = startIndex; index <= stopIndex; index++) { + var loaded = isRowLoaded({ + index: index + }); + loaded ? null !== rangeStopIndex && (unloadedRanges.push({ + startIndex: rangeStartIndex, + stopIndex: rangeStopIndex + }), rangeStartIndex = rangeStopIndex = null) : (rangeStopIndex = index, null === rangeStartIndex && (rangeStartIndex = index)); + } + if (null !== rangeStopIndex) { + for (var potentialStopIndex = Math.min(Math.max(rangeStopIndex, rangeStartIndex + minimumBatchSize - 1), rowCount - 1), _index = rangeStopIndex + 1; _index <= potentialStopIndex && !isRowLoaded({ + index: _index + }); _index++) rangeStopIndex = _index; + unloadedRanges.push({ + startIndex: rangeStartIndex, + stopIndex: rangeStopIndex + }); + } + if (unloadedRanges.length) for (var firstUnloadedRange = unloadedRanges[0]; firstUnloadedRange.stopIndex - firstUnloadedRange.startIndex + 1 < minimumBatchSize && firstUnloadedRange.startIndex > 0; ) { + var _index2 = firstUnloadedRange.startIndex - 1; + if (isRowLoaded({ + index: _index2 + })) break; + firstUnloadedRange.startIndex = _index2; + } + return unloadedRanges; + } + function forceUpdateReactVirtualizedComponent(component) { + "function" == typeof component.forceUpdateGrid ? component.forceUpdateGrid() : component.forceUpdate(); + } + Object.defineProperty(exports, "__esModule", { + value: !0 + }); + var _getPrototypeOf = __webpack_require__(3), _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf), _classCallCheck2 = __webpack_require__(29), _classCallCheck3 = _interopRequireDefault(_classCallCheck2), _createClass2 = __webpack_require__(30), _createClass3 = _interopRequireDefault(_createClass2), _possibleConstructorReturn2 = __webpack_require__(34), _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2), _inherits2 = __webpack_require__(81), _inherits3 = _interopRequireDefault(_inherits2); + exports.isRangeVisible = isRangeVisible, exports.scanForUnloadedRanges = scanForUnloadedRanges, + exports.forceUpdateReactVirtualizedComponent = forceUpdateReactVirtualizedComponent; + var _react = __webpack_require__(89), _reactAddonsShallowCompare = __webpack_require__(90), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), _createCallbackMemoizer = __webpack_require__(108), _createCallbackMemoizer2 = _interopRequireDefault(_createCallbackMemoizer), InfiniteLoader = function(_Component) { + function InfiniteLoader(props, context) { + (0, _classCallCheck3.default)(this, InfiniteLoader); + var _this = (0, _possibleConstructorReturn3.default)(this, (InfiniteLoader.__proto__ || (0, + _getPrototypeOf2.default)(InfiniteLoader)).call(this, props, context)); + return _this._loadMoreRowsMemoizer = (0, _createCallbackMemoizer2.default)(), _this._onRowsRendered = _this._onRowsRendered.bind(_this), + _this._registerChild = _this._registerChild.bind(_this), _this; + } + return (0, _inherits3.default)(InfiniteLoader, _Component), (0, _createClass3.default)(InfiniteLoader, [ { + key: "render", + value: function() { + var children = this.props.children; + return children({ + onRowsRendered: this._onRowsRendered, + registerChild: this._registerChild + }); + } + }, { + key: "shouldComponentUpdate", + value: function(nextProps, nextState) { + return (0, _reactAddonsShallowCompare2.default)(this, nextProps, nextState); + } + }, { + key: "_loadUnloadedRanges", + value: function(unloadedRanges) { + var _this2 = this, loadMoreRows = this.props.loadMoreRows; + unloadedRanges.forEach(function(unloadedRange) { + var promise = loadMoreRows(unloadedRange); + promise && promise.then(function() { + isRangeVisible({ + lastRenderedStartIndex: _this2._lastRenderedStartIndex, + lastRenderedStopIndex: _this2._lastRenderedStopIndex, + startIndex: unloadedRange.startIndex, + stopIndex: unloadedRange.stopIndex + }) && _this2._registeredChild && forceUpdateReactVirtualizedComponent(_this2._registeredChild); + }); + }); + } + }, { + key: "_onRowsRendered", + value: function(_ref) { + var _this3 = this, startIndex = _ref.startIndex, stopIndex = _ref.stopIndex, _props = this.props, isRowLoaded = _props.isRowLoaded, minimumBatchSize = _props.minimumBatchSize, rowCount = _props.rowCount, threshold = _props.threshold; + this._lastRenderedStartIndex = startIndex, this._lastRenderedStopIndex = stopIndex; + var unloadedRanges = scanForUnloadedRanges({ + isRowLoaded: isRowLoaded, + minimumBatchSize: minimumBatchSize, + rowCount: rowCount, + startIndex: Math.max(0, startIndex - threshold), + stopIndex: Math.min(rowCount - 1, stopIndex + threshold) + }), squashedUnloadedRanges = unloadedRanges.reduce(function(reduced, unloadedRange) { + return reduced.concat([ unloadedRange.startIndex, unloadedRange.stopIndex ]); + }, []); + this._loadMoreRowsMemoizer({ + callback: function() { + _this3._loadUnloadedRanges(unloadedRanges); + }, + indices: { + squashedUnloadedRanges: squashedUnloadedRanges + } + }); + } + }, { + key: "_registerChild", + value: function(registeredChild) { + this._registeredChild = registeredChild; + } + } ]), InfiniteLoader; + }(_react.Component); + InfiniteLoader.defaultProps = { + minimumBatchSize: 10, + rowCount: 0, + threshold: 15 + }, exports.default = InfiniteLoader; + }, /* 139 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + Object.defineProperty(exports, "__esModule", { + value: !0 + }), exports.ScrollSync = exports.default = void 0; + var _ScrollSync2 = __webpack_require__(140), _ScrollSync3 = _interopRequireDefault(_ScrollSync2); + exports.default = _ScrollSync3.default, exports.ScrollSync = _ScrollSync3.default; + }, /* 140 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + Object.defineProperty(exports, "__esModule", { + value: !0 + }); + var _getPrototypeOf = __webpack_require__(3), _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf), _classCallCheck2 = __webpack_require__(29), _classCallCheck3 = _interopRequireDefault(_classCallCheck2), _createClass2 = __webpack_require__(30), _createClass3 = _interopRequireDefault(_createClass2), _possibleConstructorReturn2 = __webpack_require__(34), _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2), _inherits2 = __webpack_require__(81), _inherits3 = _interopRequireDefault(_inherits2), _react = __webpack_require__(89), _reactAddonsShallowCompare = __webpack_require__(90), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), ScrollSync = function(_Component) { + function ScrollSync(props, context) { + (0, _classCallCheck3.default)(this, ScrollSync); + var _this = (0, _possibleConstructorReturn3.default)(this, (ScrollSync.__proto__ || (0, + _getPrototypeOf2.default)(ScrollSync)).call(this, props, context)); + return _this.state = { + clientHeight: 0, + clientWidth: 0, + scrollHeight: 0, + scrollLeft: 0, + scrollTop: 0, + scrollWidth: 0 + }, _this._onScroll = _this._onScroll.bind(_this), _this; + } + return (0, _inherits3.default)(ScrollSync, _Component), (0, _createClass3.default)(ScrollSync, [ { + key: "render", + value: function() { + var children = this.props.children, _state = this.state, clientHeight = _state.clientHeight, clientWidth = _state.clientWidth, scrollHeight = _state.scrollHeight, scrollLeft = _state.scrollLeft, scrollTop = _state.scrollTop, scrollWidth = _state.scrollWidth; + return children({ + clientHeight: clientHeight, + clientWidth: clientWidth, + onScroll: this._onScroll, + scrollHeight: scrollHeight, + scrollLeft: scrollLeft, + scrollTop: scrollTop, + scrollWidth: scrollWidth + }); + } + }, { + key: "shouldComponentUpdate", + value: function(nextProps, nextState) { + return (0, _reactAddonsShallowCompare2.default)(this, nextProps, nextState); + } + }, { + key: "_onScroll", + value: function(_ref) { + var clientHeight = _ref.clientHeight, clientWidth = _ref.clientWidth, scrollHeight = _ref.scrollHeight, scrollLeft = _ref.scrollLeft, scrollTop = _ref.scrollTop, scrollWidth = _ref.scrollWidth; + this.setState({ + clientHeight: clientHeight, + clientWidth: clientWidth, + scrollHeight: scrollHeight, + scrollLeft: scrollLeft, + scrollTop: scrollTop, + scrollWidth: scrollWidth + }); + } + } ]), ScrollSync; + }(_react.Component); + exports.default = ScrollSync; + }, /* 141 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + Object.defineProperty(exports, "__esModule", { + value: !0 + }), exports.List = exports.default = void 0; + var _List2 = __webpack_require__(142), _List3 = _interopRequireDefault(_List2); + exports.default = _List3.default, exports.List = _List3.default; + }, /* 142 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + Object.defineProperty(exports, "__esModule", { + value: !0 + }); + var _objectWithoutProperties2 = __webpack_require__(105), _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2), _extends2 = __webpack_require__(100), _extends3 = _interopRequireDefault(_extends2), _getPrototypeOf = __webpack_require__(3), _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf), _classCallCheck2 = __webpack_require__(29), _classCallCheck3 = _interopRequireDefault(_classCallCheck2), _createClass2 = __webpack_require__(30), _createClass3 = _interopRequireDefault(_createClass2), _possibleConstructorReturn2 = __webpack_require__(34), _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2), _inherits2 = __webpack_require__(81), _inherits3 = _interopRequireDefault(_inherits2), _Grid = __webpack_require__(120), _Grid2 = _interopRequireDefault(_Grid), _react = __webpack_require__(89), _react2 = _interopRequireDefault(_react), _classnames = __webpack_require__(107), _classnames2 = _interopRequireDefault(_classnames), _reactAddonsShallowCompare = __webpack_require__(90), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), List = function(_Component) { + function List(props, context) { + (0, _classCallCheck3.default)(this, List); + var _this = (0, _possibleConstructorReturn3.default)(this, (List.__proto__ || (0, + _getPrototypeOf2.default)(List)).call(this, props, context)); + return _this._cellRenderer = _this._cellRenderer.bind(_this), _this._onScroll = _this._onScroll.bind(_this), + _this._onSectionRendered = _this._onSectionRendered.bind(_this), _this; + } + return (0, _inherits3.default)(List, _Component), (0, _createClass3.default)(List, [ { + key: "forceUpdateGrid", + value: function() { + this.Grid.forceUpdate(); + } + }, { + key: "measureAllRows", + value: function() { + this.Grid.measureAllCells(); + } + }, { + key: "recomputeRowHeights", + value: function() { + var index = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : 0; + this.Grid.recomputeGridSize({ + rowIndex: index + }), this.forceUpdateGrid(); + } + }, { + key: "render", + value: function() { + var _this2 = this, _props = this.props, className = _props.className, noRowsRenderer = _props.noRowsRenderer, scrollToIndex = _props.scrollToIndex, width = _props.width, classNames = (0, + _classnames2.default)("ReactVirtualized__List", className); + return _react2.default.createElement(_Grid2.default, (0, _extends3.default)({}, this.props, { + autoContainerWidth: !0, + cellRenderer: this._cellRenderer, + className: classNames, + columnWidth: width, + columnCount: 1, + noContentRenderer: noRowsRenderer, + onScroll: this._onScroll, + onSectionRendered: this._onSectionRendered, + ref: function(_ref) { + _this2.Grid = _ref; + }, + scrollToRow: scrollToIndex + })); + } + }, { + key: "shouldComponentUpdate", + value: function(nextProps, nextState) { + return (0, _reactAddonsShallowCompare2.default)(this, nextProps, nextState); + } + }, { + key: "_cellRenderer", + value: function(_ref2) { + var rowIndex = _ref2.rowIndex, style = _ref2.style, rest = (0, _objectWithoutProperties3.default)(_ref2, [ "rowIndex", "style" ]), rowRenderer = this.props.rowRenderer; + return style.width = "100%", rowRenderer((0, _extends3.default)({ + index: rowIndex, + style: style + }, rest)); + } + }, { + key: "_onScroll", + value: function(_ref3) { + var clientHeight = _ref3.clientHeight, scrollHeight = _ref3.scrollHeight, scrollTop = _ref3.scrollTop, onScroll = this.props.onScroll; + onScroll({ + clientHeight: clientHeight, + scrollHeight: scrollHeight, + scrollTop: scrollTop + }); + } + }, { + key: "_onSectionRendered", + value: function(_ref4) { + var rowOverscanStartIndex = _ref4.rowOverscanStartIndex, rowOverscanStopIndex = _ref4.rowOverscanStopIndex, rowStartIndex = _ref4.rowStartIndex, rowStopIndex = _ref4.rowStopIndex, onRowsRendered = this.props.onRowsRendered; + onRowsRendered({ + overscanStartIndex: rowOverscanStartIndex, + overscanStopIndex: rowOverscanStopIndex, + startIndex: rowStartIndex, + stopIndex: rowStopIndex + }); + } + } ]), List; + }(_react.Component); + List.defaultProps = { + estimatedRowSize: 30, + noRowsRenderer: function() { + return null; + }, + onRowsRendered: function() { + return null; + }, + onScroll: function() { + return null; + }, + overscanRowCount: 10, + scrollToAlignment: "auto", + style: {} + }, exports.default = List; + }, /* 143 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + Object.defineProperty(exports, "__esModule", { + value: !0 + }), exports.IS_SCROLLING_TIMEOUT = exports.WindowScroller = exports.default = void 0; + var _onScroll = __webpack_require__(144); + Object.defineProperty(exports, "IS_SCROLLING_TIMEOUT", { + enumerable: !0, + get: function() { + return _onScroll.IS_SCROLLING_TIMEOUT; + } + }); + var _WindowScroller2 = __webpack_require__(145), _WindowScroller3 = _interopRequireDefault(_WindowScroller2); + exports.default = _WindowScroller3.default, exports.WindowScroller = _WindowScroller3.default; + }, /* 144 */ + /***/ + function(module, exports) { + "use strict"; + function enablePointerEventsIfDisabled() { + disablePointerEventsTimeoutId && (disablePointerEventsTimeoutId = null, document.firstElementChild.style.pointerEvents = originalBodyPointerEvents, + originalBodyPointerEvents = null); + } + function enablePointerEventsAfterDelayCallback() { + enablePointerEventsIfDisabled(), mountedInstances.forEach(function(component) { + return component._enablePointerEventsAfterDelayCallback(); + }); + } + function enablePointerEventsAfterDelay() { + disablePointerEventsTimeoutId && clearTimeout(disablePointerEventsTimeoutId), disablePointerEventsTimeoutId = setTimeout(enablePointerEventsAfterDelayCallback, IS_SCROLLING_TIMEOUT); + } + function onScrollWindow(event) { + null == originalBodyPointerEvents && (originalBodyPointerEvents = document.firstElementChild.style.pointerEvents, + document.firstElementChild.style.pointerEvents = "none", enablePointerEventsAfterDelay()), mountedInstances.forEach(function(component) { + return component._onScrollWindow(event); + }); + } + function registerScrollListener(component) { + mountedInstances.length || window.addEventListener("scroll", onScrollWindow), mountedInstances.push(component); + } + function unregisterScrollListener(component) { + mountedInstances = mountedInstances.filter(function(c) { + return c !== component; + }), mountedInstances.length || (window.removeEventListener("scroll", onScrollWindow), + disablePointerEventsTimeoutId && (clearTimeout(disablePointerEventsTimeoutId), enablePointerEventsIfDisabled())); + } + Object.defineProperty(exports, "__esModule", { + value: !0 + }), exports.registerScrollListener = registerScrollListener, exports.unregisterScrollListener = unregisterScrollListener; + var mountedInstances = [], originalBodyPointerEvents = null, disablePointerEventsTimeoutId = null, IS_SCROLLING_TIMEOUT = exports.IS_SCROLLING_TIMEOUT = 150; + }, /* 145 */ + /***/ + function(module, exports, __webpack_require__) { + "use strict"; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + Object.defineProperty(exports, "__esModule", { + value: !0 + }); + var _getPrototypeOf = __webpack_require__(3), _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf), _classCallCheck2 = __webpack_require__(29), _classCallCheck3 = _interopRequireDefault(_classCallCheck2), _createClass2 = __webpack_require__(30), _createClass3 = _interopRequireDefault(_createClass2), _possibleConstructorReturn2 = __webpack_require__(34), _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2), _inherits2 = __webpack_require__(81), _inherits3 = _interopRequireDefault(_inherits2), _react = __webpack_require__(89), _react2 = _interopRequireDefault(_react), _reactDom = __webpack_require__(96), _reactDom2 = _interopRequireDefault(_reactDom), _reactAddonsShallowCompare = __webpack_require__(90), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), _onScroll = __webpack_require__(144), WindowScroller = function(_Component) { + function WindowScroller(props) { + (0, _classCallCheck3.default)(this, WindowScroller); + var _this = (0, _possibleConstructorReturn3.default)(this, (WindowScroller.__proto__ || (0, + _getPrototypeOf2.default)(WindowScroller)).call(this, props)), height = "undefined" != typeof window ? window.innerHeight : 0; + return _this.state = { + isScrolling: !1, + height: height, + scrollTop: 0 + }, _this._onScrollWindow = _this._onScrollWindow.bind(_this), _this._onResizeWindow = _this._onResizeWindow.bind(_this), + _this._enablePointerEventsAfterDelayCallback = _this._enablePointerEventsAfterDelayCallback.bind(_this), + _this; + } + return (0, _inherits3.default)(WindowScroller, _Component), (0, _createClass3.default)(WindowScroller, [ { + key: "componentDidMount", + value: function() { + var height = this.state.height; + this._positionFromTop = _reactDom2.default.findDOMNode(this).getBoundingClientRect().top - document.documentElement.getBoundingClientRect().top, + height !== window.innerHeight && this.setState({ + height: window.innerHeight + }), (0, _onScroll.registerScrollListener)(this), window.addEventListener("resize", this._onResizeWindow, !1); + } + }, { + key: "componentWillUnmount", + value: function() { + (0, _onScroll.unregisterScrollListener)(this), window.removeEventListener("resize", this._onResizeWindow, !1); + } + }, { + key: "render", + value: function() { + var children = this.props.children, _state = this.state, isScrolling = _state.isScrolling, scrollTop = _state.scrollTop, height = _state.height; + return _react2.default.createElement("div", null, children({ + height: height, + isScrolling: isScrolling, + scrollTop: scrollTop + })); + } + }, { + key: "shouldComponentUpdate", + value: function(nextProps, nextState) { + return (0, _reactAddonsShallowCompare2.default)(this, nextProps, nextState); + } + }, { + key: "_enablePointerEventsAfterDelayCallback", + value: function() { + this.setState({ + isScrolling: !1 + }); + } + }, { + key: "_onResizeWindow", + value: function(event) { + var onResize = this.props.onResize, height = window.innerHeight || 0; + this.setState({ + height: height + }), onResize({ + height: height + }); + } + }, { + key: "_onScrollWindow", + value: function(event) { + var onScroll = this.props.onScroll, scrollY = "scrollY" in window ? window.scrollY : document.documentElement.scrollTop, scrollTop = Math.max(0, scrollY - this._positionFromTop); + this.setState({ + isScrolling: !0, + scrollTop: scrollTop + }), onScroll({ + scrollTop: scrollTop + }); + } + } ]), WindowScroller; + }(_react.Component); + WindowScroller.defaultProps = { + onResize: function() {}, + onScroll: function() {} + }, exports.default = WindowScroller; + } ]); +}); +//# sourceMappingURL=react-virtualized.js.map
\ No newline at end of file diff --git a/devtools/client/shared/vendor/react.js b/devtools/client/shared/vendor/react.js new file mode 100644 index 000000000..828dc5f13 --- /dev/null +++ b/devtools/client/shared/vendor/react.js @@ -0,0 +1,20763 @@ + /** + * React (with addons) v0.14.6 + */ +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.React = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactWithAddons + */ + +/** + * This module exists purely in the open source project, and is meant as a way + * to create a separate standalone build of React. This build has "addons", or + * functionality we've built and think might be useful but doesn't have a good + * place to live inside React core. + */ + +'use strict'; + +var LinkedStateMixin = _dereq_(22); +var React = _dereq_(26); +var ReactComponentWithPureRenderMixin = _dereq_(37); +var ReactCSSTransitionGroup = _dereq_(29); +var ReactFragment = _dereq_(64); +var ReactTransitionGroup = _dereq_(94); +var ReactUpdates = _dereq_(96); + +var cloneWithProps = _dereq_(118); +var shallowCompare = _dereq_(140); +var update = _dereq_(143); +var warning = _dereq_(173); + +var warnedAboutBatchedUpdates = false; + +React.addons = { + CSSTransitionGroup: ReactCSSTransitionGroup, + LinkedStateMixin: LinkedStateMixin, + PureRenderMixin: ReactComponentWithPureRenderMixin, + TransitionGroup: ReactTransitionGroup, + + batchedUpdates: function () { + if ("production" !== 'production') { + "production" !== 'production' ? warning(warnedAboutBatchedUpdates, 'React.addons.batchedUpdates is deprecated. Use ' + 'ReactDOM.unstable_batchedUpdates instead.') : undefined; + warnedAboutBatchedUpdates = true; + } + return ReactUpdates.batchedUpdates.apply(this, arguments); + }, + cloneWithProps: cloneWithProps, + createFragment: ReactFragment.create, + shallowCompare: shallowCompare, + update: update +}; + +React.addons.TestUtils = _dereq_(91); + +if ("production" !== 'production') { + React.addons.Perf = _dereq_(55); +} + +module.exports = React; +},{"118":118,"140":140,"143":143,"173":173,"22":22,"26":26,"29":29,"37":37,"55":55,"64":64,"91":91,"94":94,"96":96}],2:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule AutoFocusUtils + * @typechecks static-only + */ + +'use strict'; + +var ReactMount = _dereq_(72); + +var findDOMNode = _dereq_(122); +var focusNode = _dereq_(155); + +var Mixin = { + componentDidMount: function () { + if (this.props.autoFocus) { + focusNode(findDOMNode(this)); + } + } +}; + +var AutoFocusUtils = { + Mixin: Mixin, + + focusDOMComponent: function () { + focusNode(ReactMount.getNode(this._rootNodeID)); + } +}; + +module.exports = AutoFocusUtils; +},{"122":122,"155":155,"72":72}],3:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015 Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule BeforeInputEventPlugin + * @typechecks static-only + */ + +'use strict'; + +var EventConstants = _dereq_(15); +var EventPropagators = _dereq_(19); +var ExecutionEnvironment = _dereq_(147); +var FallbackCompositionState = _dereq_(20); +var SyntheticCompositionEvent = _dereq_(103); +var SyntheticInputEvent = _dereq_(107); + +var keyOf = _dereq_(166); + +var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space +var START_KEYCODE = 229; + +var canUseCompositionEvent = ExecutionEnvironment.canUseDOM && 'CompositionEvent' in window; + +var documentMode = null; +if (ExecutionEnvironment.canUseDOM && 'documentMode' in document) { + documentMode = document.documentMode; +} + +// Webkit offers a very useful `textInput` event that can be used to +// directly represent `beforeInput`. The IE `textinput` event is not as +// useful, so we don't use it. +var canUseTextInputEvent = ExecutionEnvironment.canUseDOM && 'TextEvent' in window && !documentMode && !isPresto(); + +// In IE9+, we have access to composition events, but the data supplied +// by the native compositionend event may be incorrect. Japanese ideographic +// spaces, for instance (\u3000) are not recorded correctly. +var useFallbackCompositionData = ExecutionEnvironment.canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11); + +/** + * Opera <= 12 includes TextEvent in window, but does not fire + * text input events. Rely on keypress instead. + */ +function isPresto() { + var opera = window.opera; + return typeof opera === 'object' && typeof opera.version === 'function' && parseInt(opera.version(), 10) <= 12; +} + +var SPACEBAR_CODE = 32; +var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE); + +var topLevelTypes = EventConstants.topLevelTypes; + +// Events and their corresponding property names. +var eventTypes = { + beforeInput: { + phasedRegistrationNames: { + bubbled: keyOf({ onBeforeInput: null }), + captured: keyOf({ onBeforeInputCapture: null }) + }, + dependencies: [topLevelTypes.topCompositionEnd, topLevelTypes.topKeyPress, topLevelTypes.topTextInput, topLevelTypes.topPaste] + }, + compositionEnd: { + phasedRegistrationNames: { + bubbled: keyOf({ onCompositionEnd: null }), + captured: keyOf({ onCompositionEndCapture: null }) + }, + dependencies: [topLevelTypes.topBlur, topLevelTypes.topCompositionEnd, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown] + }, + compositionStart: { + phasedRegistrationNames: { + bubbled: keyOf({ onCompositionStart: null }), + captured: keyOf({ onCompositionStartCapture: null }) + }, + dependencies: [topLevelTypes.topBlur, topLevelTypes.topCompositionStart, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown] + }, + compositionUpdate: { + phasedRegistrationNames: { + bubbled: keyOf({ onCompositionUpdate: null }), + captured: keyOf({ onCompositionUpdateCapture: null }) + }, + dependencies: [topLevelTypes.topBlur, topLevelTypes.topCompositionUpdate, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown] + } +}; + +// Track whether we've ever handled a keypress on the space key. +var hasSpaceKeypress = false; + +/** + * Return whether a native keypress event is assumed to be a command. + * This is required because Firefox fires `keypress` events for key commands + * (cut, copy, select-all, etc.) even though no character is inserted. + */ +function isKeypressCommand(nativeEvent) { + return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) && + // ctrlKey && altKey is equivalent to AltGr, and is not a command. + !(nativeEvent.ctrlKey && nativeEvent.altKey); +} + +/** + * Translate native top level events into event types. + * + * @param {string} topLevelType + * @return {object} + */ +function getCompositionEventType(topLevelType) { + switch (topLevelType) { + case topLevelTypes.topCompositionStart: + return eventTypes.compositionStart; + case topLevelTypes.topCompositionEnd: + return eventTypes.compositionEnd; + case topLevelTypes.topCompositionUpdate: + return eventTypes.compositionUpdate; + } +} + +/** + * Does our fallback best-guess model think this event signifies that + * composition has begun? + * + * @param {string} topLevelType + * @param {object} nativeEvent + * @return {boolean} + */ +function isFallbackCompositionStart(topLevelType, nativeEvent) { + return topLevelType === topLevelTypes.topKeyDown && nativeEvent.keyCode === START_KEYCODE; +} + +/** + * Does our fallback mode think that this event is the end of composition? + * + * @param {string} topLevelType + * @param {object} nativeEvent + * @return {boolean} + */ +function isFallbackCompositionEnd(topLevelType, nativeEvent) { + switch (topLevelType) { + case topLevelTypes.topKeyUp: + // Command keys insert or clear IME input. + return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1; + case topLevelTypes.topKeyDown: + // Expect IME keyCode on each keydown. If we get any other + // code we must have exited earlier. + return nativeEvent.keyCode !== START_KEYCODE; + case topLevelTypes.topKeyPress: + case topLevelTypes.topMouseDown: + case topLevelTypes.topBlur: + // Events are not possible without cancelling IME. + return true; + default: + return false; + } +} + +/** + * Google Input Tools provides composition data via a CustomEvent, + * with the `data` property populated in the `detail` object. If this + * is available on the event object, use it. If not, this is a plain + * composition event and we have nothing special to extract. + * + * @param {object} nativeEvent + * @return {?string} + */ +function getDataFromCustomEvent(nativeEvent) { + var detail = nativeEvent.detail; + if (typeof detail === 'object' && 'data' in detail) { + return detail.data; + } + return null; +} + +// Track the current IME composition fallback object, if any. +var currentComposition = null; + +/** + * @param {string} topLevelType Record from `EventConstants`. + * @param {DOMEventTarget} topLevelTarget The listening component root node. + * @param {string} topLevelTargetID ID of `topLevelTarget`. + * @param {object} nativeEvent Native browser event. + * @return {?object} A SyntheticCompositionEvent. + */ +function extractCompositionEvent(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) { + var eventType; + var fallbackData; + + if (canUseCompositionEvent) { + eventType = getCompositionEventType(topLevelType); + } else if (!currentComposition) { + if (isFallbackCompositionStart(topLevelType, nativeEvent)) { + eventType = eventTypes.compositionStart; + } + } else if (isFallbackCompositionEnd(topLevelType, nativeEvent)) { + eventType = eventTypes.compositionEnd; + } + + if (!eventType) { + return null; + } + + if (useFallbackCompositionData) { + // The current composition is stored statically and must not be + // overwritten while composition continues. + if (!currentComposition && eventType === eventTypes.compositionStart) { + currentComposition = FallbackCompositionState.getPooled(topLevelTarget); + } else if (eventType === eventTypes.compositionEnd) { + if (currentComposition) { + fallbackData = currentComposition.getData(); + } + } + } + + var event = SyntheticCompositionEvent.getPooled(eventType, topLevelTargetID, nativeEvent, nativeEventTarget); + + if (fallbackData) { + // Inject data generated from fallback path into the synthetic event. + // This matches the property of native CompositionEventInterface. + event.data = fallbackData; + } else { + var customData = getDataFromCustomEvent(nativeEvent); + if (customData !== null) { + event.data = customData; + } + } + + EventPropagators.accumulateTwoPhaseDispatches(event); + return event; +} + +/** + * @param {string} topLevelType Record from `EventConstants`. + * @param {object} nativeEvent Native browser event. + * @return {?string} The string corresponding to this `beforeInput` event. + */ +function getNativeBeforeInputChars(topLevelType, nativeEvent) { + switch (topLevelType) { + case topLevelTypes.topCompositionEnd: + return getDataFromCustomEvent(nativeEvent); + case topLevelTypes.topKeyPress: + /** + * If native `textInput` events are available, our goal is to make + * use of them. However, there is a special case: the spacebar key. + * In Webkit, preventing default on a spacebar `textInput` event + * cancels character insertion, but it *also* causes the browser + * to fall back to its default spacebar behavior of scrolling the + * page. + * + * Tracking at: + * https://code.google.com/p/chromium/issues/detail?id=355103 + * + * To avoid this issue, use the keypress event as if no `textInput` + * event is available. + */ + var which = nativeEvent.which; + if (which !== SPACEBAR_CODE) { + return null; + } + + hasSpaceKeypress = true; + return SPACEBAR_CHAR; + + case topLevelTypes.topTextInput: + // Record the characters to be added to the DOM. + var chars = nativeEvent.data; + + // If it's a spacebar character, assume that we have already handled + // it at the keypress level and bail immediately. Android Chrome + // doesn't give us keycodes, so we need to blacklist it. + if (chars === SPACEBAR_CHAR && hasSpaceKeypress) { + return null; + } + + return chars; + + default: + // For other native event types, do nothing. + return null; + } +} + +/** + * For browsers that do not provide the `textInput` event, extract the + * appropriate string to use for SyntheticInputEvent. + * + * @param {string} topLevelType Record from `EventConstants`. + * @param {object} nativeEvent Native browser event. + * @return {?string} The fallback string for this `beforeInput` event. + */ +function getFallbackBeforeInputChars(topLevelType, nativeEvent) { + // If we are currently composing (IME) and using a fallback to do so, + // try to extract the composed characters from the fallback object. + if (currentComposition) { + if (topLevelType === topLevelTypes.topCompositionEnd || isFallbackCompositionEnd(topLevelType, nativeEvent)) { + var chars = currentComposition.getData(); + FallbackCompositionState.release(currentComposition); + currentComposition = null; + return chars; + } + return null; + } + + switch (topLevelType) { + case topLevelTypes.topPaste: + // If a paste event occurs after a keypress, throw out the input + // chars. Paste events should not lead to BeforeInput events. + return null; + case topLevelTypes.topKeyPress: + /** + * As of v27, Firefox may fire keypress events even when no character + * will be inserted. A few possibilities: + * + * - `which` is `0`. Arrow keys, Esc key, etc. + * + * - `which` is the pressed key code, but no char is available. + * Ex: 'AltGr + d` in Polish. There is no modified character for + * this key combination and no character is inserted into the + * document, but FF fires the keypress for char code `100` anyway. + * No `input` event will occur. + * + * - `which` is the pressed key code, but a command combination is + * being used. Ex: `Cmd+C`. No character is inserted, and no + * `input` event will occur. + */ + if (nativeEvent.which && !isKeypressCommand(nativeEvent)) { + return String.fromCharCode(nativeEvent.which); + } + return null; + case topLevelTypes.topCompositionEnd: + return useFallbackCompositionData ? null : nativeEvent.data; + default: + return null; + } +} + +/** + * Extract a SyntheticInputEvent for `beforeInput`, based on either native + * `textInput` or fallback behavior. + * + * @param {string} topLevelType Record from `EventConstants`. + * @param {DOMEventTarget} topLevelTarget The listening component root node. + * @param {string} topLevelTargetID ID of `topLevelTarget`. + * @param {object} nativeEvent Native browser event. + * @return {?object} A SyntheticInputEvent. + */ +function extractBeforeInputEvent(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) { + var chars; + + if (canUseTextInputEvent) { + chars = getNativeBeforeInputChars(topLevelType, nativeEvent); + } else { + chars = getFallbackBeforeInputChars(topLevelType, nativeEvent); + } + + // If no characters are being inserted, no BeforeInput event should + // be fired. + if (!chars) { + return null; + } + + var event = SyntheticInputEvent.getPooled(eventTypes.beforeInput, topLevelTargetID, nativeEvent, nativeEventTarget); + + event.data = chars; + EventPropagators.accumulateTwoPhaseDispatches(event); + return event; +} + +/** + * Create an `onBeforeInput` event to match + * http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents. + * + * This event plugin is based on the native `textInput` event + * available in Chrome, Safari, Opera, and IE. This event fires after + * `onKeyPress` and `onCompositionEnd`, but before `onInput`. + * + * `beforeInput` is spec'd but not implemented in any browsers, and + * the `input` event does not provide any useful information about what has + * actually been added, contrary to the spec. Thus, `textInput` is the best + * available event to identify the characters that have actually been inserted + * into the target node. + * + * This plugin is also responsible for emitting `composition` events, thus + * allowing us to share composition fallback code for both `beforeInput` and + * `composition` event types. + */ +var BeforeInputEventPlugin = { + + eventTypes: eventTypes, + + /** + * @param {string} topLevelType Record from `EventConstants`. + * @param {DOMEventTarget} topLevelTarget The listening component root node. + * @param {string} topLevelTargetID ID of `topLevelTarget`. + * @param {object} nativeEvent Native browser event. + * @return {*} An accumulation of synthetic events. + * @see {EventPluginHub.extractEvents} + */ + extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) { + return [extractCompositionEvent(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget), extractBeforeInputEvent(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget)]; + } +}; + +module.exports = BeforeInputEventPlugin; +},{"103":103,"107":107,"147":147,"15":15,"166":166,"19":19,"20":20}],4:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule CSSProperty + */ + +'use strict'; + +/** + * CSS properties which accept numbers but are not in units of "px". + */ +var isUnitlessNumber = { + animationIterationCount: true, + boxFlex: true, + boxFlexGroup: true, + boxOrdinalGroup: true, + columnCount: true, + flex: true, + flexGrow: true, + flexPositive: true, + flexShrink: true, + flexNegative: true, + flexOrder: true, + fontWeight: true, + lineClamp: true, + lineHeight: true, + opacity: true, + order: true, + orphans: true, + tabSize: true, + widows: true, + zIndex: true, + zoom: true, + + // SVG-related properties + fillOpacity: true, + stopOpacity: true, + strokeDashoffset: true, + strokeOpacity: true, + strokeWidth: true +}; + +/** + * @param {string} prefix vendor-specific prefix, eg: Webkit + * @param {string} key style name, eg: transitionDuration + * @return {string} style name prefixed with `prefix`, properly camelCased, eg: + * WebkitTransitionDuration + */ +function prefixKey(prefix, key) { + return prefix + key.charAt(0).toUpperCase() + key.substring(1); +} + +/** + * Support style names that may come passed in prefixed by adding permutations + * of vendor prefixes. + */ +var prefixes = ['Webkit', 'ms', 'Moz', 'O']; + +// Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an +// infinite loop, because it iterates over the newly added props too. +Object.keys(isUnitlessNumber).forEach(function (prop) { + prefixes.forEach(function (prefix) { + isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop]; + }); +}); + +/** + * Most style properties can be unset by doing .style[prop] = '' but IE8 + * doesn't like doing that with shorthand properties so for the properties that + * IE8 breaks on, which are listed here, we instead unset each of the + * individual properties. See http://bugs.jquery.com/ticket/12385. + * The 4-value 'clock' properties like margin, padding, border-width seem to + * behave without any problems. Curiously, list-style works too without any + * special prodding. + */ +var shorthandPropertyExpansions = { + background: { + backgroundAttachment: true, + backgroundColor: true, + backgroundImage: true, + backgroundPositionX: true, + backgroundPositionY: true, + backgroundRepeat: true + }, + backgroundPosition: { + backgroundPositionX: true, + backgroundPositionY: true + }, + border: { + borderWidth: true, + borderStyle: true, + borderColor: true + }, + borderBottom: { + borderBottomWidth: true, + borderBottomStyle: true, + borderBottomColor: true + }, + borderLeft: { + borderLeftWidth: true, + borderLeftStyle: true, + borderLeftColor: true + }, + borderRight: { + borderRightWidth: true, + borderRightStyle: true, + borderRightColor: true + }, + borderTop: { + borderTopWidth: true, + borderTopStyle: true, + borderTopColor: true + }, + font: { + fontStyle: true, + fontVariant: true, + fontWeight: true, + fontSize: true, + lineHeight: true, + fontFamily: true + }, + outline: { + outlineWidth: true, + outlineStyle: true, + outlineColor: true + } +}; + +var CSSProperty = { + isUnitlessNumber: isUnitlessNumber, + shorthandPropertyExpansions: shorthandPropertyExpansions +}; + +module.exports = CSSProperty; +},{}],5:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule CSSPropertyOperations + * @typechecks static-only + */ + +'use strict'; + +var CSSProperty = _dereq_(4); +var ExecutionEnvironment = _dereq_(147); +var ReactPerf = _dereq_(78); + +var camelizeStyleName = _dereq_(149); +var dangerousStyleValue = _dereq_(119); +var hyphenateStyleName = _dereq_(160); +var memoizeStringOnly = _dereq_(168); +var warning = _dereq_(173); + +var processStyleName = memoizeStringOnly(function (styleName) { + return hyphenateStyleName(styleName); +}); + +var hasShorthandPropertyBug = false; +var styleFloatAccessor = 'cssFloat'; +if (ExecutionEnvironment.canUseDOM) { + var tempStyle = document.createElementNS('http://www.w3.org/1999/xhtml', 'div').style; + try { + // IE8 throws "Invalid argument." if resetting shorthand style properties. + tempStyle.font = ''; + } catch (e) { + hasShorthandPropertyBug = true; + } + // IE8 only supports accessing cssFloat (standard) as styleFloat + if (document.documentElement.style.cssFloat === undefined) { + styleFloatAccessor = 'styleFloat'; + } +} + +if ("production" !== 'production') { + // 'msTransform' is correct, but the other prefixes should be capitalized + var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/; + + // style values shouldn't contain a semicolon + var badStyleValueWithSemicolonPattern = /;\s*$/; + + var warnedStyleNames = {}; + var warnedStyleValues = {}; + + var warnHyphenatedStyleName = function (name) { + if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { + return; + } + + warnedStyleNames[name] = true; + "production" !== 'production' ? warning(false, 'Unsupported style property %s. Did you mean %s?', name, camelizeStyleName(name)) : undefined; + }; + + var warnBadVendoredStyleName = function (name) { + if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { + return; + } + + warnedStyleNames[name] = true; + "production" !== 'production' ? warning(false, 'Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1)) : undefined; + }; + + var warnStyleValueWithSemicolon = function (name, value) { + if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) { + return; + } + + warnedStyleValues[value] = true; + "production" !== 'production' ? warning(false, 'Style property values shouldn\'t contain a semicolon. ' + 'Try "%s: %s" instead.', name, value.replace(badStyleValueWithSemicolonPattern, '')) : undefined; + }; + + /** + * @param {string} name + * @param {*} value + */ + var warnValidStyle = function (name, value) { + if (name.indexOf('-') > -1) { + warnHyphenatedStyleName(name); + } else if (badVendoredStyleNamePattern.test(name)) { + warnBadVendoredStyleName(name); + } else if (badStyleValueWithSemicolonPattern.test(value)) { + warnStyleValueWithSemicolon(name, value); + } + }; +} + +/** + * Operations for dealing with CSS properties. + */ +var CSSPropertyOperations = { + + /** + * Serializes a mapping of style properties for use as inline styles: + * + * > createMarkupForStyles({width: '200px', height: 0}) + * "width:200px;height:0;" + * + * Undefined values are ignored so that declarative programming is easier. + * The result should be HTML-escaped before insertion into the DOM. + * + * @param {object} styles + * @return {?string} + */ + createMarkupForStyles: function (styles) { + var serialized = ''; + for (var styleName in styles) { + if (!styles.hasOwnProperty(styleName)) { + continue; + } + var styleValue = styles[styleName]; + if ("production" !== 'production') { + warnValidStyle(styleName, styleValue); + } + if (styleValue != null) { + serialized += processStyleName(styleName) + ':'; + serialized += dangerousStyleValue(styleName, styleValue) + ';'; + } + } + return serialized || null; + }, + + /** + * Sets the value for multiple styles on a node. If a value is specified as + * '' (empty string), the corresponding style property will be unset. + * + * @param {DOMElement} node + * @param {object} styles + */ + setValueForStyles: function (node, styles) { + var style = node.style; + for (var styleName in styles) { + if (!styles.hasOwnProperty(styleName)) { + continue; + } + if ("production" !== 'production') { + warnValidStyle(styleName, styles[styleName]); + } + var styleValue = dangerousStyleValue(styleName, styles[styleName]); + if (styleName === 'float') { + styleName = styleFloatAccessor; + } + if (styleValue) { + style[styleName] = styleValue; + } else { + var expansion = hasShorthandPropertyBug && CSSProperty.shorthandPropertyExpansions[styleName]; + if (expansion) { + // Shorthand property that IE8 won't like unsetting, so unset each + // component to placate it + for (var individualStyleName in expansion) { + style[individualStyleName] = ''; + } + } else { + style[styleName] = ''; + } + } + } + } + +}; + +ReactPerf.measureMethods(CSSPropertyOperations, 'CSSPropertyOperations', { + setValueForStyles: 'setValueForStyles' +}); + +module.exports = CSSPropertyOperations; +},{"119":119,"147":147,"149":149,"160":160,"168":168,"173":173,"4":4,"78":78}],6:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule CallbackQueue + */ + +'use strict'; + +var PooledClass = _dereq_(25); + +var assign = _dereq_(24); +var invariant = _dereq_(161); + +/** + * A specialized pseudo-event module to help keep track of components waiting to + * be notified when their DOM representations are available for use. + * + * This implements `PooledClass`, so you should never need to instantiate this. + * Instead, use `CallbackQueue.getPooled()`. + * + * @class ReactMountReady + * @implements PooledClass + * @internal + */ +function CallbackQueue() { + this._callbacks = null; + this._contexts = null; +} + +assign(CallbackQueue.prototype, { + + /** + * Enqueues a callback to be invoked when `notifyAll` is invoked. + * + * @param {function} callback Invoked when `notifyAll` is invoked. + * @param {?object} context Context to call `callback` with. + * @internal + */ + enqueue: function (callback, context) { + this._callbacks = this._callbacks || []; + this._contexts = this._contexts || []; + this._callbacks.push(callback); + this._contexts.push(context); + }, + + /** + * Invokes all enqueued callbacks and clears the queue. This is invoked after + * the DOM representation of a component has been created or updated. + * + * @internal + */ + notifyAll: function () { + var callbacks = this._callbacks; + var contexts = this._contexts; + if (callbacks) { + !(callbacks.length === contexts.length) ? "production" !== 'production' ? invariant(false, 'Mismatched list of contexts in callback queue') : invariant(false) : undefined; + this._callbacks = null; + this._contexts = null; + for (var i = 0; i < callbacks.length; i++) { + callbacks[i].call(contexts[i]); + } + callbacks.length = 0; + contexts.length = 0; + } + }, + + /** + * Resets the internal queue. + * + * @internal + */ + reset: function () { + this._callbacks = null; + this._contexts = null; + }, + + /** + * `PooledClass` looks for this. + */ + destructor: function () { + this.reset(); + } + +}); + +PooledClass.addPoolingTo(CallbackQueue); + +module.exports = CallbackQueue; +},{"161":161,"24":24,"25":25}],7:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ChangeEventPlugin + */ + +'use strict'; + +var EventConstants = _dereq_(15); +var EventPluginHub = _dereq_(16); +var EventPropagators = _dereq_(19); +var ExecutionEnvironment = _dereq_(147); +var ReactUpdates = _dereq_(96); +var SyntheticEvent = _dereq_(105); + +var getEventTarget = _dereq_(128); +var isEventSupported = _dereq_(133); +var isTextInputElement = _dereq_(134); +var keyOf = _dereq_(166); + +var topLevelTypes = EventConstants.topLevelTypes; + +var eventTypes = { + change: { + phasedRegistrationNames: { + bubbled: keyOf({ onChange: null }), + captured: keyOf({ onChangeCapture: null }) + }, + dependencies: [topLevelTypes.topBlur, topLevelTypes.topChange, topLevelTypes.topClick, topLevelTypes.topFocus, topLevelTypes.topInput, topLevelTypes.topKeyDown, topLevelTypes.topKeyUp, topLevelTypes.topSelectionChange] + } +}; + +/** + * For IE shims + */ +var activeElement = null; +var activeElementID = null; +var activeElementValue = null; +var activeElementValueProp = null; + +/** + * SECTION: handle `change` event + */ +function shouldUseChangeEvent(elem) { + var nodeName = elem.nodeName && elem.nodeName.toLowerCase(); + return nodeName === 'select' || nodeName === 'input' && elem.type === 'file'; +} + +var doesChangeEventBubble = false; +if (ExecutionEnvironment.canUseDOM) { + // See `handleChange` comment below + doesChangeEventBubble = isEventSupported('change') && (!('documentMode' in document) || document.documentMode > 8); +} + +function manualDispatchChangeEvent(nativeEvent) { + var event = SyntheticEvent.getPooled(eventTypes.change, activeElementID, nativeEvent, getEventTarget(nativeEvent)); + EventPropagators.accumulateTwoPhaseDispatches(event); + + // If change and propertychange bubbled, we'd just bind to it like all the + // other events and have it go through ReactBrowserEventEmitter. Since it + // doesn't, we manually listen for the events and so we have to enqueue and + // process the abstract event manually. + // + // Batching is necessary here in order to ensure that all event handlers run + // before the next rerender (including event handlers attached to ancestor + // elements instead of directly on the input). Without this, controlled + // components don't work properly in conjunction with event bubbling because + // the component is rerendered and the value reverted before all the event + // handlers can run. See https://github.com/facebook/react/issues/708. + ReactUpdates.batchedUpdates(runEventInBatch, event); +} + +function runEventInBatch(event) { + EventPluginHub.enqueueEvents(event); + EventPluginHub.processEventQueue(false); +} + +function startWatchingForChangeEventIE8(target, targetID) { + activeElement = target; + activeElementID = targetID; + activeElement.attachEvent('onchange', manualDispatchChangeEvent); +} + +function stopWatchingForChangeEventIE8() { + if (!activeElement) { + return; + } + activeElement.detachEvent('onchange', manualDispatchChangeEvent); + activeElement = null; + activeElementID = null; +} + +function getTargetIDForChangeEvent(topLevelType, topLevelTarget, topLevelTargetID) { + if (topLevelType === topLevelTypes.topChange) { + return topLevelTargetID; + } +} +function handleEventsForChangeEventIE8(topLevelType, topLevelTarget, topLevelTargetID) { + if (topLevelType === topLevelTypes.topFocus) { + // stopWatching() should be a noop here but we call it just in case we + // missed a blur event somehow. + stopWatchingForChangeEventIE8(); + startWatchingForChangeEventIE8(topLevelTarget, topLevelTargetID); + } else if (topLevelType === topLevelTypes.topBlur) { + stopWatchingForChangeEventIE8(); + } +} + +/** + * SECTION: handle `input` event + */ +var isInputEventSupported = false; +if (ExecutionEnvironment.canUseDOM) { + // IE9 claims to support the input event but fails to trigger it when + // deleting text, so we ignore its input events + isInputEventSupported = isEventSupported('input') && (!('documentMode' in document) || document.documentMode > 9); +} + +/** + * (For old IE.) Replacement getter/setter for the `value` property that gets + * set on the active element. + */ +var newValueProp = { + get: function () { + return activeElementValueProp.get.call(this); + }, + set: function (val) { + // Cast to a string so we can do equality checks. + activeElementValue = '' + val; + activeElementValueProp.set.call(this, val); + } +}; + +/** + * (For old IE.) Starts tracking propertychange events on the passed-in element + * and override the value property so that we can distinguish user events from + * value changes in JS. + */ +function startWatchingForValueChange(target, targetID) { + activeElement = target; + activeElementID = targetID; + activeElementValue = target.value; + activeElementValueProp = Object.getOwnPropertyDescriptor(target.constructor.prototype, 'value'); + + // Not guarded in a canDefineProperty check: IE8 supports defineProperty only + // on DOM elements + Object.defineProperty(activeElement, 'value', newValueProp); + activeElement.attachEvent('onpropertychange', handlePropertyChange); +} + +/** + * (For old IE.) Removes the event listeners from the currently-tracked element, + * if any exists. + */ +function stopWatchingForValueChange() { + if (!activeElement) { + return; + } + + // delete restores the original property definition + delete activeElement.value; + activeElement.detachEvent('onpropertychange', handlePropertyChange); + + activeElement = null; + activeElementID = null; + activeElementValue = null; + activeElementValueProp = null; +} + +/** + * (For old IE.) Handles a propertychange event, sending a `change` event if + * the value of the active element has changed. + */ +function handlePropertyChange(nativeEvent) { + if (nativeEvent.propertyName !== 'value') { + return; + } + var value = nativeEvent.srcElement.value; + if (value === activeElementValue) { + return; + } + activeElementValue = value; + + manualDispatchChangeEvent(nativeEvent); +} + +/** + * If a `change` event should be fired, returns the target's ID. + */ +function getTargetIDForInputEvent(topLevelType, topLevelTarget, topLevelTargetID) { + if (topLevelType === topLevelTypes.topInput) { + // In modern browsers (i.e., not IE8 or IE9), the input event is exactly + // what we want so fall through here and trigger an abstract event + return topLevelTargetID; + } +} + +// For IE8 and IE9. +function handleEventsForInputEventIE(topLevelType, topLevelTarget, topLevelTargetID) { + if (topLevelType === topLevelTypes.topFocus) { + // In IE8, we can capture almost all .value changes by adding a + // propertychange handler and looking for events with propertyName + // equal to 'value' + // In IE9, propertychange fires for most input events but is buggy and + // doesn't fire when text is deleted, but conveniently, selectionchange + // appears to fire in all of the remaining cases so we catch those and + // forward the event if the value has changed + // In either case, we don't want to call the event handler if the value + // is changed from JS so we redefine a setter for `.value` that updates + // our activeElementValue variable, allowing us to ignore those changes + // + // stopWatching() should be a noop here but we call it just in case we + // missed a blur event somehow. + stopWatchingForValueChange(); + startWatchingForValueChange(topLevelTarget, topLevelTargetID); + } else if (topLevelType === topLevelTypes.topBlur) { + stopWatchingForValueChange(); + } +} + +// For IE8 and IE9. +function getTargetIDForInputEventIE(topLevelType, topLevelTarget, topLevelTargetID) { + if (topLevelType === topLevelTypes.topSelectionChange || topLevelType === topLevelTypes.topKeyUp || topLevelType === topLevelTypes.topKeyDown) { + // On the selectionchange event, the target is just document which isn't + // helpful for us so just check activeElement instead. + // + // 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire + // propertychange on the first input event after setting `value` from a + // script and fires only keydown, keypress, keyup. Catching keyup usually + // gets it and catching keydown lets us fire an event for the first + // keystroke if user does a key repeat (it'll be a little delayed: right + // before the second keystroke). Other input methods (e.g., paste) seem to + // fire selectionchange normally. + if (activeElement && activeElement.value !== activeElementValue) { + activeElementValue = activeElement.value; + return activeElementID; + } + } +} + +/** + * SECTION: handle `click` event + */ +function shouldUseClickEvent(elem) { + // Use the `click` event to detect changes to checkbox and radio inputs. + // This approach works across all browsers, whereas `change` does not fire + // until `blur` in IE8. + return elem.nodeName && elem.nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio'); +} + +function getTargetIDForClickEvent(topLevelType, topLevelTarget, topLevelTargetID) { + if (topLevelType === topLevelTypes.topClick) { + return topLevelTargetID; + } +} + +/** + * This plugin creates an `onChange` event that normalizes change events + * across form elements. This event fires at a time when it's possible to + * change the element's value without seeing a flicker. + * + * Supported elements are: + * - input (see `isTextInputElement`) + * - textarea + * - select + */ +var ChangeEventPlugin = { + + eventTypes: eventTypes, + + /** + * @param {string} topLevelType Record from `EventConstants`. + * @param {DOMEventTarget} topLevelTarget The listening component root node. + * @param {string} topLevelTargetID ID of `topLevelTarget`. + * @param {object} nativeEvent Native browser event. + * @return {*} An accumulation of synthetic events. + * @see {EventPluginHub.extractEvents} + */ + extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) { + + var getTargetIDFunc, handleEventFunc; + if (shouldUseChangeEvent(topLevelTarget)) { + if (doesChangeEventBubble) { + getTargetIDFunc = getTargetIDForChangeEvent; + } else { + handleEventFunc = handleEventsForChangeEventIE8; + } + } else if (isTextInputElement(topLevelTarget)) { + if (isInputEventSupported) { + getTargetIDFunc = getTargetIDForInputEvent; + } else { + getTargetIDFunc = getTargetIDForInputEventIE; + handleEventFunc = handleEventsForInputEventIE; + } + } else if (shouldUseClickEvent(topLevelTarget)) { + getTargetIDFunc = getTargetIDForClickEvent; + } + + if (getTargetIDFunc) { + var targetID = getTargetIDFunc(topLevelType, topLevelTarget, topLevelTargetID); + if (targetID) { + var event = SyntheticEvent.getPooled(eventTypes.change, targetID, nativeEvent, nativeEventTarget); + event.type = 'change'; + EventPropagators.accumulateTwoPhaseDispatches(event); + return event; + } + } + + if (handleEventFunc) { + handleEventFunc(topLevelType, topLevelTarget, topLevelTargetID); + } + } + +}; + +module.exports = ChangeEventPlugin; +},{"105":105,"128":128,"133":133,"134":134,"147":147,"15":15,"16":16,"166":166,"19":19,"96":96}],8:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ClientReactRootIndex + * @typechecks + */ + +'use strict'; + +var nextReactRootIndex = 0; + +var ClientReactRootIndex = { + createReactRootIndex: function () { + return nextReactRootIndex++; + } +}; + +module.exports = ClientReactRootIndex; +},{}],9:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule DOMChildrenOperations + * @typechecks static-only + */ + +'use strict'; + +var Danger = _dereq_(12); +var ReactMultiChildUpdateTypes = _dereq_(74); +var ReactPerf = _dereq_(78); + +var setInnerHTML = _dereq_(138); +var setTextContent = _dereq_(139); +var invariant = _dereq_(161); + +/** + * Inserts `childNode` as a child of `parentNode` at the `index`. + * + * @param {DOMElement} parentNode Parent node in which to insert. + * @param {DOMElement} childNode Child node to insert. + * @param {number} index Index at which to insert the child. + * @internal + */ +function insertChildAt(parentNode, childNode, index) { + // By exploiting arrays returning `undefined` for an undefined index, we can + // rely exclusively on `insertBefore(node, null)` instead of also using + // `appendChild(node)`. However, using `undefined` is not allowed by all + // browsers so we must replace it with `null`. + + // fix render order error in safari + // IE8 will throw error when index out of list size. + var beforeChild = index >= parentNode.childNodes.length ? null : parentNode.childNodes.item(index); + + parentNode.insertBefore(childNode, beforeChild); +} + +/** + * Operations for updating with DOM children. + */ +var DOMChildrenOperations = { + + dangerouslyReplaceNodeWithMarkup: Danger.dangerouslyReplaceNodeWithMarkup, + + updateTextContent: setTextContent, + + /** + * Updates a component's children by processing a series of updates. The + * update configurations are each expected to have a `parentNode` property. + * + * @param {array<object>} updates List of update configurations. + * @param {array<string>} markupList List of markup strings. + * @internal + */ + processUpdates: function (updates, markupList) { + var update; + // Mapping from parent IDs to initial child orderings. + var initialChildren = null; + // List of children that will be moved or removed. + var updatedChildren = null; + + for (var i = 0; i < updates.length; i++) { + update = updates[i]; + if (update.type === ReactMultiChildUpdateTypes.MOVE_EXISTING || update.type === ReactMultiChildUpdateTypes.REMOVE_NODE) { + var updatedIndex = update.fromIndex; + var updatedChild = update.parentNode.childNodes[updatedIndex]; + var parentID = update.parentID; + + !updatedChild ? "production" !== 'production' ? invariant(false, 'processUpdates(): Unable to find child %s of element. This ' + 'probably means the DOM was unexpectedly mutated (e.g., by the ' + 'browser), usually due to forgetting a <tbody> when using tables, ' + 'nesting tags like <form>, <p>, or <a>, or using non-SVG elements ' + 'in an <svg> parent. Try inspecting the child nodes of the element ' + 'with React ID `%s`.', updatedIndex, parentID) : invariant(false) : undefined; + + initialChildren = initialChildren || {}; + initialChildren[parentID] = initialChildren[parentID] || []; + initialChildren[parentID][updatedIndex] = updatedChild; + + updatedChildren = updatedChildren || []; + updatedChildren.push(updatedChild); + } + } + + var renderedMarkup; + // markupList is either a list of markup or just a list of elements + if (markupList.length && typeof markupList[0] === 'string') { + renderedMarkup = Danger.dangerouslyRenderMarkup(markupList); + } else { + renderedMarkup = markupList; + } + + // Remove updated children first so that `toIndex` is consistent. + if (updatedChildren) { + for (var j = 0; j < updatedChildren.length; j++) { + updatedChildren[j].parentNode.removeChild(updatedChildren[j]); + } + } + + for (var k = 0; k < updates.length; k++) { + update = updates[k]; + switch (update.type) { + case ReactMultiChildUpdateTypes.INSERT_MARKUP: + insertChildAt(update.parentNode, renderedMarkup[update.markupIndex], update.toIndex); + break; + case ReactMultiChildUpdateTypes.MOVE_EXISTING: + insertChildAt(update.parentNode, initialChildren[update.parentID][update.fromIndex], update.toIndex); + break; + case ReactMultiChildUpdateTypes.SET_MARKUP: + setInnerHTML(update.parentNode, update.content); + break; + case ReactMultiChildUpdateTypes.TEXT_CONTENT: + setTextContent(update.parentNode, update.content); + break; + case ReactMultiChildUpdateTypes.REMOVE_NODE: + // Already removed by the for-loop above. + break; + } + } + } + +}; + +ReactPerf.measureMethods(DOMChildrenOperations, 'DOMChildrenOperations', { + updateTextContent: 'updateTextContent' +}); + +module.exports = DOMChildrenOperations; +},{"12":12,"138":138,"139":139,"161":161,"74":74,"78":78}],10:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule DOMProperty + * @typechecks static-only + */ + +'use strict'; + +var invariant = _dereq_(161); + +function checkMask(value, bitmask) { + return (value & bitmask) === bitmask; +} + +var DOMPropertyInjection = { + /** + * Mapping from normalized, camelcased property names to a configuration that + * specifies how the associated DOM property should be accessed or rendered. + */ + MUST_USE_ATTRIBUTE: 0x1, + MUST_USE_PROPERTY: 0x2, + HAS_SIDE_EFFECTS: 0x4, + HAS_BOOLEAN_VALUE: 0x8, + HAS_NUMERIC_VALUE: 0x10, + HAS_POSITIVE_NUMERIC_VALUE: 0x20 | 0x10, + HAS_OVERLOADED_BOOLEAN_VALUE: 0x40, + + /** + * Inject some specialized knowledge about the DOM. This takes a config object + * with the following properties: + * + * isCustomAttribute: function that given an attribute name will return true + * if it can be inserted into the DOM verbatim. Useful for data-* or aria-* + * attributes where it's impossible to enumerate all of the possible + * attribute names, + * + * Properties: object mapping DOM property name to one of the + * DOMPropertyInjection constants or null. If your attribute isn't in here, + * it won't get written to the DOM. + * + * DOMAttributeNames: object mapping React attribute name to the DOM + * attribute name. Attribute names not specified use the **lowercase** + * normalized name. + * + * DOMAttributeNamespaces: object mapping React attribute name to the DOM + * attribute namespace URL. (Attribute names not specified use no namespace.) + * + * DOMPropertyNames: similar to DOMAttributeNames but for DOM properties. + * Property names not specified use the normalized name. + * + * DOMMutationMethods: Properties that require special mutation methods. If + * `value` is undefined, the mutation method should unset the property. + * + * @param {object} domPropertyConfig the config as described above. + */ + injectDOMPropertyConfig: function (domPropertyConfig) { + var Injection = DOMPropertyInjection; + var Properties = domPropertyConfig.Properties || {}; + var DOMAttributeNamespaces = domPropertyConfig.DOMAttributeNamespaces || {}; + var DOMAttributeNames = domPropertyConfig.DOMAttributeNames || {}; + var DOMPropertyNames = domPropertyConfig.DOMPropertyNames || {}; + var DOMMutationMethods = domPropertyConfig.DOMMutationMethods || {}; + + if (domPropertyConfig.isCustomAttribute) { + DOMProperty._isCustomAttributeFunctions.push(domPropertyConfig.isCustomAttribute); + } + + for (var propName in Properties) { + !!DOMProperty.properties.hasOwnProperty(propName) ? "production" !== 'production' ? invariant(false, 'injectDOMPropertyConfig(...): You\'re trying to inject DOM property ' + '\'%s\' which has already been injected. You may be accidentally ' + 'injecting the same DOM property config twice, or you may be ' + 'injecting two configs that have conflicting property names.', propName) : invariant(false) : undefined; + + var lowerCased = propName.toLowerCase(); + var propConfig = Properties[propName]; + + var propertyInfo = { + attributeName: lowerCased, + attributeNamespace: null, + propertyName: propName, + mutationMethod: null, + + mustUseAttribute: checkMask(propConfig, Injection.MUST_USE_ATTRIBUTE), + mustUseProperty: checkMask(propConfig, Injection.MUST_USE_PROPERTY), + hasSideEffects: checkMask(propConfig, Injection.HAS_SIDE_EFFECTS), + hasBooleanValue: checkMask(propConfig, Injection.HAS_BOOLEAN_VALUE), + hasNumericValue: checkMask(propConfig, Injection.HAS_NUMERIC_VALUE), + hasPositiveNumericValue: checkMask(propConfig, Injection.HAS_POSITIVE_NUMERIC_VALUE), + hasOverloadedBooleanValue: checkMask(propConfig, Injection.HAS_OVERLOADED_BOOLEAN_VALUE) + }; + + !(!propertyInfo.mustUseAttribute || !propertyInfo.mustUseProperty) ? "production" !== 'production' ? invariant(false, 'DOMProperty: Cannot require using both attribute and property: %s', propName) : invariant(false) : undefined; + !(propertyInfo.mustUseProperty || !propertyInfo.hasSideEffects) ? "production" !== 'production' ? invariant(false, 'DOMProperty: Properties that have side effects must use property: %s', propName) : invariant(false) : undefined; + !(propertyInfo.hasBooleanValue + propertyInfo.hasNumericValue + propertyInfo.hasOverloadedBooleanValue <= 1) ? "production" !== 'production' ? invariant(false, 'DOMProperty: Value can be one of boolean, overloaded boolean, or ' + 'numeric value, but not a combination: %s', propName) : invariant(false) : undefined; + + if ("production" !== 'production') { + DOMProperty.getPossibleStandardName[lowerCased] = propName; + } + + if (DOMAttributeNames.hasOwnProperty(propName)) { + var attributeName = DOMAttributeNames[propName]; + propertyInfo.attributeName = attributeName; + if ("production" !== 'production') { + DOMProperty.getPossibleStandardName[attributeName] = propName; + } + } + + if (DOMAttributeNamespaces.hasOwnProperty(propName)) { + propertyInfo.attributeNamespace = DOMAttributeNamespaces[propName]; + } + + if (DOMPropertyNames.hasOwnProperty(propName)) { + propertyInfo.propertyName = DOMPropertyNames[propName]; + } + + if (DOMMutationMethods.hasOwnProperty(propName)) { + propertyInfo.mutationMethod = DOMMutationMethods[propName]; + } + + DOMProperty.properties[propName] = propertyInfo; + } + } +}; +var defaultValueCache = {}; + +/** + * DOMProperty exports lookup objects that can be used like functions: + * + * > DOMProperty.isValid['id'] + * true + * > DOMProperty.isValid['foobar'] + * undefined + * + * Although this may be confusing, it performs better in general. + * + * @see http://jsperf.com/key-exists + * @see http://jsperf.com/key-missing + */ +var DOMProperty = { + + ID_ATTRIBUTE_NAME: 'data-reactid', + + /** + * Map from property "standard name" to an object with info about how to set + * the property in the DOM. Each object contains: + * + * attributeName: + * Used when rendering markup or with `*Attribute()`. + * attributeNamespace + * propertyName: + * Used on DOM node instances. (This includes properties that mutate due to + * external factors.) + * mutationMethod: + * If non-null, used instead of the property or `setAttribute()` after + * initial render. + * mustUseAttribute: + * Whether the property must be accessed and mutated using `*Attribute()`. + * (This includes anything that fails `<propName> in <element>`.) + * mustUseProperty: + * Whether the property must be accessed and mutated as an object property. + * hasSideEffects: + * Whether or not setting a value causes side effects such as triggering + * resources to be loaded or text selection changes. If true, we read from + * the DOM before updating to ensure that the value is only set if it has + * changed. + * hasBooleanValue: + * Whether the property should be removed when set to a falsey value. + * hasNumericValue: + * Whether the property must be numeric or parse as a numeric and should be + * removed when set to a falsey value. + * hasPositiveNumericValue: + * Whether the property must be positive numeric or parse as a positive + * numeric and should be removed when set to a falsey value. + * hasOverloadedBooleanValue: + * Whether the property can be used as a flag as well as with a value. + * Removed when strictly equal to false; present without a value when + * strictly equal to true; present with a value otherwise. + */ + properties: {}, + + /** + * Mapping from lowercase property names to the properly cased version, used + * to warn in the case of missing properties. Available only in __DEV__. + * @type {Object} + */ + getPossibleStandardName: "production" !== 'production' ? {} : null, + + /** + * All of the isCustomAttribute() functions that have been injected. + */ + _isCustomAttributeFunctions: [], + + /** + * Checks whether a property name is a custom attribute. + * @method + */ + isCustomAttribute: function (attributeName) { + for (var i = 0; i < DOMProperty._isCustomAttributeFunctions.length; i++) { + var isCustomAttributeFn = DOMProperty._isCustomAttributeFunctions[i]; + if (isCustomAttributeFn(attributeName)) { + return true; + } + } + return false; + }, + + /** + * Returns the default property value for a DOM property (i.e., not an + * attribute). Most default values are '' or false, but not all. Worse yet, + * some (in particular, `type`) vary depending on the type of element. + * + * TODO: Is it better to grab all the possible properties when creating an + * element to avoid having to create the same element twice? + */ + getDefaultValueForProperty: function (nodeName, prop) { + var nodeDefaults = defaultValueCache[nodeName]; + var testElement; + if (!nodeDefaults) { + defaultValueCache[nodeName] = nodeDefaults = {}; + } + if (!(prop in nodeDefaults)) { + testElement = document.createElementNS('http://www.w3.org/1999/xhtml', nodeName); + nodeDefaults[prop] = testElement[prop]; + } + return nodeDefaults[prop]; + }, + + injection: DOMPropertyInjection +}; + +module.exports = DOMProperty; +},{"161":161}],11:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule DOMPropertyOperations + * @typechecks static-only + */ + +'use strict'; + +var DOMProperty = _dereq_(10); +var ReactPerf = _dereq_(78); + +var quoteAttributeValueForBrowser = _dereq_(136); +var warning = _dereq_(173); + +// Simplified subset +var VALID_ATTRIBUTE_NAME_REGEX = /^[a-zA-Z_][\w\.\-]*$/; +var illegalAttributeNameCache = {}; +var validatedAttributeNameCache = {}; + +function isAttributeNameSafe(attributeName) { + if (validatedAttributeNameCache.hasOwnProperty(attributeName)) { + return true; + } + if (illegalAttributeNameCache.hasOwnProperty(attributeName)) { + return false; + } + if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) { + validatedAttributeNameCache[attributeName] = true; + return true; + } + illegalAttributeNameCache[attributeName] = true; + "production" !== 'production' ? warning(false, 'Invalid attribute name: `%s`', attributeName) : undefined; + return false; +} + +function shouldIgnoreValue(propertyInfo, value) { + return value == null || propertyInfo.hasBooleanValue && !value || propertyInfo.hasNumericValue && isNaN(value) || propertyInfo.hasPositiveNumericValue && value < 1 || propertyInfo.hasOverloadedBooleanValue && value === false; +} + +if ("production" !== 'production') { + var reactProps = { + children: true, + dangerouslySetInnerHTML: true, + key: true, + ref: true + }; + var warnedProperties = {}; + + var warnUnknownProperty = function (name) { + if (reactProps.hasOwnProperty(name) && reactProps[name] || warnedProperties.hasOwnProperty(name) && warnedProperties[name]) { + return; + } + + warnedProperties[name] = true; + var lowerCasedName = name.toLowerCase(); + + // data-* attributes should be lowercase; suggest the lowercase version + var standardName = DOMProperty.isCustomAttribute(lowerCasedName) ? lowerCasedName : DOMProperty.getPossibleStandardName.hasOwnProperty(lowerCasedName) ? DOMProperty.getPossibleStandardName[lowerCasedName] : null; + + // For now, only warn when we have a suggested correction. This prevents + // logging too much when using transferPropsTo. + "production" !== 'production' ? warning(standardName == null, 'Unknown DOM property %s. Did you mean %s?', name, standardName) : undefined; + }; +} + +/** + * Operations for dealing with DOM properties. + */ +var DOMPropertyOperations = { + + /** + * Creates markup for the ID property. + * + * @param {string} id Unescaped ID. + * @return {string} Markup string. + */ + createMarkupForID: function (id) { + return DOMProperty.ID_ATTRIBUTE_NAME + '=' + quoteAttributeValueForBrowser(id); + }, + + setAttributeForID: function (node, id) { + node.setAttribute(DOMProperty.ID_ATTRIBUTE_NAME, id); + }, + + /** + * Creates markup for a property. + * + * @param {string} name + * @param {*} value + * @return {?string} Markup string, or null if the property was invalid. + */ + createMarkupForProperty: function (name, value) { + var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null; + if (propertyInfo) { + if (shouldIgnoreValue(propertyInfo, value)) { + return ''; + } + var attributeName = propertyInfo.attributeName; + if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) { + return attributeName + '=""'; + } + return attributeName + '=' + quoteAttributeValueForBrowser(value); + } else if (DOMProperty.isCustomAttribute(name)) { + if (value == null) { + return ''; + } + return name + '=' + quoteAttributeValueForBrowser(value); + } else if ("production" !== 'production') { + warnUnknownProperty(name); + } + return null; + }, + + /** + * Creates markup for a custom property. + * + * @param {string} name + * @param {*} value + * @return {string} Markup string, or empty string if the property was invalid. + */ + createMarkupForCustomAttribute: function (name, value) { + if (!isAttributeNameSafe(name) || value == null) { + return ''; + } + return name + '=' + quoteAttributeValueForBrowser(value); + }, + + /** + * Sets the value for a property on a node. + * + * @param {DOMElement} node + * @param {string} name + * @param {*} value + */ + setValueForProperty: function (node, name, value) { + var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null; + if (propertyInfo) { + var mutationMethod = propertyInfo.mutationMethod; + if (mutationMethod) { + mutationMethod(node, value); + } else if (shouldIgnoreValue(propertyInfo, value)) { + this.deleteValueForProperty(node, name); + } else if (propertyInfo.mustUseAttribute) { + var attributeName = propertyInfo.attributeName; + var namespace = propertyInfo.attributeNamespace; + // `setAttribute` with objects becomes only `[object]` in IE8/9, + // ('' + value) makes it output the correct toString()-value. + if (namespace) { + node.setAttributeNS(namespace, attributeName, '' + value); + } else if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) { + node.setAttribute(attributeName, ''); + } else { + node.setAttribute(attributeName, '' + value); + } + } else { + var propName = propertyInfo.propertyName; + // Must explicitly cast values for HAS_SIDE_EFFECTS-properties to the + // property type before comparing; only `value` does and is string. + if (!propertyInfo.hasSideEffects || '' + node[propName] !== '' + value) { + // Contrary to `setAttribute`, object properties are properly + // `toString`ed by IE8/9. + node[propName] = value; + } + } + } else if (DOMProperty.isCustomAttribute(name)) { + DOMPropertyOperations.setValueForAttribute(node, name, value); + } else if ("production" !== 'production') { + warnUnknownProperty(name); + } + }, + + setValueForAttribute: function (node, name, value) { + if (!isAttributeNameSafe(name)) { + return; + } + if (value == null) { + node.removeAttribute(name); + } else { + node.setAttribute(name, '' + value); + } + }, + + /** + * Deletes the value for a property on a node. + * + * @param {DOMElement} node + * @param {string} name + */ + deleteValueForProperty: function (node, name) { + var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null; + if (propertyInfo) { + var mutationMethod = propertyInfo.mutationMethod; + if (mutationMethod) { + mutationMethod(node, undefined); + } else if (propertyInfo.mustUseAttribute) { + node.removeAttribute(propertyInfo.attributeName); + } else { + var propName = propertyInfo.propertyName; + var defaultValue = DOMProperty.getDefaultValueForProperty(node.nodeName, propName); + if (!propertyInfo.hasSideEffects || '' + node[propName] !== defaultValue) { + node[propName] = defaultValue; + } + } + } else if (DOMProperty.isCustomAttribute(name)) { + node.removeAttribute(name); + } else if ("production" !== 'production') { + warnUnknownProperty(name); + } + } + +}; + +ReactPerf.measureMethods(DOMPropertyOperations, 'DOMPropertyOperations', { + setValueForProperty: 'setValueForProperty', + setValueForAttribute: 'setValueForAttribute', + deleteValueForProperty: 'deleteValueForProperty' +}); + +module.exports = DOMPropertyOperations; +},{"10":10,"136":136,"173":173,"78":78}],12:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule Danger + * @typechecks static-only + */ + +'use strict'; + +var ExecutionEnvironment = _dereq_(147); + +var createNodesFromMarkup = _dereq_(152); +var emptyFunction = _dereq_(153); +var getMarkupWrap = _dereq_(157); +var invariant = _dereq_(161); + +var OPEN_TAG_NAME_EXP = /^(<[^ \/>]+)/; +var RESULT_INDEX_ATTR = 'data-danger-index'; + +/** + * Extracts the `nodeName` from a string of markup. + * + * NOTE: Extracting the `nodeName` does not require a regular expression match + * because we make assumptions about React-generated markup (i.e. there are no + * spaces surrounding the opening tag and there is at least one attribute). + * + * @param {string} markup String of markup. + * @return {string} Node name of the supplied markup. + * @see http://jsperf.com/extract-nodename + */ +function getNodeName(markup) { + return markup.substring(1, markup.indexOf(' ')); +} + +var Danger = { + + /** + * Renders markup into an array of nodes. The markup is expected to render + * into a list of root nodes. Also, the length of `resultList` and + * `markupList` should be the same. + * + * @param {array<string>} markupList List of markup strings to render. + * @return {array<DOMElement>} List of rendered nodes. + * @internal + */ + dangerouslyRenderMarkup: function (markupList) { + !ExecutionEnvironment.canUseDOM ? "production" !== 'production' ? invariant(false, 'dangerouslyRenderMarkup(...): Cannot render markup in a worker ' + 'thread. Make sure `window` and `document` are available globally ' + 'before requiring React when unit testing or use ' + 'ReactDOMServer.renderToString for server rendering.') : invariant(false) : undefined; + var nodeName; + var markupByNodeName = {}; + // Group markup by `nodeName` if a wrap is necessary, else by '*'. + for (var i = 0; i < markupList.length; i++) { + !markupList[i] ? "production" !== 'production' ? invariant(false, 'dangerouslyRenderMarkup(...): Missing markup.') : invariant(false) : undefined; + nodeName = getNodeName(markupList[i]); + nodeName = getMarkupWrap(nodeName) ? nodeName : '*'; + markupByNodeName[nodeName] = markupByNodeName[nodeName] || []; + markupByNodeName[nodeName][i] = markupList[i]; + } + var resultList = []; + var resultListAssignmentCount = 0; + for (nodeName in markupByNodeName) { + if (!markupByNodeName.hasOwnProperty(nodeName)) { + continue; + } + var markupListByNodeName = markupByNodeName[nodeName]; + + // This for-in loop skips the holes of the sparse array. The order of + // iteration should follow the order of assignment, which happens to match + // numerical index order, but we don't rely on that. + var resultIndex; + for (resultIndex in markupListByNodeName) { + if (markupListByNodeName.hasOwnProperty(resultIndex)) { + var markup = markupListByNodeName[resultIndex]; + + // Push the requested markup with an additional RESULT_INDEX_ATTR + // attribute. If the markup does not start with a < character, it + // will be discarded below (with an appropriate console.error). + markupListByNodeName[resultIndex] = markup.replace(OPEN_TAG_NAME_EXP, + // This index will be parsed back out below. + '$1 ' + RESULT_INDEX_ATTR + '="' + resultIndex + '" '); + } + } + + // Render each group of markup with similar wrapping `nodeName`. + var renderNodes = createNodesFromMarkup(markupListByNodeName.join(''), emptyFunction // Do nothing special with <script> tags. + ); + + for (var j = 0; j < renderNodes.length; ++j) { + var renderNode = renderNodes[j]; + if (renderNode.hasAttribute && renderNode.hasAttribute(RESULT_INDEX_ATTR)) { + + resultIndex = +renderNode.getAttribute(RESULT_INDEX_ATTR); + renderNode.removeAttribute(RESULT_INDEX_ATTR); + + !!resultList.hasOwnProperty(resultIndex) ? "production" !== 'production' ? invariant(false, 'Danger: Assigning to an already-occupied result index.') : invariant(false) : undefined; + + resultList[resultIndex] = renderNode; + + // This should match resultList.length and markupList.length when + // we're done. + resultListAssignmentCount += 1; + } else if ("production" !== 'production') { + console.error('Danger: Discarding unexpected node:', renderNode); + } + } + } + + // Although resultList was populated out of order, it should now be a dense + // array. + !(resultListAssignmentCount === resultList.length) ? "production" !== 'production' ? invariant(false, 'Danger: Did not assign to every index of resultList.') : invariant(false) : undefined; + + !(resultList.length === markupList.length) ? "production" !== 'production' ? invariant(false, 'Danger: Expected markup to render %s nodes, but rendered %s.', markupList.length, resultList.length) : invariant(false) : undefined; + + return resultList; + }, + + /** + * Replaces a node with a string of markup at its current position within its + * parent. The markup must render into a single root node. + * + * @param {DOMElement} oldChild Child node to replace. + * @param {string} markup Markup to render in place of the child node. + * @internal + */ + dangerouslyReplaceNodeWithMarkup: function (oldChild, markup) { + !ExecutionEnvironment.canUseDOM ? "production" !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Cannot render markup in a ' + 'worker thread. Make sure `window` and `document` are available ' + 'globally before requiring React when unit testing or use ' + 'ReactDOMServer.renderToString() for server rendering.') : invariant(false) : undefined; + !markup ? "production" !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Missing markup.') : invariant(false) : undefined; + !(oldChild.tagName.toLowerCase() !== 'html') ? "production" !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Cannot replace markup of the ' + '<html> node. This is because browser quirks make this unreliable ' + 'and/or slow. If you want to render to the root you must use ' + 'server rendering. See ReactDOMServer.renderToString().') : invariant(false) : undefined; + + var newChild; + if (typeof markup === 'string') { + newChild = createNodesFromMarkup(markup, emptyFunction)[0]; + } else { + newChild = markup; + } + oldChild.parentNode.replaceChild(newChild, oldChild); + } + +}; + +module.exports = Danger; +},{"147":147,"152":152,"153":153,"157":157,"161":161}],13:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule DefaultEventPluginOrder + */ + +'use strict'; + +var keyOf = _dereq_(166); + +/** + * Module that is injectable into `EventPluginHub`, that specifies a + * deterministic ordering of `EventPlugin`s. A convenient way to reason about + * plugins, without having to package every one of them. This is better than + * having plugins be ordered in the same order that they are injected because + * that ordering would be influenced by the packaging order. + * `ResponderEventPlugin` must occur before `SimpleEventPlugin` so that + * preventing default on events is convenient in `SimpleEventPlugin` handlers. + */ +var DefaultEventPluginOrder = [keyOf({ ResponderEventPlugin: null }), keyOf({ SimpleEventPlugin: null }), keyOf({ TapEventPlugin: null }), keyOf({ EnterLeaveEventPlugin: null }), keyOf({ ChangeEventPlugin: null }), keyOf({ SelectEventPlugin: null }), keyOf({ BeforeInputEventPlugin: null })]; + +module.exports = DefaultEventPluginOrder; +},{"166":166}],14:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule EnterLeaveEventPlugin + * @typechecks static-only + */ + +'use strict'; + +var EventConstants = _dereq_(15); +var EventPropagators = _dereq_(19); +var SyntheticMouseEvent = _dereq_(109); + +var ReactMount = _dereq_(72); +var keyOf = _dereq_(166); + +var topLevelTypes = EventConstants.topLevelTypes; +var getFirstReactDOM = ReactMount.getFirstReactDOM; + +var eventTypes = { + mouseEnter: { + registrationName: keyOf({ onMouseEnter: null }), + dependencies: [topLevelTypes.topMouseOut, topLevelTypes.topMouseOver] + }, + mouseLeave: { + registrationName: keyOf({ onMouseLeave: null }), + dependencies: [topLevelTypes.topMouseOut, topLevelTypes.topMouseOver] + } +}; + +var extractedEvents = [null, null]; + +var EnterLeaveEventPlugin = { + + eventTypes: eventTypes, + + /** + * For almost every interaction we care about, there will be both a top-level + * `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that + * we do not extract duplicate events. However, moving the mouse into the + * browser from outside will not fire a `mouseout` event. In this case, we use + * the `mouseover` top-level event. + * + * @param {string} topLevelType Record from `EventConstants`. + * @param {DOMEventTarget} topLevelTarget The listening component root node. + * @param {string} topLevelTargetID ID of `topLevelTarget`. + * @param {object} nativeEvent Native browser event. + * @return {*} An accumulation of synthetic events. + * @see {EventPluginHub.extractEvents} + */ + extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) { + if (topLevelType === topLevelTypes.topMouseOver && (nativeEvent.relatedTarget || nativeEvent.fromElement)) { + return null; + } + if (topLevelType !== topLevelTypes.topMouseOut && topLevelType !== topLevelTypes.topMouseOver) { + // Must not be a mouse in or mouse out - ignoring. + return null; + } + + var win; + if (topLevelTarget.window === topLevelTarget) { + // `topLevelTarget` is probably a window object. + win = topLevelTarget; + } else { + // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. + var doc = topLevelTarget.ownerDocument; + if (doc) { + win = doc.defaultView || doc.parentWindow; + } else { + win = window; + } + } + + var from; + var to; + var fromID = ''; + var toID = ''; + if (topLevelType === topLevelTypes.topMouseOut) { + from = topLevelTarget; + fromID = topLevelTargetID; + to = getFirstReactDOM(nativeEvent.relatedTarget || nativeEvent.toElement); + if (to) { + toID = ReactMount.getID(to); + } else { + to = win; + } + to = to || win; + } else { + from = win; + to = topLevelTarget; + toID = topLevelTargetID; + } + + if (from === to) { + // Nothing pertains to our managed components. + return null; + } + + var leave = SyntheticMouseEvent.getPooled(eventTypes.mouseLeave, fromID, nativeEvent, nativeEventTarget); + leave.type = 'mouseleave'; + leave.target = from; + leave.relatedTarget = to; + + var enter = SyntheticMouseEvent.getPooled(eventTypes.mouseEnter, toID, nativeEvent, nativeEventTarget); + enter.type = 'mouseenter'; + enter.target = to; + enter.relatedTarget = from; + + EventPropagators.accumulateEnterLeaveDispatches(leave, enter, fromID, toID); + + extractedEvents[0] = leave; + extractedEvents[1] = enter; + + return extractedEvents; + } + +}; + +module.exports = EnterLeaveEventPlugin; +},{"109":109,"15":15,"166":166,"19":19,"72":72}],15:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule EventConstants + */ + +'use strict'; + +var keyMirror = _dereq_(165); + +var PropagationPhases = keyMirror({ bubbled: null, captured: null }); + +/** + * Types of raw signals from the browser caught at the top level. + */ +var topLevelTypes = keyMirror({ + topAbort: null, + topBlur: null, + topCanPlay: null, + topCanPlayThrough: null, + topChange: null, + topClick: null, + topCompositionEnd: null, + topCompositionStart: null, + topCompositionUpdate: null, + topContextMenu: null, + topCopy: null, + topCut: null, + topDoubleClick: null, + topDrag: null, + topDragEnd: null, + topDragEnter: null, + topDragExit: null, + topDragLeave: null, + topDragOver: null, + topDragStart: null, + topDrop: null, + topDurationChange: null, + topEmptied: null, + topEncrypted: null, + topEnded: null, + topError: null, + topFocus: null, + topInput: null, + topKeyDown: null, + topKeyPress: null, + topKeyUp: null, + topLoad: null, + topLoadedData: null, + topLoadedMetadata: null, + topLoadStart: null, + topMouseDown: null, + topMouseMove: null, + topMouseOut: null, + topMouseOver: null, + topMouseUp: null, + topPaste: null, + topPause: null, + topPlay: null, + topPlaying: null, + topProgress: null, + topRateChange: null, + topReset: null, + topScroll: null, + topSeeked: null, + topSeeking: null, + topSelectionChange: null, + topStalled: null, + topSubmit: null, + topSuspend: null, + topTextInput: null, + topTimeUpdate: null, + topTouchCancel: null, + topTouchEnd: null, + topTouchMove: null, + topTouchStart: null, + topVolumeChange: null, + topWaiting: null, + topWheel: null +}); + +var EventConstants = { + topLevelTypes: topLevelTypes, + PropagationPhases: PropagationPhases +}; + +module.exports = EventConstants; +},{"165":165}],16:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule EventPluginHub + */ + +'use strict'; + +var EventPluginRegistry = _dereq_(17); +var EventPluginUtils = _dereq_(18); +var ReactErrorUtils = _dereq_(61); + +var accumulateInto = _dereq_(115); +var forEachAccumulated = _dereq_(124); +var invariant = _dereq_(161); +var warning = _dereq_(173); + +/** + * Internal store for event listeners + */ +var listenerBank = {}; + +/** + * Internal queue of events that have accumulated their dispatches and are + * waiting to have their dispatches executed. + */ +var eventQueue = null; + +/** + * Dispatches an event and releases it back into the pool, unless persistent. + * + * @param {?object} event Synthetic event to be dispatched. + * @param {boolean} simulated If the event is simulated (changes exn behavior) + * @private + */ +var executeDispatchesAndRelease = function (event, simulated) { + if (event) { + EventPluginUtils.executeDispatchesInOrder(event, simulated); + + if (!event.isPersistent()) { + event.constructor.release(event); + } + } +}; +var executeDispatchesAndReleaseSimulated = function (e) { + return executeDispatchesAndRelease(e, true); +}; +var executeDispatchesAndReleaseTopLevel = function (e) { + return executeDispatchesAndRelease(e, false); +}; + +/** + * - `InstanceHandle`: [required] Module that performs logical traversals of DOM + * hierarchy given ids of the logical DOM elements involved. + */ +var InstanceHandle = null; + +function validateInstanceHandle() { + var valid = InstanceHandle && InstanceHandle.traverseTwoPhase && InstanceHandle.traverseEnterLeave; + "production" !== 'production' ? warning(valid, 'InstanceHandle not injected before use!') : undefined; +} + +/** + * This is a unified interface for event plugins to be installed and configured. + * + * Event plugins can implement the following properties: + * + * `extractEvents` {function(string, DOMEventTarget, string, object): *} + * Required. When a top-level event is fired, this method is expected to + * extract synthetic events that will in turn be queued and dispatched. + * + * `eventTypes` {object} + * Optional, plugins that fire events must publish a mapping of registration + * names that are used to register listeners. Values of this mapping must + * be objects that contain `registrationName` or `phasedRegistrationNames`. + * + * `executeDispatch` {function(object, function, string)} + * Optional, allows plugins to override how an event gets dispatched. By + * default, the listener is simply invoked. + * + * Each plugin that is injected into `EventsPluginHub` is immediately operable. + * + * @public + */ +var EventPluginHub = { + + /** + * Methods for injecting dependencies. + */ + injection: { + + /** + * @param {object} InjectedMount + * @public + */ + injectMount: EventPluginUtils.injection.injectMount, + + /** + * @param {object} InjectedInstanceHandle + * @public + */ + injectInstanceHandle: function (InjectedInstanceHandle) { + InstanceHandle = InjectedInstanceHandle; + if ("production" !== 'production') { + validateInstanceHandle(); + } + }, + + getInstanceHandle: function () { + if ("production" !== 'production') { + validateInstanceHandle(); + } + return InstanceHandle; + }, + + /** + * @param {array} InjectedEventPluginOrder + * @public + */ + injectEventPluginOrder: EventPluginRegistry.injectEventPluginOrder, + + /** + * @param {object} injectedNamesToPlugins Map from names to plugin modules. + */ + injectEventPluginsByName: EventPluginRegistry.injectEventPluginsByName + + }, + + eventNameDispatchConfigs: EventPluginRegistry.eventNameDispatchConfigs, + + registrationNameModules: EventPluginRegistry.registrationNameModules, + + /** + * Stores `listener` at `listenerBank[registrationName][id]`. Is idempotent. + * + * @param {string} id ID of the DOM element. + * @param {string} registrationName Name of listener (e.g. `onClick`). + * @param {?function} listener The callback to store. + */ + putListener: function (id, registrationName, listener) { + !(typeof listener === 'function') ? "production" !== 'production' ? invariant(false, 'Expected %s listener to be a function, instead got type %s', registrationName, typeof listener) : invariant(false) : undefined; + + var bankForRegistrationName = listenerBank[registrationName] || (listenerBank[registrationName] = {}); + bankForRegistrationName[id] = listener; + + var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; + if (PluginModule && PluginModule.didPutListener) { + PluginModule.didPutListener(id, registrationName, listener); + } + }, + + /** + * @param {string} id ID of the DOM element. + * @param {string} registrationName Name of listener (e.g. `onClick`). + * @return {?function} The stored callback. + */ + getListener: function (id, registrationName) { + var bankForRegistrationName = listenerBank[registrationName]; + return bankForRegistrationName && bankForRegistrationName[id]; + }, + + /** + * Deletes a listener from the registration bank. + * + * @param {string} id ID of the DOM element. + * @param {string} registrationName Name of listener (e.g. `onClick`). + */ + deleteListener: function (id, registrationName) { + var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; + if (PluginModule && PluginModule.willDeleteListener) { + PluginModule.willDeleteListener(id, registrationName); + } + + var bankForRegistrationName = listenerBank[registrationName]; + // TODO: This should never be null -- when is it? + if (bankForRegistrationName) { + delete bankForRegistrationName[id]; + } + }, + + /** + * Deletes all listeners for the DOM element with the supplied ID. + * + * @param {string} id ID of the DOM element. + */ + deleteAllListeners: function (id) { + for (var registrationName in listenerBank) { + if (!listenerBank[registrationName][id]) { + continue; + } + + var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; + if (PluginModule && PluginModule.willDeleteListener) { + PluginModule.willDeleteListener(id, registrationName); + } + + delete listenerBank[registrationName][id]; + } + }, + + /** + * Allows registered plugins an opportunity to extract events from top-level + * native browser events. + * + * @param {string} topLevelType Record from `EventConstants`. + * @param {DOMEventTarget} topLevelTarget The listening component root node. + * @param {string} topLevelTargetID ID of `topLevelTarget`. + * @param {object} nativeEvent Native browser event. + * @return {*} An accumulation of synthetic events. + * @internal + */ + extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) { + var events; + var plugins = EventPluginRegistry.plugins; + for (var i = 0; i < plugins.length; i++) { + // Not every plugin in the ordering may be loaded at runtime. + var possiblePlugin = plugins[i]; + if (possiblePlugin) { + var extractedEvents = possiblePlugin.extractEvents(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget); + if (extractedEvents) { + events = accumulateInto(events, extractedEvents); + } + } + } + return events; + }, + + /** + * Enqueues a synthetic event that should be dispatched when + * `processEventQueue` is invoked. + * + * @param {*} events An accumulation of synthetic events. + * @internal + */ + enqueueEvents: function (events) { + if (events) { + eventQueue = accumulateInto(eventQueue, events); + } + }, + + /** + * Dispatches all synthetic events on the event queue. + * + * @internal + */ + processEventQueue: function (simulated) { + // Set `eventQueue` to null before processing it so that we can tell if more + // events get enqueued while processing. + var processingEventQueue = eventQueue; + eventQueue = null; + if (simulated) { + forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseSimulated); + } else { + forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel); + } + !!eventQueue ? "production" !== 'production' ? invariant(false, 'processEventQueue(): Additional events were enqueued while processing ' + 'an event queue. Support for this has not yet been implemented.') : invariant(false) : undefined; + // This would be a good time to rethrow if any of the event handlers threw. + ReactErrorUtils.rethrowCaughtError(); + }, + + /** + * These are needed for tests only. Do not use! + */ + __purge: function () { + listenerBank = {}; + }, + + __getListenerBank: function () { + return listenerBank; + } + +}; + +module.exports = EventPluginHub; +},{"115":115,"124":124,"161":161,"17":17,"173":173,"18":18,"61":61}],17:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule EventPluginRegistry + * @typechecks static-only + */ + +'use strict'; + +var invariant = _dereq_(161); + +/** + * Injectable ordering of event plugins. + */ +var EventPluginOrder = null; + +/** + * Injectable mapping from names to event plugin modules. + */ +var namesToPlugins = {}; + +/** + * Recomputes the plugin list using the injected plugins and plugin ordering. + * + * @private + */ +function recomputePluginOrdering() { + if (!EventPluginOrder) { + // Wait until an `EventPluginOrder` is injected. + return; + } + for (var pluginName in namesToPlugins) { + var PluginModule = namesToPlugins[pluginName]; + var pluginIndex = EventPluginOrder.indexOf(pluginName); + !(pluginIndex > -1) ? "production" !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject event plugins that do not exist in ' + 'the plugin ordering, `%s`.', pluginName) : invariant(false) : undefined; + if (EventPluginRegistry.plugins[pluginIndex]) { + continue; + } + !PluginModule.extractEvents ? "production" !== 'production' ? invariant(false, 'EventPluginRegistry: Event plugins must implement an `extractEvents` ' + 'method, but `%s` does not.', pluginName) : invariant(false) : undefined; + EventPluginRegistry.plugins[pluginIndex] = PluginModule; + var publishedEvents = PluginModule.eventTypes; + for (var eventName in publishedEvents) { + !publishEventForPlugin(publishedEvents[eventName], PluginModule, eventName) ? "production" !== 'production' ? invariant(false, 'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.', eventName, pluginName) : invariant(false) : undefined; + } + } +} + +/** + * Publishes an event so that it can be dispatched by the supplied plugin. + * + * @param {object} dispatchConfig Dispatch configuration for the event. + * @param {object} PluginModule Plugin publishing the event. + * @return {boolean} True if the event was successfully published. + * @private + */ +function publishEventForPlugin(dispatchConfig, PluginModule, eventName) { + !!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName) ? "production" !== 'production' ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same ' + 'event name, `%s`.', eventName) : invariant(false) : undefined; + EventPluginRegistry.eventNameDispatchConfigs[eventName] = dispatchConfig; + + var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; + if (phasedRegistrationNames) { + for (var phaseName in phasedRegistrationNames) { + if (phasedRegistrationNames.hasOwnProperty(phaseName)) { + var phasedRegistrationName = phasedRegistrationNames[phaseName]; + publishRegistrationName(phasedRegistrationName, PluginModule, eventName); + } + } + return true; + } else if (dispatchConfig.registrationName) { + publishRegistrationName(dispatchConfig.registrationName, PluginModule, eventName); + return true; + } + return false; +} + +/** + * Publishes a registration name that is used to identify dispatched events and + * can be used with `EventPluginHub.putListener` to register listeners. + * + * @param {string} registrationName Registration name to add. + * @param {object} PluginModule Plugin publishing the event. + * @private + */ +function publishRegistrationName(registrationName, PluginModule, eventName) { + !!EventPluginRegistry.registrationNameModules[registrationName] ? "production" !== 'production' ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same ' + 'registration name, `%s`.', registrationName) : invariant(false) : undefined; + EventPluginRegistry.registrationNameModules[registrationName] = PluginModule; + EventPluginRegistry.registrationNameDependencies[registrationName] = PluginModule.eventTypes[eventName].dependencies; +} + +/** + * Registers plugins so that they can extract and dispatch events. + * + * @see {EventPluginHub} + */ +var EventPluginRegistry = { + + /** + * Ordered list of injected plugins. + */ + plugins: [], + + /** + * Mapping from event name to dispatch config + */ + eventNameDispatchConfigs: {}, + + /** + * Mapping from registration name to plugin module + */ + registrationNameModules: {}, + + /** + * Mapping from registration name to event name + */ + registrationNameDependencies: {}, + + /** + * Injects an ordering of plugins (by plugin name). This allows the ordering + * to be decoupled from injection of the actual plugins so that ordering is + * always deterministic regardless of packaging, on-the-fly injection, etc. + * + * @param {array} InjectedEventPluginOrder + * @internal + * @see {EventPluginHub.injection.injectEventPluginOrder} + */ + injectEventPluginOrder: function (InjectedEventPluginOrder) { + !!EventPluginOrder ? "production" !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject event plugin ordering more than ' + 'once. You are likely trying to load more than one copy of React.') : invariant(false) : undefined; + // Clone the ordering so it cannot be dynamically mutated. + EventPluginOrder = Array.prototype.slice.call(InjectedEventPluginOrder); + recomputePluginOrdering(); + }, + + /** + * Injects plugins to be used by `EventPluginHub`. The plugin names must be + * in the ordering injected by `injectEventPluginOrder`. + * + * Plugins can be injected as part of page initialization or on-the-fly. + * + * @param {object} injectedNamesToPlugins Map from names to plugin modules. + * @internal + * @see {EventPluginHub.injection.injectEventPluginsByName} + */ + injectEventPluginsByName: function (injectedNamesToPlugins) { + var isOrderingDirty = false; + for (var pluginName in injectedNamesToPlugins) { + if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) { + continue; + } + var PluginModule = injectedNamesToPlugins[pluginName]; + if (!namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== PluginModule) { + !!namesToPlugins[pluginName] ? "production" !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject two different event plugins ' + 'using the same name, `%s`.', pluginName) : invariant(false) : undefined; + namesToPlugins[pluginName] = PluginModule; + isOrderingDirty = true; + } + } + if (isOrderingDirty) { + recomputePluginOrdering(); + } + }, + + /** + * Looks up the plugin for the supplied event. + * + * @param {object} event A synthetic event. + * @return {?object} The plugin that created the supplied event. + * @internal + */ + getPluginModuleForEvent: function (event) { + var dispatchConfig = event.dispatchConfig; + if (dispatchConfig.registrationName) { + return EventPluginRegistry.registrationNameModules[dispatchConfig.registrationName] || null; + } + for (var phase in dispatchConfig.phasedRegistrationNames) { + if (!dispatchConfig.phasedRegistrationNames.hasOwnProperty(phase)) { + continue; + } + var PluginModule = EventPluginRegistry.registrationNameModules[dispatchConfig.phasedRegistrationNames[phase]]; + if (PluginModule) { + return PluginModule; + } + } + return null; + }, + + /** + * Exposed for unit testing. + * @private + */ + _resetEventPlugins: function () { + EventPluginOrder = null; + for (var pluginName in namesToPlugins) { + if (namesToPlugins.hasOwnProperty(pluginName)) { + delete namesToPlugins[pluginName]; + } + } + EventPluginRegistry.plugins.length = 0; + + var eventNameDispatchConfigs = EventPluginRegistry.eventNameDispatchConfigs; + for (var eventName in eventNameDispatchConfigs) { + if (eventNameDispatchConfigs.hasOwnProperty(eventName)) { + delete eventNameDispatchConfigs[eventName]; + } + } + + var registrationNameModules = EventPluginRegistry.registrationNameModules; + for (var registrationName in registrationNameModules) { + if (registrationNameModules.hasOwnProperty(registrationName)) { + delete registrationNameModules[registrationName]; + } + } + } + +}; + +module.exports = EventPluginRegistry; +},{"161":161}],18:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule EventPluginUtils + */ + +'use strict'; + +var EventConstants = _dereq_(15); +var ReactErrorUtils = _dereq_(61); + +var invariant = _dereq_(161); +var warning = _dereq_(173); + +/** + * Injected dependencies: + */ + +/** + * - `Mount`: [required] Module that can convert between React dom IDs and + * actual node references. + */ +var injection = { + Mount: null, + injectMount: function (InjectedMount) { + injection.Mount = InjectedMount; + if ("production" !== 'production') { + "production" !== 'production' ? warning(InjectedMount && InjectedMount.getNode && InjectedMount.getID, 'EventPluginUtils.injection.injectMount(...): Injected Mount ' + 'module is missing getNode or getID.') : undefined; + } + } +}; + +var topLevelTypes = EventConstants.topLevelTypes; + +function isEndish(topLevelType) { + return topLevelType === topLevelTypes.topMouseUp || topLevelType === topLevelTypes.topTouchEnd || topLevelType === topLevelTypes.topTouchCancel; +} + +function isMoveish(topLevelType) { + return topLevelType === topLevelTypes.topMouseMove || topLevelType === topLevelTypes.topTouchMove; +} +function isStartish(topLevelType) { + return topLevelType === topLevelTypes.topMouseDown || topLevelType === topLevelTypes.topTouchStart; +} + +var validateEventDispatches; +if ("production" !== 'production') { + validateEventDispatches = function (event) { + var dispatchListeners = event._dispatchListeners; + var dispatchIDs = event._dispatchIDs; + + var listenersIsArr = Array.isArray(dispatchListeners); + var idsIsArr = Array.isArray(dispatchIDs); + var IDsLen = idsIsArr ? dispatchIDs.length : dispatchIDs ? 1 : 0; + var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0; + + "production" !== 'production' ? warning(idsIsArr === listenersIsArr && IDsLen === listenersLen, 'EventPluginUtils: Invalid `event`.') : undefined; + }; +} + +/** + * Dispatch the event to the listener. + * @param {SyntheticEvent} event SyntheticEvent to handle + * @param {boolean} simulated If the event is simulated (changes exn behavior) + * @param {function} listener Application-level callback + * @param {string} domID DOM id to pass to the callback. + */ +function executeDispatch(event, simulated, listener, domID) { + var type = event.type || 'unknown-event'; + event.currentTarget = injection.Mount.getNode(domID); + if (simulated) { + ReactErrorUtils.invokeGuardedCallbackWithCatch(type, listener, event, domID); + } else { + ReactErrorUtils.invokeGuardedCallback(type, listener, event, domID); + } + event.currentTarget = null; +} + +/** + * Standard/simple iteration through an event's collected dispatches. + */ +function executeDispatchesInOrder(event, simulated) { + var dispatchListeners = event._dispatchListeners; + var dispatchIDs = event._dispatchIDs; + if ("production" !== 'production') { + validateEventDispatches(event); + } + if (Array.isArray(dispatchListeners)) { + for (var i = 0; i < dispatchListeners.length; i++) { + if (event.isPropagationStopped()) { + break; + } + // Listeners and IDs are two parallel arrays that are always in sync. + executeDispatch(event, simulated, dispatchListeners[i], dispatchIDs[i]); + } + } else if (dispatchListeners) { + executeDispatch(event, simulated, dispatchListeners, dispatchIDs); + } + event._dispatchListeners = null; + event._dispatchIDs = null; +} + +/** + * Standard/simple iteration through an event's collected dispatches, but stops + * at the first dispatch execution returning true, and returns that id. + * + * @return {?string} id of the first dispatch execution who's listener returns + * true, or null if no listener returned true. + */ +function executeDispatchesInOrderStopAtTrueImpl(event) { + var dispatchListeners = event._dispatchListeners; + var dispatchIDs = event._dispatchIDs; + if ("production" !== 'production') { + validateEventDispatches(event); + } + if (Array.isArray(dispatchListeners)) { + for (var i = 0; i < dispatchListeners.length; i++) { + if (event.isPropagationStopped()) { + break; + } + // Listeners and IDs are two parallel arrays that are always in sync. + if (dispatchListeners[i](event, dispatchIDs[i])) { + return dispatchIDs[i]; + } + } + } else if (dispatchListeners) { + if (dispatchListeners(event, dispatchIDs)) { + return dispatchIDs; + } + } + return null; +} + +/** + * @see executeDispatchesInOrderStopAtTrueImpl + */ +function executeDispatchesInOrderStopAtTrue(event) { + var ret = executeDispatchesInOrderStopAtTrueImpl(event); + event._dispatchIDs = null; + event._dispatchListeners = null; + return ret; +} + +/** + * Execution of a "direct" dispatch - there must be at most one dispatch + * accumulated on the event or it is considered an error. It doesn't really make + * sense for an event with multiple dispatches (bubbled) to keep track of the + * return values at each dispatch execution, but it does tend to make sense when + * dealing with "direct" dispatches. + * + * @return {*} The return value of executing the single dispatch. + */ +function executeDirectDispatch(event) { + if ("production" !== 'production') { + validateEventDispatches(event); + } + var dispatchListener = event._dispatchListeners; + var dispatchID = event._dispatchIDs; + !!Array.isArray(dispatchListener) ? "production" !== 'production' ? invariant(false, 'executeDirectDispatch(...): Invalid `event`.') : invariant(false) : undefined; + var res = dispatchListener ? dispatchListener(event, dispatchID) : null; + event._dispatchListeners = null; + event._dispatchIDs = null; + return res; +} + +/** + * @param {SyntheticEvent} event + * @return {boolean} True iff number of dispatches accumulated is greater than 0. + */ +function hasDispatches(event) { + return !!event._dispatchListeners; +} + +/** + * General utilities that are useful in creating custom Event Plugins. + */ +var EventPluginUtils = { + isEndish: isEndish, + isMoveish: isMoveish, + isStartish: isStartish, + + executeDirectDispatch: executeDirectDispatch, + executeDispatchesInOrder: executeDispatchesInOrder, + executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue, + hasDispatches: hasDispatches, + + getNode: function (id) { + return injection.Mount.getNode(id); + }, + getID: function (node) { + return injection.Mount.getID(node); + }, + + injection: injection +}; + +module.exports = EventPluginUtils; +},{"15":15,"161":161,"173":173,"61":61}],19:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule EventPropagators + */ + +'use strict'; + +var EventConstants = _dereq_(15); +var EventPluginHub = _dereq_(16); + +var warning = _dereq_(173); + +var accumulateInto = _dereq_(115); +var forEachAccumulated = _dereq_(124); + +var PropagationPhases = EventConstants.PropagationPhases; +var getListener = EventPluginHub.getListener; + +/** + * Some event types have a notion of different registration names for different + * "phases" of propagation. This finds listeners by a given phase. + */ +function listenerAtPhase(id, event, propagationPhase) { + var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase]; + return getListener(id, registrationName); +} + +/** + * Tags a `SyntheticEvent` with dispatched listeners. Creating this function + * here, allows us to not have to bind or create functions for each event. + * Mutating the event's members allows us to not have to create a wrapping + * "dispatch" object that pairs the event with the listener. + */ +function accumulateDirectionalDispatches(domID, upwards, event) { + if ("production" !== 'production') { + "production" !== 'production' ? warning(domID, 'Dispatching id must not be null') : undefined; + } + var phase = upwards ? PropagationPhases.bubbled : PropagationPhases.captured; + var listener = listenerAtPhase(domID, event, phase); + if (listener) { + event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); + event._dispatchIDs = accumulateInto(event._dispatchIDs, domID); + } +} + +/** + * Collect dispatches (must be entirely collected before dispatching - see unit + * tests). Lazily allocate the array to conserve memory. We must loop through + * each event and perform the traversal for each one. We cannot perform a + * single traversal for the entire collection of events because each event may + * have a different target. + */ +function accumulateTwoPhaseDispatchesSingle(event) { + if (event && event.dispatchConfig.phasedRegistrationNames) { + EventPluginHub.injection.getInstanceHandle().traverseTwoPhase(event.dispatchMarker, accumulateDirectionalDispatches, event); + } +} + +/** + * Same as `accumulateTwoPhaseDispatchesSingle`, but skips over the targetID. + */ +function accumulateTwoPhaseDispatchesSingleSkipTarget(event) { + if (event && event.dispatchConfig.phasedRegistrationNames) { + EventPluginHub.injection.getInstanceHandle().traverseTwoPhaseSkipTarget(event.dispatchMarker, accumulateDirectionalDispatches, event); + } +} + +/** + * Accumulates without regard to direction, does not look for phased + * registration names. Same as `accumulateDirectDispatchesSingle` but without + * requiring that the `dispatchMarker` be the same as the dispatched ID. + */ +function accumulateDispatches(id, ignoredDirection, event) { + if (event && event.dispatchConfig.registrationName) { + var registrationName = event.dispatchConfig.registrationName; + var listener = getListener(id, registrationName); + if (listener) { + event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); + event._dispatchIDs = accumulateInto(event._dispatchIDs, id); + } + } +} + +/** + * Accumulates dispatches on an `SyntheticEvent`, but only for the + * `dispatchMarker`. + * @param {SyntheticEvent} event + */ +function accumulateDirectDispatchesSingle(event) { + if (event && event.dispatchConfig.registrationName) { + accumulateDispatches(event.dispatchMarker, null, event); + } +} + +function accumulateTwoPhaseDispatches(events) { + forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle); +} + +function accumulateTwoPhaseDispatchesSkipTarget(events) { + forEachAccumulated(events, accumulateTwoPhaseDispatchesSingleSkipTarget); +} + +function accumulateEnterLeaveDispatches(leave, enter, fromID, toID) { + EventPluginHub.injection.getInstanceHandle().traverseEnterLeave(fromID, toID, accumulateDispatches, leave, enter); +} + +function accumulateDirectDispatches(events) { + forEachAccumulated(events, accumulateDirectDispatchesSingle); +} + +/** + * A small set of propagation patterns, each of which will accept a small amount + * of information, and generate a set of "dispatch ready event objects" - which + * are sets of events that have already been annotated with a set of dispatched + * listener functions/ids. The API is designed this way to discourage these + * propagation strategies from actually executing the dispatches, since we + * always want to collect the entire set of dispatches before executing event a + * single one. + * + * @constructor EventPropagators + */ +var EventPropagators = { + accumulateTwoPhaseDispatches: accumulateTwoPhaseDispatches, + accumulateTwoPhaseDispatchesSkipTarget: accumulateTwoPhaseDispatchesSkipTarget, + accumulateDirectDispatches: accumulateDirectDispatches, + accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches +}; + +module.exports = EventPropagators; +},{"115":115,"124":124,"15":15,"16":16,"173":173}],20:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule FallbackCompositionState + * @typechecks static-only + */ + +'use strict'; + +var PooledClass = _dereq_(25); + +var assign = _dereq_(24); +var getTextContentAccessor = _dereq_(131); + +/** + * This helper class stores information about text content of a target node, + * allowing comparison of content before and after a given event. + * + * Identify the node where selection currently begins, then observe + * both its text content and its current position in the DOM. Since the + * browser may natively replace the target node during composition, we can + * use its position to find its replacement. + * + * @param {DOMEventTarget} root + */ +function FallbackCompositionState(root) { + this._root = root; + this._startText = this.getText(); + this._fallbackText = null; +} + +assign(FallbackCompositionState.prototype, { + destructor: function () { + this._root = null; + this._startText = null; + this._fallbackText = null; + }, + + /** + * Get current text of input. + * + * @return {string} + */ + getText: function () { + if ('value' in this._root) { + return this._root.value; + } + return this._root[getTextContentAccessor()]; + }, + + /** + * Determine the differing substring between the initially stored + * text content and the current content. + * + * @return {string} + */ + getData: function () { + if (this._fallbackText) { + return this._fallbackText; + } + + var start; + var startValue = this._startText; + var startLength = startValue.length; + var end; + var endValue = this.getText(); + var endLength = endValue.length; + + for (start = 0; start < startLength; start++) { + if (startValue[start] !== endValue[start]) { + break; + } + } + + var minEnd = startLength - start; + for (end = 1; end <= minEnd; end++) { + if (startValue[startLength - end] !== endValue[endLength - end]) { + break; + } + } + + var sliceTail = end > 1 ? 1 - end : undefined; + this._fallbackText = endValue.slice(start, sliceTail); + return this._fallbackText; + } +}); + +PooledClass.addPoolingTo(FallbackCompositionState); + +module.exports = FallbackCompositionState; +},{"131":131,"24":24,"25":25}],21:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule HTMLDOMPropertyConfig + */ + +'use strict'; + +var DOMProperty = _dereq_(10); +var ExecutionEnvironment = _dereq_(147); + +var MUST_USE_ATTRIBUTE = DOMProperty.injection.MUST_USE_ATTRIBUTE; +var MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY; +var HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE; +var HAS_SIDE_EFFECTS = DOMProperty.injection.HAS_SIDE_EFFECTS; +var HAS_NUMERIC_VALUE = DOMProperty.injection.HAS_NUMERIC_VALUE; +var HAS_POSITIVE_NUMERIC_VALUE = DOMProperty.injection.HAS_POSITIVE_NUMERIC_VALUE; +var HAS_OVERLOADED_BOOLEAN_VALUE = DOMProperty.injection.HAS_OVERLOADED_BOOLEAN_VALUE; + +var hasSVG; +if (ExecutionEnvironment.canUseDOM) { + var implementation = document.implementation; + hasSVG = implementation && implementation.hasFeature && implementation.hasFeature('http://www.w3.org/TR/SVG11/feature#BasicStructure', '1.1'); +} + +var HTMLDOMPropertyConfig = { + isCustomAttribute: RegExp.prototype.test.bind(/^(data|aria)-[a-z_][a-z\d_.\-]*$/), + Properties: { + /** + * Standard Properties + */ + accept: null, + acceptCharset: null, + accessKey: null, + action: null, + allowFullScreen: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, + allowTransparency: MUST_USE_ATTRIBUTE, + alt: null, + async: HAS_BOOLEAN_VALUE, + autoComplete: null, + // autoFocus is polyfilled/normalized by AutoFocusUtils + // autoFocus: HAS_BOOLEAN_VALUE, + autoPlay: HAS_BOOLEAN_VALUE, + capture: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, + cellPadding: null, + cellSpacing: null, + charSet: MUST_USE_ATTRIBUTE, + challenge: MUST_USE_ATTRIBUTE, + checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, + classID: MUST_USE_ATTRIBUTE, + // To set className on SVG elements, it's necessary to use .setAttribute; + // this works on HTML elements too in all browsers except IE8. Conveniently, + // IE8 doesn't support SVG and so we can simply use the attribute in + // browsers that support SVG and the property in browsers that don't, + // regardless of whether the element is HTML or SVG. + className: hasSVG ? MUST_USE_ATTRIBUTE : MUST_USE_PROPERTY, + cols: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE, + colSpan: null, + content: null, + contentEditable: null, + contextMenu: MUST_USE_ATTRIBUTE, + controls: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, + coords: null, + crossOrigin: null, + data: null, // For `<object />` acts as `src`. + dateTime: MUST_USE_ATTRIBUTE, + 'default': HAS_BOOLEAN_VALUE, + defer: HAS_BOOLEAN_VALUE, + dir: null, + disabled: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, + download: HAS_OVERLOADED_BOOLEAN_VALUE, + draggable: null, + encType: null, + form: MUST_USE_ATTRIBUTE, + formAction: MUST_USE_ATTRIBUTE, + formEncType: MUST_USE_ATTRIBUTE, + formMethod: MUST_USE_ATTRIBUTE, + formNoValidate: HAS_BOOLEAN_VALUE, + formTarget: MUST_USE_ATTRIBUTE, + frameBorder: MUST_USE_ATTRIBUTE, + headers: null, + height: MUST_USE_ATTRIBUTE, + hidden: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, + high: null, + href: null, + hrefLang: null, + htmlFor: null, + httpEquiv: null, + icon: null, + id: MUST_USE_PROPERTY, + inputMode: MUST_USE_ATTRIBUTE, + integrity: null, + is: MUST_USE_ATTRIBUTE, + keyParams: MUST_USE_ATTRIBUTE, + keyType: MUST_USE_ATTRIBUTE, + kind: null, + label: null, + lang: null, + list: MUST_USE_ATTRIBUTE, + loop: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, + low: null, + manifest: MUST_USE_ATTRIBUTE, + marginHeight: null, + marginWidth: null, + max: null, + maxLength: MUST_USE_ATTRIBUTE, + media: MUST_USE_ATTRIBUTE, + mediaGroup: null, + method: null, + min: null, + minLength: MUST_USE_ATTRIBUTE, + multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, + muted: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, + name: null, + nonce: MUST_USE_ATTRIBUTE, + noValidate: HAS_BOOLEAN_VALUE, + open: HAS_BOOLEAN_VALUE, + optimum: null, + pattern: null, + placeholder: null, + poster: null, + preload: null, + radioGroup: null, + readOnly: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, + rel: null, + required: HAS_BOOLEAN_VALUE, + reversed: HAS_BOOLEAN_VALUE, + role: MUST_USE_ATTRIBUTE, + rows: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE, + rowSpan: null, + sandbox: null, + scope: null, + scoped: HAS_BOOLEAN_VALUE, + scrolling: null, + seamless: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, + selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, + shape: null, + size: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE, + sizes: MUST_USE_ATTRIBUTE, + span: HAS_POSITIVE_NUMERIC_VALUE, + spellCheck: null, + src: null, + srcDoc: MUST_USE_PROPERTY, + srcLang: null, + srcSet: MUST_USE_ATTRIBUTE, + start: HAS_NUMERIC_VALUE, + step: null, + style: null, + summary: null, + tabIndex: null, + target: null, + title: null, + type: null, + useMap: null, + value: MUST_USE_PROPERTY | HAS_SIDE_EFFECTS, + width: MUST_USE_ATTRIBUTE, + wmode: MUST_USE_ATTRIBUTE, + wrap: null, + + /** + * RDFa Properties + */ + about: MUST_USE_ATTRIBUTE, + datatype: MUST_USE_ATTRIBUTE, + inlist: MUST_USE_ATTRIBUTE, + prefix: MUST_USE_ATTRIBUTE, + // property is also supported for OpenGraph in meta tags. + property: MUST_USE_ATTRIBUTE, + resource: MUST_USE_ATTRIBUTE, + 'typeof': MUST_USE_ATTRIBUTE, + vocab: MUST_USE_ATTRIBUTE, + + /** + * Non-standard Properties + */ + // autoCapitalize and autoCorrect are supported in Mobile Safari for + // keyboard hints. + autoCapitalize: MUST_USE_ATTRIBUTE, + autoCorrect: MUST_USE_ATTRIBUTE, + // autoSave allows WebKit/Blink to persist values of input fields on page reloads + autoSave: null, + // color is for Safari mask-icon link + color: null, + // itemProp, itemScope, itemType are for + // Microdata support. See http://schema.org/docs/gs.html + itemProp: MUST_USE_ATTRIBUTE, + itemScope: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, + itemType: MUST_USE_ATTRIBUTE, + // itemID and itemRef are for Microdata support as well but + // only specified in the the WHATWG spec document. See + // https://html.spec.whatwg.org/multipage/microdata.html#microdata-dom-api + itemID: MUST_USE_ATTRIBUTE, + itemRef: MUST_USE_ATTRIBUTE, + // results show looking glass icon and recent searches on input + // search fields in WebKit/Blink + results: null, + // IE-only attribute that specifies security restrictions on an iframe + // as an alternative to the sandbox attribute on IE<10 + security: MUST_USE_ATTRIBUTE, + // IE-only attribute that controls focus behavior + unselectable: MUST_USE_ATTRIBUTE + }, + DOMAttributeNames: { + acceptCharset: 'accept-charset', + className: 'class', + htmlFor: 'for', + httpEquiv: 'http-equiv' + }, + DOMPropertyNames: { + autoComplete: 'autocomplete', + autoFocus: 'autofocus', + autoPlay: 'autoplay', + autoSave: 'autosave', + // `encoding` is equivalent to `enctype`, IE8 lacks an `enctype` setter. + // http://www.w3.org/TR/html5/forms.html#dom-fs-encoding + encType: 'encoding', + hrefLang: 'hreflang', + radioGroup: 'radiogroup', + spellCheck: 'spellcheck', + srcDoc: 'srcdoc', + srcSet: 'srcset' + } +}; + +module.exports = HTMLDOMPropertyConfig; +},{"10":10,"147":147}],22:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule LinkedStateMixin + * @typechecks static-only + */ + +'use strict'; + +var ReactLink = _dereq_(70); +var ReactStateSetters = _dereq_(90); + +/** + * A simple mixin around ReactLink.forState(). + */ +var LinkedStateMixin = { + /** + * Create a ReactLink that's linked to part of this component's state. The + * ReactLink will have the current value of this.state[key] and will call + * setState() when a change is requested. + * + * @param {string} key state key to update. Note: you may want to use keyOf() + * if you're using Google Closure Compiler advanced mode. + * @return {ReactLink} ReactLink instance linking to the state. + */ + linkState: function (key) { + return new ReactLink(this.state[key], ReactStateSetters.createStateKeySetter(this, key)); + } +}; + +module.exports = LinkedStateMixin; +},{"70":70,"90":90}],23:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule LinkedValueUtils + * @typechecks static-only + */ + +'use strict'; + +var ReactPropTypes = _dereq_(82); +var ReactPropTypeLocations = _dereq_(81); + +var invariant = _dereq_(161); +var warning = _dereq_(173); + +var hasReadOnlyValue = { + 'button': true, + 'checkbox': true, + 'image': true, + 'hidden': true, + 'radio': true, + 'reset': true, + 'submit': true +}; + +function _assertSingleLink(inputProps) { + !(inputProps.checkedLink == null || inputProps.valueLink == null) ? "production" !== 'production' ? invariant(false, 'Cannot provide a checkedLink and a valueLink. If you want to use ' + 'checkedLink, you probably don\'t want to use valueLink and vice versa.') : invariant(false) : undefined; +} +function _assertValueLink(inputProps) { + _assertSingleLink(inputProps); + !(inputProps.value == null && inputProps.onChange == null) ? "production" !== 'production' ? invariant(false, 'Cannot provide a valueLink and a value or onChange event. If you want ' + 'to use value or onChange, you probably don\'t want to use valueLink.') : invariant(false) : undefined; +} + +function _assertCheckedLink(inputProps) { + _assertSingleLink(inputProps); + !(inputProps.checked == null && inputProps.onChange == null) ? "production" !== 'production' ? invariant(false, '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') : invariant(false) : undefined; +} + +var propTypes = { + value: function (props, propName, componentName) { + if (!props[propName] || hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled) { + return null; + } + return new Error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); + }, + checked: function (props, propName, componentName) { + if (!props[propName] || props.onChange || props.readOnly || props.disabled) { + return null; + } + return new Error('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`.'); + }, + onChange: ReactPropTypes.func +}; + +var loggedTypeFailures = {}; +function getDeclarationErrorAddendum(owner) { + if (owner) { + var name = owner.getName(); + if (name) { + return ' Check the render method of `' + name + '`.'; + } + } + return ''; +} + +/** + * Provide a linked `value` attribute for controlled forms. You should not use + * this outside of the ReactDOM controlled form components. + */ +var LinkedValueUtils = { + checkPropTypes: function (tagName, props, owner) { + for (var propName in propTypes) { + if (propTypes.hasOwnProperty(propName)) { + var error = propTypes[propName](props, propName, tagName, ReactPropTypeLocations.prop); + } + if (error instanceof Error && !(error.message in loggedTypeFailures)) { + // Only monitor this failure once because there tends to be a lot of the + // same error. + loggedTypeFailures[error.message] = true; + + var addendum = getDeclarationErrorAddendum(owner); + "production" !== 'production' ? warning(false, 'Failed form propType: %s%s', error.message, addendum) : undefined; + } + } + }, + + /** + * @param {object} inputProps Props for form component + * @return {*} current value of the input either from value prop or link. + */ + getValue: function (inputProps) { + if (inputProps.valueLink) { + _assertValueLink(inputProps); + return inputProps.valueLink.value; + } + return inputProps.value; + }, + + /** + * @param {object} inputProps Props for form component + * @return {*} current checked status of the input either from checked prop + * or link. + */ + getChecked: function (inputProps) { + if (inputProps.checkedLink) { + _assertCheckedLink(inputProps); + return inputProps.checkedLink.value; + } + return inputProps.checked; + }, + + /** + * @param {object} inputProps Props for form component + * @param {SyntheticEvent} event change event to handle + */ + executeOnChange: function (inputProps, event) { + if (inputProps.valueLink) { + _assertValueLink(inputProps); + return inputProps.valueLink.requestChange(event.target.value); + } else if (inputProps.checkedLink) { + _assertCheckedLink(inputProps); + return inputProps.checkedLink.requestChange(event.target.checked); + } else if (inputProps.onChange) { + return inputProps.onChange.call(undefined, event); + } + } +}; + +module.exports = LinkedValueUtils; +},{"161":161,"173":173,"81":81,"82":82}],24:[function(_dereq_,module,exports){ +/** + * Copyright 2014-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule Object.assign + */ + +// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign + +'use strict'; + +function assign(target, sources) { + if (target == null) { + throw new TypeError('Object.assign target cannot be null or undefined'); + } + + var to = Object(target); + var hasOwnProperty = Object.prototype.hasOwnProperty; + + for (var nextIndex = 1; nextIndex < arguments.length; nextIndex++) { + var nextSource = arguments[nextIndex]; + if (nextSource == null) { + continue; + } + + var from = Object(nextSource); + + // We don't currently support accessors nor proxies. Therefore this + // copy cannot throw. If we ever supported this then we must handle + // exceptions and side-effects. We don't support symbols so they won't + // be transferred. + + for (var key in from) { + if (hasOwnProperty.call(from, key)) { + to[key] = from[key]; + } + } + } + + return to; +} + +module.exports = assign; +},{}],25:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule PooledClass + */ + +'use strict'; + +var invariant = _dereq_(161); + +/** + * Static poolers. Several custom versions for each potential number of + * arguments. A completely generic pooler is easy to implement, but would + * require accessing the `arguments` object. In each of these, `this` refers to + * the Class itself, not an instance. If any others are needed, simply add them + * here, or in their own files. + */ +var oneArgumentPooler = function (copyFieldsFrom) { + var Klass = this; + if (Klass.instancePool.length) { + var instance = Klass.instancePool.pop(); + Klass.call(instance, copyFieldsFrom); + return instance; + } else { + return new Klass(copyFieldsFrom); + } +}; + +var twoArgumentPooler = function (a1, a2) { + var Klass = this; + if (Klass.instancePool.length) { + var instance = Klass.instancePool.pop(); + Klass.call(instance, a1, a2); + return instance; + } else { + return new Klass(a1, a2); + } +}; + +var threeArgumentPooler = function (a1, a2, a3) { + var Klass = this; + if (Klass.instancePool.length) { + var instance = Klass.instancePool.pop(); + Klass.call(instance, a1, a2, a3); + return instance; + } else { + return new Klass(a1, a2, a3); + } +}; + +var fourArgumentPooler = function (a1, a2, a3, a4) { + var Klass = this; + if (Klass.instancePool.length) { + var instance = Klass.instancePool.pop(); + Klass.call(instance, a1, a2, a3, a4); + return instance; + } else { + return new Klass(a1, a2, a3, a4); + } +}; + +var fiveArgumentPooler = function (a1, a2, a3, a4, a5) { + var Klass = this; + if (Klass.instancePool.length) { + var instance = Klass.instancePool.pop(); + Klass.call(instance, a1, a2, a3, a4, a5); + return instance; + } else { + return new Klass(a1, a2, a3, a4, a5); + } +}; + +var standardReleaser = function (instance) { + var Klass = this; + !(instance instanceof Klass) ? "production" !== 'production' ? invariant(false, 'Trying to release an instance into a pool of a different type.') : invariant(false) : undefined; + instance.destructor(); + if (Klass.instancePool.length < Klass.poolSize) { + Klass.instancePool.push(instance); + } +}; + +var DEFAULT_POOL_SIZE = 10; +var DEFAULT_POOLER = oneArgumentPooler; + +/** + * Augments `CopyConstructor` to be a poolable class, augmenting only the class + * itself (statically) not adding any prototypical fields. Any CopyConstructor + * you give this may have a `poolSize` property, and will look for a + * prototypical `destructor` on instances (optional). + * + * @param {Function} CopyConstructor Constructor that can be used to reset. + * @param {Function} pooler Customizable pooler. + */ +var addPoolingTo = function (CopyConstructor, pooler) { + var NewKlass = CopyConstructor; + NewKlass.instancePool = []; + NewKlass.getPooled = pooler || DEFAULT_POOLER; + if (!NewKlass.poolSize) { + NewKlass.poolSize = DEFAULT_POOL_SIZE; + } + NewKlass.release = standardReleaser; + return NewKlass; +}; + +var PooledClass = { + addPoolingTo: addPoolingTo, + oneArgumentPooler: oneArgumentPooler, + twoArgumentPooler: twoArgumentPooler, + threeArgumentPooler: threeArgumentPooler, + fourArgumentPooler: fourArgumentPooler, + fiveArgumentPooler: fiveArgumentPooler +}; + +module.exports = PooledClass; +},{"161":161}],26:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule React + */ + +'use strict'; + +var ReactDOM = _dereq_(40); +var ReactDOMServer = _dereq_(50); +var ReactIsomorphic = _dereq_(69); + +var assign = _dereq_(24); +var deprecated = _dereq_(120); + +// `version` will be added here by ReactIsomorphic. +var React = {}; + +assign(React, ReactIsomorphic); + +assign(React, { + // ReactDOM + findDOMNode: deprecated('findDOMNode', 'ReactDOM', 'react-dom', ReactDOM, ReactDOM.findDOMNode), + render: deprecated('render', 'ReactDOM', 'react-dom', ReactDOM, ReactDOM.render), + unmountComponentAtNode: deprecated('unmountComponentAtNode', 'ReactDOM', 'react-dom', ReactDOM, ReactDOM.unmountComponentAtNode), + + // ReactDOMServer + renderToString: deprecated('renderToString', 'ReactDOMServer', 'react-dom/server', ReactDOMServer, ReactDOMServer.renderToString), + renderToStaticMarkup: deprecated('renderToStaticMarkup', 'ReactDOMServer', 'react-dom/server', ReactDOMServer, ReactDOMServer.renderToStaticMarkup) +}); + +React.__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactDOM; +React.__SECRET_DOM_SERVER_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactDOMServer; + +module.exports = React; +},{"120":120,"24":24,"40":40,"50":50,"69":69}],27:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactBrowserComponentMixin + */ + +'use strict'; + +var ReactInstanceMap = _dereq_(68); + +var findDOMNode = _dereq_(122); +var warning = _dereq_(173); + +var didWarnKey = '_getDOMNodeDidWarn'; + +var ReactBrowserComponentMixin = { + /** + * Returns the DOM node rendered by this component. + * + * @return {DOMElement} The root node of this component. + * @final + * @protected + */ + getDOMNode: function () { + "production" !== 'production' ? warning(this.constructor[didWarnKey], '%s.getDOMNode(...) is deprecated. Please use ' + 'ReactDOM.findDOMNode(instance) instead.', ReactInstanceMap.get(this).getName() || this.tagName || 'Unknown') : undefined; + this.constructor[didWarnKey] = true; + return findDOMNode(this); + } +}; + +module.exports = ReactBrowserComponentMixin; +},{"122":122,"173":173,"68":68}],28:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactBrowserEventEmitter + * @typechecks static-only + */ + +'use strict'; + +var EventConstants = _dereq_(15); +var EventPluginHub = _dereq_(16); +var EventPluginRegistry = _dereq_(17); +var ReactEventEmitterMixin = _dereq_(62); +var ReactPerf = _dereq_(78); +var ViewportMetrics = _dereq_(114); + +var assign = _dereq_(24); +var isEventSupported = _dereq_(133); + +/** + * Summary of `ReactBrowserEventEmitter` event handling: + * + * - Top-level delegation is used to trap most native browser events. This + * may only occur in the main thread and is the responsibility of + * ReactEventListener, which is injected and can therefore support pluggable + * event sources. This is the only work that occurs in the main thread. + * + * - We normalize and de-duplicate events to account for browser quirks. This + * may be done in the worker thread. + * + * - Forward these native events (with the associated top-level type used to + * trap it) to `EventPluginHub`, which in turn will ask plugins if they want + * to extract any synthetic events. + * + * - The `EventPluginHub` will then process each event by annotating them with + * "dispatches", a sequence of listeners and IDs that care about that event. + * + * - The `EventPluginHub` then dispatches the events. + * + * Overview of React and the event system: + * + * +------------+ . + * | DOM | . + * +------------+ . + * | . + * v . + * +------------+ . + * | ReactEvent | . + * | Listener | . + * +------------+ . +-----------+ + * | . +--------+|SimpleEvent| + * | . | |Plugin | + * +-----|------+ . v +-----------+ + * | | | . +--------------+ +------------+ + * | +-----------.--->|EventPluginHub| | Event | + * | | . | | +-----------+ | Propagators| + * | ReactEvent | . | | |TapEvent | |------------| + * | Emitter | . | |<---+|Plugin | |other plugin| + * | | . | | +-----------+ | utilities | + * | +-----------.--->| | +------------+ + * | | | . +--------------+ + * +-----|------+ . ^ +-----------+ + * | . | |Enter/Leave| + * + . +-------+|Plugin | + * +-------------+ . +-----------+ + * | application | . + * |-------------| . + * | | . + * | | . + * +-------------+ . + * . + * React Core . General Purpose Event Plugin System + */ + +var alreadyListeningTo = {}; +var isMonitoringScrollValue = false; +var reactTopListenersCounter = 0; + +// For events like 'submit' which don't consistently bubble (which we trap at a +// lower node than `document`), binding at `document` would cause duplicate +// events so we don't include them here +var topEventMapping = { + topAbort: 'abort', + topBlur: 'blur', + topCanPlay: 'canplay', + topCanPlayThrough: 'canplaythrough', + topChange: 'change', + topClick: 'click', + topCompositionEnd: 'compositionend', + topCompositionStart: 'compositionstart', + topCompositionUpdate: 'compositionupdate', + topContextMenu: 'contextmenu', + topCopy: 'copy', + topCut: 'cut', + topDoubleClick: 'dblclick', + topDrag: 'drag', + topDragEnd: 'dragend', + topDragEnter: 'dragenter', + topDragExit: 'dragexit', + topDragLeave: 'dragleave', + topDragOver: 'dragover', + topDragStart: 'dragstart', + topDrop: 'drop', + topDurationChange: 'durationchange', + topEmptied: 'emptied', + topEncrypted: 'encrypted', + topEnded: 'ended', + topError: 'error', + topFocus: 'focus', + topInput: 'input', + topKeyDown: 'keydown', + topKeyPress: 'keypress', + topKeyUp: 'keyup', + topLoadedData: 'loadeddata', + topLoadedMetadata: 'loadedmetadata', + topLoadStart: 'loadstart', + topMouseDown: 'mousedown', + topMouseMove: 'mousemove', + topMouseOut: 'mouseout', + topMouseOver: 'mouseover', + topMouseUp: 'mouseup', + topPaste: 'paste', + topPause: 'pause', + topPlay: 'play', + topPlaying: 'playing', + topProgress: 'progress', + topRateChange: 'ratechange', + topScroll: 'scroll', + topSeeked: 'seeked', + topSeeking: 'seeking', + topSelectionChange: 'selectionchange', + topStalled: 'stalled', + topSuspend: 'suspend', + topTextInput: 'textInput', + topTimeUpdate: 'timeupdate', + topTouchCancel: 'touchcancel', + topTouchEnd: 'touchend', + topTouchMove: 'touchmove', + topTouchStart: 'touchstart', + topVolumeChange: 'volumechange', + topWaiting: 'waiting', + topWheel: 'wheel' +}; + +/** + * To ensure no conflicts with other potential React instances on the page + */ +var topListenersIDKey = '_reactListenersID' + String(Math.random()).slice(2); + +function getListeningForDocument(mountAt) { + // In IE8, `mountAt` is a host object and doesn't have `hasOwnProperty` + // directly. + if (!Object.prototype.hasOwnProperty.call(mountAt, topListenersIDKey)) { + mountAt[topListenersIDKey] = reactTopListenersCounter++; + alreadyListeningTo[mountAt[topListenersIDKey]] = {}; + } + return alreadyListeningTo[mountAt[topListenersIDKey]]; +} + +/** + * `ReactBrowserEventEmitter` is used to attach top-level event listeners. For + * example: + * + * ReactBrowserEventEmitter.putListener('myID', 'onClick', myFunction); + * + * This would allocate a "registration" of `('onClick', myFunction)` on 'myID'. + * + * @internal + */ +var ReactBrowserEventEmitter = assign({}, ReactEventEmitterMixin, { + + /** + * Injectable event backend + */ + ReactEventListener: null, + + injection: { + /** + * @param {object} ReactEventListener + */ + injectReactEventListener: function (ReactEventListener) { + ReactEventListener.setHandleTopLevel(ReactBrowserEventEmitter.handleTopLevel); + ReactBrowserEventEmitter.ReactEventListener = ReactEventListener; + } + }, + + /** + * Sets whether or not any created callbacks should be enabled. + * + * @param {boolean} enabled True if callbacks should be enabled. + */ + setEnabled: function (enabled) { + if (ReactBrowserEventEmitter.ReactEventListener) { + ReactBrowserEventEmitter.ReactEventListener.setEnabled(enabled); + } + }, + + /** + * @return {boolean} True if callbacks are enabled. + */ + isEnabled: function () { + return !!(ReactBrowserEventEmitter.ReactEventListener && ReactBrowserEventEmitter.ReactEventListener.isEnabled()); + }, + + /** + * We listen for bubbled touch events on the document object. + * + * Firefox v8.01 (and possibly others) exhibited strange behavior when + * mounting `onmousemove` events at some node that was not the document + * element. The symptoms were that if your mouse is not moving over something + * contained within that mount point (for example on the background) the + * top-level listeners for `onmousemove` won't be called. However, if you + * register the `mousemove` on the document object, then it will of course + * catch all `mousemove`s. This along with iOS quirks, justifies restricting + * top-level listeners to the document object only, at least for these + * movement types of events and possibly all events. + * + * @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html + * + * Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but + * they bubble to document. + * + * @param {string} registrationName Name of listener (e.g. `onClick`). + * @param {object} contentDocumentHandle Document which owns the container + */ + listenTo: function (registrationName, contentDocumentHandle) { + var mountAt = contentDocumentHandle; + var isListening = getListeningForDocument(mountAt); + var dependencies = EventPluginRegistry.registrationNameDependencies[registrationName]; + + var topLevelTypes = EventConstants.topLevelTypes; + for (var i = 0; i < dependencies.length; i++) { + var dependency = dependencies[i]; + if (!(isListening.hasOwnProperty(dependency) && isListening[dependency])) { + if (dependency === topLevelTypes.topWheel) { + if (isEventSupported('wheel')) { + ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'wheel', mountAt); + } else if (isEventSupported('mousewheel')) { + ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'mousewheel', mountAt); + } else { + // Firefox needs to capture a different mouse scroll event. + // @see http://www.quirksmode.org/dom/events/tests/scroll.html + ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'DOMMouseScroll', mountAt); + } + } else if (dependency === topLevelTypes.topScroll) { + + if (isEventSupported('scroll', true)) { + ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topScroll, 'scroll', mountAt); + } else { + ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topScroll, 'scroll', ReactBrowserEventEmitter.ReactEventListener.WINDOW_HANDLE); + } + } else if (dependency === topLevelTypes.topFocus || dependency === topLevelTypes.topBlur) { + + if (isEventSupported('focus', true)) { + ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topFocus, 'focus', mountAt); + ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topBlur, 'blur', mountAt); + } else if (isEventSupported('focusin')) { + // IE has `focusin` and `focusout` events which bubble. + // @see http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html + ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topFocus, 'focusin', mountAt); + ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topBlur, 'focusout', mountAt); + } + + // to make sure blur and focus event listeners are only attached once + isListening[topLevelTypes.topBlur] = true; + isListening[topLevelTypes.topFocus] = true; + } else if (topEventMapping.hasOwnProperty(dependency)) { + ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(dependency, topEventMapping[dependency], mountAt); + } + + isListening[dependency] = true; + } + } + }, + + trapBubbledEvent: function (topLevelType, handlerBaseName, handle) { + return ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelType, handlerBaseName, handle); + }, + + trapCapturedEvent: function (topLevelType, handlerBaseName, handle) { + return ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelType, handlerBaseName, handle); + }, + + /** + * Listens to window scroll and resize events. We cache scroll values so that + * application code can access them without triggering reflows. + * + * NOTE: Scroll events do not bubble. + * + * @see http://www.quirksmode.org/dom/events/scroll.html + */ + ensureScrollValueMonitoring: function () { + if (!isMonitoringScrollValue) { + var refresh = ViewportMetrics.refreshScrollValues; + ReactBrowserEventEmitter.ReactEventListener.monitorScrollValue(refresh); + isMonitoringScrollValue = true; + } + }, + + eventNameDispatchConfigs: EventPluginHub.eventNameDispatchConfigs, + + registrationNameModules: EventPluginHub.registrationNameModules, + + putListener: EventPluginHub.putListener, + + getListener: EventPluginHub.getListener, + + deleteListener: EventPluginHub.deleteListener, + + deleteAllListeners: EventPluginHub.deleteAllListeners + +}); + +ReactPerf.measureMethods(ReactBrowserEventEmitter, 'ReactBrowserEventEmitter', { + putListener: 'putListener', + deleteListener: 'deleteListener' +}); + +module.exports = ReactBrowserEventEmitter; +},{"114":114,"133":133,"15":15,"16":16,"17":17,"24":24,"62":62,"78":78}],29:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @typechecks + * @providesModule ReactCSSTransitionGroup + */ + +'use strict'; + +var React = _dereq_(26); + +var assign = _dereq_(24); + +var ReactTransitionGroup = _dereq_(94); +var ReactCSSTransitionGroupChild = _dereq_(30); + +function createTransitionTimeoutPropValidator(transitionType) { + var timeoutPropName = 'transition' + transitionType + 'Timeout'; + var enabledPropName = 'transition' + transitionType; + + return function (props) { + // If the transition is enabled + if (props[enabledPropName]) { + // If no timeout duration is provided + if (props[timeoutPropName] == null) { + return new Error(timeoutPropName + ' wasn\'t supplied to ReactCSSTransitionGroup: ' + 'this can cause unreliable animations and won\'t be supported in ' + 'a future version of React. See ' + 'https://fb.me/react-animation-transition-group-timeout for more ' + 'information.'); + + // If the duration isn't a number + } else if (typeof props[timeoutPropName] !== 'number') { + return new Error(timeoutPropName + ' must be a number (in milliseconds)'); + } + } + }; +} + +var ReactCSSTransitionGroup = React.createClass({ + displayName: 'ReactCSSTransitionGroup', + + propTypes: { + transitionName: ReactCSSTransitionGroupChild.propTypes.name, + + transitionAppear: React.PropTypes.bool, + transitionEnter: React.PropTypes.bool, + transitionLeave: React.PropTypes.bool, + transitionAppearTimeout: createTransitionTimeoutPropValidator('Appear'), + transitionEnterTimeout: createTransitionTimeoutPropValidator('Enter'), + transitionLeaveTimeout: createTransitionTimeoutPropValidator('Leave') + }, + + getDefaultProps: function () { + return { + transitionAppear: false, + transitionEnter: true, + transitionLeave: true + }; + }, + + _wrapChild: function (child) { + // We need to provide this childFactory so that + // ReactCSSTransitionGroupChild can receive updates to name, enter, and + // leave while it is leaving. + return React.createElement(ReactCSSTransitionGroupChild, { + name: this.props.transitionName, + appear: this.props.transitionAppear, + enter: this.props.transitionEnter, + leave: this.props.transitionLeave, + appearTimeout: this.props.transitionAppearTimeout, + enterTimeout: this.props.transitionEnterTimeout, + leaveTimeout: this.props.transitionLeaveTimeout + }, child); + }, + + render: function () { + return React.createElement(ReactTransitionGroup, assign({}, this.props, { childFactory: this._wrapChild })); + } +}); + +module.exports = ReactCSSTransitionGroup; +},{"24":24,"26":26,"30":30,"94":94}],30:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @typechecks + * @providesModule ReactCSSTransitionGroupChild + */ + +'use strict'; + +var React = _dereq_(26); +var ReactDOM = _dereq_(40); + +var CSSCore = _dereq_(145); +var ReactTransitionEvents = _dereq_(93); + +var onlyChild = _dereq_(135); + +// We don't remove the element from the DOM until we receive an animationend or +// transitionend event. If the user screws up and forgets to add an animation +// their node will be stuck in the DOM forever, so we detect if an animation +// does not start and if it doesn't, we just call the end listener immediately. +var TICK = 17; + +var ReactCSSTransitionGroupChild = React.createClass({ + displayName: 'ReactCSSTransitionGroupChild', + + propTypes: { + name: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.shape({ + enter: React.PropTypes.string, + leave: React.PropTypes.string, + active: React.PropTypes.string + }), React.PropTypes.shape({ + enter: React.PropTypes.string, + enterActive: React.PropTypes.string, + leave: React.PropTypes.string, + leaveActive: React.PropTypes.string, + appear: React.PropTypes.string, + appearActive: React.PropTypes.string + })]).isRequired, + + // Once we require timeouts to be specified, we can remove the + // boolean flags (appear etc.) and just accept a number + // or a bool for the timeout flags (appearTimeout etc.) + appear: React.PropTypes.bool, + enter: React.PropTypes.bool, + leave: React.PropTypes.bool, + appearTimeout: React.PropTypes.number, + enterTimeout: React.PropTypes.number, + leaveTimeout: React.PropTypes.number + }, + + transition: function (animationType, finishCallback, userSpecifiedDelay) { + var node = ReactDOM.findDOMNode(this); + + if (!node) { + if (finishCallback) { + finishCallback(); + } + return; + } + + var className = this.props.name[animationType] || this.props.name + '-' + animationType; + var activeClassName = this.props.name[animationType + 'Active'] || className + '-active'; + var timeout = null; + + var endListener = function (e) { + if (e && e.target !== node) { + return; + } + + clearTimeout(timeout); + + CSSCore.removeClass(node, className); + CSSCore.removeClass(node, activeClassName); + + ReactTransitionEvents.removeEndEventListener(node, endListener); + + // Usually this optional callback is used for informing an owner of + // a leave animation and telling it to remove the child. + if (finishCallback) { + finishCallback(); + } + }; + + CSSCore.addClass(node, className); + + // Need to do this to actually trigger a transition. + this.queueClass(activeClassName); + + // If the user specified a timeout delay. + if (userSpecifiedDelay) { + // Clean-up the animation after the specified delay + timeout = setTimeout(endListener, userSpecifiedDelay); + this.transitionTimeouts.push(timeout); + } else { + // DEPRECATED: this listener will be removed in a future version of react + ReactTransitionEvents.addEndEventListener(node, endListener); + } + }, + + queueClass: function (className) { + this.classNameQueue.push(className); + + if (!this.timeout) { + this.timeout = setTimeout(this.flushClassNameQueue, TICK); + } + }, + + flushClassNameQueue: function () { + if (this.isMounted()) { + this.classNameQueue.forEach(CSSCore.addClass.bind(CSSCore, ReactDOM.findDOMNode(this))); + } + this.classNameQueue.length = 0; + this.timeout = null; + }, + + componentWillMount: function () { + this.classNameQueue = []; + this.transitionTimeouts = []; + }, + + componentWillUnmount: function () { + if (this.timeout) { + clearTimeout(this.timeout); + } + this.transitionTimeouts.forEach(function (timeout) { + clearTimeout(timeout); + }); + }, + + componentWillAppear: function (done) { + if (this.props.appear) { + this.transition('appear', done, this.props.appearTimeout); + } else { + done(); + } + }, + + componentWillEnter: function (done) { + if (this.props.enter) { + this.transition('enter', done, this.props.enterTimeout); + } else { + done(); + } + }, + + componentWillLeave: function (done) { + if (this.props.leave) { + this.transition('leave', done, this.props.leaveTimeout); + } else { + done(); + } + }, + + render: function () { + return onlyChild(this.props.children); + } +}); + +module.exports = ReactCSSTransitionGroupChild; +},{"135":135,"145":145,"26":26,"40":40,"93":93}],31:[function(_dereq_,module,exports){ +/** + * Copyright 2014-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactChildReconciler + * @typechecks static-only + */ + +'use strict'; + +var ReactReconciler = _dereq_(84); + +var instantiateReactComponent = _dereq_(132); +var shouldUpdateReactComponent = _dereq_(141); +var traverseAllChildren = _dereq_(142); +var warning = _dereq_(173); + +function instantiateChild(childInstances, child, name) { + // We found a component instance. + var keyUnique = childInstances[name] === undefined; + if ("production" !== 'production') { + "production" !== 'production' ? warning(keyUnique, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.', name) : undefined; + } + if (child != null && keyUnique) { + childInstances[name] = instantiateReactComponent(child, null); + } +} + +/** + * ReactChildReconciler provides helpers for initializing or updating a set of + * children. Its output is suitable for passing it onto ReactMultiChild which + * does diffed reordering and insertion. + */ +var ReactChildReconciler = { + /** + * Generates a "mount image" for each of the supplied children. In the case + * of `ReactDOMComponent`, a mount image is a string of markup. + * + * @param {?object} nestedChildNodes Nested child maps. + * @return {?object} A set of child instances. + * @internal + */ + instantiateChildren: function (nestedChildNodes, transaction, context) { + if (nestedChildNodes == null) { + return null; + } + var childInstances = {}; + traverseAllChildren(nestedChildNodes, instantiateChild, childInstances); + return childInstances; + }, + + /** + * Updates the rendered children and returns a new set of children. + * + * @param {?object} prevChildren Previously initialized set of children. + * @param {?object} nextChildren Flat child element maps. + * @param {ReactReconcileTransaction} transaction + * @param {object} context + * @return {?object} A new set of child instances. + * @internal + */ + updateChildren: function (prevChildren, nextChildren, transaction, context) { + // We currently don't have a way to track moves here but if we use iterators + // instead of for..in we can zip the iterators and check if an item has + // moved. + // TODO: If nothing has changed, return the prevChildren object so that we + // can quickly bailout if nothing has changed. + if (!nextChildren && !prevChildren) { + return null; + } + var name; + for (name in nextChildren) { + if (!nextChildren.hasOwnProperty(name)) { + continue; + } + var prevChild = prevChildren && prevChildren[name]; + var prevElement = prevChild && prevChild._currentElement; + var nextElement = nextChildren[name]; + if (prevChild != null && shouldUpdateReactComponent(prevElement, nextElement)) { + ReactReconciler.receiveComponent(prevChild, nextElement, transaction, context); + nextChildren[name] = prevChild; + } else { + if (prevChild) { + ReactReconciler.unmountComponent(prevChild, name); + } + // The child must be instantiated before it's mounted. + var nextChildInstance = instantiateReactComponent(nextElement, null); + nextChildren[name] = nextChildInstance; + } + } + // Unmount children that are no longer present. + for (name in prevChildren) { + if (prevChildren.hasOwnProperty(name) && !(nextChildren && nextChildren.hasOwnProperty(name))) { + ReactReconciler.unmountComponent(prevChildren[name]); + } + } + return nextChildren; + }, + + /** + * Unmounts all rendered children. This should be used to clean up children + * when this component is unmounted. + * + * @param {?object} renderedChildren Previously initialized set of children. + * @internal + */ + unmountChildren: function (renderedChildren) { + for (var name in renderedChildren) { + if (renderedChildren.hasOwnProperty(name)) { + var renderedChild = renderedChildren[name]; + ReactReconciler.unmountComponent(renderedChild); + } + } + } + +}; + +module.exports = ReactChildReconciler; +},{"132":132,"141":141,"142":142,"173":173,"84":84}],32:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactChildren + */ + +'use strict'; + +var PooledClass = _dereq_(25); +var ReactElement = _dereq_(57); + +var emptyFunction = _dereq_(153); +var traverseAllChildren = _dereq_(142); + +var twoArgumentPooler = PooledClass.twoArgumentPooler; +var fourArgumentPooler = PooledClass.fourArgumentPooler; + +var userProvidedKeyEscapeRegex = /\/(?!\/)/g; +function escapeUserProvidedKey(text) { + return ('' + text).replace(userProvidedKeyEscapeRegex, '//'); +} + +/** + * PooledClass representing the bookkeeping associated with performing a child + * traversal. Allows avoiding binding callbacks. + * + * @constructor ForEachBookKeeping + * @param {!function} forEachFunction Function to perform traversal with. + * @param {?*} forEachContext Context to perform context with. + */ +function ForEachBookKeeping(forEachFunction, forEachContext) { + this.func = forEachFunction; + this.context = forEachContext; + this.count = 0; +} +ForEachBookKeeping.prototype.destructor = function () { + this.func = null; + this.context = null; + this.count = 0; +}; +PooledClass.addPoolingTo(ForEachBookKeeping, twoArgumentPooler); + +function forEachSingleChild(bookKeeping, child, name) { + var func = bookKeeping.func; + var context = bookKeeping.context; + + func.call(context, child, bookKeeping.count++); +} + +/** + * Iterates through children that are typically specified as `props.children`. + * + * The provided forEachFunc(child, index) will be called for each + * leaf child. + * + * @param {?*} children Children tree container. + * @param {function(*, int)} forEachFunc + * @param {*} forEachContext Context for forEachContext. + */ +function forEachChildren(children, forEachFunc, forEachContext) { + if (children == null) { + return children; + } + var traverseContext = ForEachBookKeeping.getPooled(forEachFunc, forEachContext); + traverseAllChildren(children, forEachSingleChild, traverseContext); + ForEachBookKeeping.release(traverseContext); +} + +/** + * PooledClass representing the bookkeeping associated with performing a child + * mapping. Allows avoiding binding callbacks. + * + * @constructor MapBookKeeping + * @param {!*} mapResult Object containing the ordered map of results. + * @param {!function} mapFunction Function to perform mapping with. + * @param {?*} mapContext Context to perform mapping with. + */ +function MapBookKeeping(mapResult, keyPrefix, mapFunction, mapContext) { + this.result = mapResult; + this.keyPrefix = keyPrefix; + this.func = mapFunction; + this.context = mapContext; + this.count = 0; +} +MapBookKeeping.prototype.destructor = function () { + this.result = null; + this.keyPrefix = null; + this.func = null; + this.context = null; + this.count = 0; +}; +PooledClass.addPoolingTo(MapBookKeeping, fourArgumentPooler); + +function mapSingleChildIntoContext(bookKeeping, child, childKey) { + var result = bookKeeping.result; + var keyPrefix = bookKeeping.keyPrefix; + var func = bookKeeping.func; + var context = bookKeeping.context; + + var mappedChild = func.call(context, child, bookKeeping.count++); + if (Array.isArray(mappedChild)) { + mapIntoWithKeyPrefixInternal(mappedChild, result, childKey, emptyFunction.thatReturnsArgument); + } else if (mappedChild != null) { + if (ReactElement.isValidElement(mappedChild)) { + mappedChild = ReactElement.cloneAndReplaceKey(mappedChild, + // Keep both the (mapped) and old keys if they differ, just as + // traverseAllChildren used to do for objects as children + keyPrefix + (mappedChild !== child ? escapeUserProvidedKey(mappedChild.key || '') + '/' : '') + childKey); + } + result.push(mappedChild); + } +} + +function mapIntoWithKeyPrefixInternal(children, array, prefix, func, context) { + var escapedPrefix = ''; + if (prefix != null) { + escapedPrefix = escapeUserProvidedKey(prefix) + '/'; + } + var traverseContext = MapBookKeeping.getPooled(array, escapedPrefix, func, context); + traverseAllChildren(children, mapSingleChildIntoContext, traverseContext); + MapBookKeeping.release(traverseContext); +} + +/** + * Maps children that are typically specified as `props.children`. + * + * The provided mapFunction(child, key, index) will be called for each + * leaf child. + * + * @param {?*} children Children tree container. + * @param {function(*, int)} func The map function. + * @param {*} context Context for mapFunction. + * @return {object} Object containing the ordered map of results. + */ +function mapChildren(children, func, context) { + if (children == null) { + return children; + } + var result = []; + mapIntoWithKeyPrefixInternal(children, result, null, func, context); + return result; +} + +function forEachSingleChildDummy(traverseContext, child, name) { + return null; +} + +/** + * Count the number of children that are typically specified as + * `props.children`. + * + * @param {?*} children Children tree container. + * @return {number} The number of children. + */ +function countChildren(children, context) { + return traverseAllChildren(children, forEachSingleChildDummy, null); +} + +/** + * Flatten a children object (typically specified as `props.children`) and + * return an array with appropriately re-keyed children. + */ +function toArray(children) { + var result = []; + mapIntoWithKeyPrefixInternal(children, result, null, emptyFunction.thatReturnsArgument); + return result; +} + +var ReactChildren = { + forEach: forEachChildren, + map: mapChildren, + mapIntoWithKeyPrefixInternal: mapIntoWithKeyPrefixInternal, + count: countChildren, + toArray: toArray +}; + +module.exports = ReactChildren; +},{"142":142,"153":153,"25":25,"57":57}],33:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactClass + */ + +'use strict'; + +var ReactComponent = _dereq_(34); +var ReactElement = _dereq_(57); +var ReactPropTypeLocations = _dereq_(81); +var ReactPropTypeLocationNames = _dereq_(80); +var ReactNoopUpdateQueue = _dereq_(76); + +var assign = _dereq_(24); +var emptyObject = _dereq_(154); +var invariant = _dereq_(161); +var keyMirror = _dereq_(165); +var keyOf = _dereq_(166); +var warning = _dereq_(173); + +var MIXINS_KEY = keyOf({ mixins: null }); + +/** + * Policies that describe methods in `ReactClassInterface`. + */ +var SpecPolicy = keyMirror({ + /** + * These methods may be defined only once by the class specification or mixin. + */ + DEFINE_ONCE: null, + /** + * These methods may be defined by both the class specification and mixins. + * Subsequent definitions will be chained. These methods must return void. + */ + DEFINE_MANY: null, + /** + * These methods are overriding the base class. + */ + OVERRIDE_BASE: null, + /** + * These methods are similar to DEFINE_MANY, except we assume they return + * objects. We try to merge the keys of the return values of all the mixed in + * functions. If there is a key conflict we throw. + */ + DEFINE_MANY_MERGED: null +}); + +var injectedMixins = []; + +var warnedSetProps = false; +function warnSetProps() { + if (!warnedSetProps) { + warnedSetProps = true; + "production" !== 'production' ? warning(false, 'setProps(...) and replaceProps(...) are deprecated. ' + 'Instead, call render again at the top level.') : undefined; + } +} + +/** + * Composite components are higher-level components that compose other composite + * or native components. + * + * To create a new type of `ReactClass`, pass a specification of + * your new class to `React.createClass`. The only requirement of your class + * specification is that you implement a `render` method. + * + * var MyComponent = React.createClass({ + * render: function() { + * return <div>Hello World</div>; + * } + * }); + * + * The class specification supports a specific protocol of methods that have + * special meaning (e.g. `render`). See `ReactClassInterface` for + * more the comprehensive protocol. Any other properties and methods in the + * class specification will be available on the prototype. + * + * @interface ReactClassInterface + * @internal + */ +var ReactClassInterface = { + + /** + * An array of Mixin objects to include when defining your component. + * + * @type {array} + * @optional + */ + mixins: SpecPolicy.DEFINE_MANY, + + /** + * An object containing properties and methods that should be defined on + * the component's constructor instead of its prototype (static methods). + * + * @type {object} + * @optional + */ + statics: SpecPolicy.DEFINE_MANY, + + /** + * Definition of prop types for this component. + * + * @type {object} + * @optional + */ + propTypes: SpecPolicy.DEFINE_MANY, + + /** + * Definition of context types for this component. + * + * @type {object} + * @optional + */ + contextTypes: SpecPolicy.DEFINE_MANY, + + /** + * Definition of context types this component sets for its children. + * + * @type {object} + * @optional + */ + childContextTypes: SpecPolicy.DEFINE_MANY, + + // ==== Definition methods ==== + + /** + * Invoked when the component is mounted. Values in the mapping will be set on + * `this.props` if that prop is not specified (i.e. using an `in` check). + * + * This method is invoked before `getInitialState` and therefore cannot rely + * on `this.state` or use `this.setState`. + * + * @return {object} + * @optional + */ + getDefaultProps: SpecPolicy.DEFINE_MANY_MERGED, + + /** + * Invoked once before the component is mounted. The return value will be used + * as the initial value of `this.state`. + * + * getInitialState: function() { + * return { + * isOn: false, + * fooBaz: new BazFoo() + * } + * } + * + * @return {object} + * @optional + */ + getInitialState: SpecPolicy.DEFINE_MANY_MERGED, + + /** + * @return {object} + * @optional + */ + getChildContext: SpecPolicy.DEFINE_MANY_MERGED, + + /** + * Uses props from `this.props` and state from `this.state` to render the + * structure of the component. + * + * No guarantees are made about when or how often this method is invoked, so + * it must not have side effects. + * + * render: function() { + * var name = this.props.name; + * return <div>Hello, {name}!</div>; + * } + * + * @return {ReactComponent} + * @nosideeffects + * @required + */ + render: SpecPolicy.DEFINE_ONCE, + + // ==== Delegate methods ==== + + /** + * Invoked when the component is initially created and about to be mounted. + * This may have side effects, but any external subscriptions or data created + * by this method must be cleaned up in `componentWillUnmount`. + * + * @optional + */ + componentWillMount: SpecPolicy.DEFINE_MANY, + + /** + * Invoked when the component has been mounted and has a DOM representation. + * However, there is no guarantee that the DOM node is in the document. + * + * Use this as an opportunity to operate on the DOM when the component has + * been mounted (initialized and rendered) for the first time. + * + * @param {DOMElement} rootNode DOM element representing the component. + * @optional + */ + componentDidMount: SpecPolicy.DEFINE_MANY, + + /** + * Invoked before the component receives new props. + * + * Use this as an opportunity to react to a prop transition by updating the + * state using `this.setState`. Current props are accessed via `this.props`. + * + * componentWillReceiveProps: function(nextProps, nextContext) { + * this.setState({ + * likesIncreasing: nextProps.likeCount > this.props.likeCount + * }); + * } + * + * NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop + * transition may cause a state change, but the opposite is not true. If you + * need it, you are probably looking for `componentWillUpdate`. + * + * @param {object} nextProps + * @optional + */ + componentWillReceiveProps: SpecPolicy.DEFINE_MANY, + + /** + * Invoked while deciding if the component should be updated as a result of + * receiving new props, state and/or context. + * + * Use this as an opportunity to `return false` when you're certain that the + * transition to the new props/state/context will not require a component + * update. + * + * shouldComponentUpdate: function(nextProps, nextState, nextContext) { + * return !equal(nextProps, this.props) || + * !equal(nextState, this.state) || + * !equal(nextContext, this.context); + * } + * + * @param {object} nextProps + * @param {?object} nextState + * @param {?object} nextContext + * @return {boolean} True if the component should update. + * @optional + */ + shouldComponentUpdate: SpecPolicy.DEFINE_ONCE, + + /** + * Invoked when the component is about to update due to a transition from + * `this.props`, `this.state` and `this.context` to `nextProps`, `nextState` + * and `nextContext`. + * + * Use this as an opportunity to perform preparation before an update occurs. + * + * NOTE: You **cannot** use `this.setState()` in this method. + * + * @param {object} nextProps + * @param {?object} nextState + * @param {?object} nextContext + * @param {ReactReconcileTransaction} transaction + * @optional + */ + componentWillUpdate: SpecPolicy.DEFINE_MANY, + + /** + * Invoked when the component's DOM representation has been updated. + * + * Use this as an opportunity to operate on the DOM when the component has + * been updated. + * + * @param {object} prevProps + * @param {?object} prevState + * @param {?object} prevContext + * @param {DOMElement} rootNode DOM element representing the component. + * @optional + */ + componentDidUpdate: SpecPolicy.DEFINE_MANY, + + /** + * Invoked when the component is about to be removed from its parent and have + * its DOM representation destroyed. + * + * Use this as an opportunity to deallocate any external resources. + * + * NOTE: There is no `componentDidUnmount` since your component will have been + * destroyed by that point. + * + * @optional + */ + componentWillUnmount: SpecPolicy.DEFINE_MANY, + + // ==== Advanced methods ==== + + /** + * Updates the component's currently mounted DOM representation. + * + * By default, this implements React's rendering and reconciliation algorithm. + * Sophisticated clients may wish to override this. + * + * @param {ReactReconcileTransaction} transaction + * @internal + * @overridable + */ + updateComponent: SpecPolicy.OVERRIDE_BASE + +}; + +/** + * Mapping from class specification keys to special processing functions. + * + * Although these are declared like instance properties in the specification + * when defining classes using `React.createClass`, they are actually static + * and are accessible on the constructor instead of the prototype. Despite + * being static, they must be defined outside of the "statics" key under + * which all other static methods are defined. + */ +var RESERVED_SPEC_KEYS = { + displayName: function (Constructor, displayName) { + Constructor.displayName = displayName; + }, + mixins: function (Constructor, mixins) { + if (mixins) { + for (var i = 0; i < mixins.length; i++) { + mixSpecIntoComponent(Constructor, mixins[i]); + } + } + }, + childContextTypes: function (Constructor, childContextTypes) { + if ("production" !== 'production') { + validateTypeDef(Constructor, childContextTypes, ReactPropTypeLocations.childContext); + } + Constructor.childContextTypes = assign({}, Constructor.childContextTypes, childContextTypes); + }, + contextTypes: function (Constructor, contextTypes) { + if ("production" !== 'production') { + validateTypeDef(Constructor, contextTypes, ReactPropTypeLocations.context); + } + Constructor.contextTypes = assign({}, Constructor.contextTypes, contextTypes); + }, + /** + * Special case getDefaultProps which should move into statics but requires + * automatic merging. + */ + getDefaultProps: function (Constructor, getDefaultProps) { + if (Constructor.getDefaultProps) { + Constructor.getDefaultProps = createMergedResultFunction(Constructor.getDefaultProps, getDefaultProps); + } else { + Constructor.getDefaultProps = getDefaultProps; + } + }, + propTypes: function (Constructor, propTypes) { + if ("production" !== 'production') { + validateTypeDef(Constructor, propTypes, ReactPropTypeLocations.prop); + } + Constructor.propTypes = assign({}, Constructor.propTypes, propTypes); + }, + statics: function (Constructor, statics) { + mixStaticSpecIntoComponent(Constructor, statics); + }, + autobind: function () {} }; + +// noop +function validateTypeDef(Constructor, typeDef, location) { + for (var propName in typeDef) { + if (typeDef.hasOwnProperty(propName)) { + // use a warning instead of an invariant so components + // don't show up in prod but not in __DEV__ + "production" !== 'production' ? warning(typeof typeDef[propName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', Constructor.displayName || 'ReactClass', ReactPropTypeLocationNames[location], propName) : undefined; + } + } +} + +function validateMethodOverride(proto, name) { + var specPolicy = ReactClassInterface.hasOwnProperty(name) ? ReactClassInterface[name] : null; + + // Disallow overriding of base class methods unless explicitly allowed. + if (ReactClassMixin.hasOwnProperty(name)) { + !(specPolicy === SpecPolicy.OVERRIDE_BASE) ? "production" !== 'production' ? invariant(false, 'ReactClassInterface: You are attempting to override ' + '`%s` from your class specification. Ensure that your method names ' + 'do not overlap with React methods.', name) : invariant(false) : undefined; + } + + // Disallow defining methods more than once unless explicitly allowed. + if (proto.hasOwnProperty(name)) { + !(specPolicy === SpecPolicy.DEFINE_MANY || specPolicy === SpecPolicy.DEFINE_MANY_MERGED) ? "production" !== 'production' ? invariant(false, 'ReactClassInterface: You are attempting to define ' + '`%s` on your component more than once. This conflict may be due ' + 'to a mixin.', name) : invariant(false) : undefined; + } +} + +/** + * Mixin helper which handles policy validation and reserved + * specification keys when building React classses. + */ +function mixSpecIntoComponent(Constructor, spec) { + if (!spec) { + return; + } + + !(typeof spec !== 'function') ? "production" !== 'production' ? invariant(false, 'ReactClass: You\'re attempting to ' + 'use a component class as a mixin. Instead, just use a regular object.') : invariant(false) : undefined; + !!ReactElement.isValidElement(spec) ? "production" !== 'production' ? invariant(false, 'ReactClass: You\'re attempting to ' + 'use a component as a mixin. Instead, just use a regular object.') : invariant(false) : undefined; + + var proto = Constructor.prototype; + + // By handling mixins before any other properties, we ensure the same + // chaining order is applied to methods with DEFINE_MANY policy, whether + // mixins are listed before or after these methods in the spec. + if (spec.hasOwnProperty(MIXINS_KEY)) { + RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins); + } + + for (var name in spec) { + if (!spec.hasOwnProperty(name)) { + continue; + } + + if (name === MIXINS_KEY) { + // We have already handled mixins in a special case above. + continue; + } + + var property = spec[name]; + validateMethodOverride(proto, name); + + if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) { + RESERVED_SPEC_KEYS[name](Constructor, property); + } else { + // Setup methods on prototype: + // The following member methods should not be automatically bound: + // 1. Expected ReactClass methods (in the "interface"). + // 2. Overridden methods (that were mixed in). + var isReactClassMethod = ReactClassInterface.hasOwnProperty(name); + var isAlreadyDefined = proto.hasOwnProperty(name); + var isFunction = typeof property === 'function'; + var shouldAutoBind = isFunction && !isReactClassMethod && !isAlreadyDefined && spec.autobind !== false; + + if (shouldAutoBind) { + if (!proto.__reactAutoBindMap) { + proto.__reactAutoBindMap = {}; + } + proto.__reactAutoBindMap[name] = property; + proto[name] = property; + } else { + if (isAlreadyDefined) { + var specPolicy = ReactClassInterface[name]; + + // These cases should already be caught by validateMethodOverride. + !(isReactClassMethod && (specPolicy === SpecPolicy.DEFINE_MANY_MERGED || specPolicy === SpecPolicy.DEFINE_MANY)) ? "production" !== 'production' ? invariant(false, 'ReactClass: Unexpected spec policy %s for key %s ' + 'when mixing in component specs.', specPolicy, name) : invariant(false) : undefined; + + // For methods which are defined more than once, call the existing + // methods before calling the new property, merging if appropriate. + if (specPolicy === SpecPolicy.DEFINE_MANY_MERGED) { + proto[name] = createMergedResultFunction(proto[name], property); + } else if (specPolicy === SpecPolicy.DEFINE_MANY) { + proto[name] = createChainedFunction(proto[name], property); + } + } else { + proto[name] = property; + if ("production" !== 'production') { + // Add verbose displayName to the function, which helps when looking + // at profiling tools. + if (typeof property === 'function' && spec.displayName) { + proto[name].displayName = spec.displayName + '_' + name; + } + } + } + } + } + } +} + +function mixStaticSpecIntoComponent(Constructor, statics) { + if (!statics) { + return; + } + for (var name in statics) { + var property = statics[name]; + if (!statics.hasOwnProperty(name)) { + continue; + } + + var isReserved = (name in RESERVED_SPEC_KEYS); + !!isReserved ? "production" !== 'production' ? invariant(false, 'ReactClass: You are attempting to define a reserved ' + 'property, `%s`, that shouldn\'t be on the "statics" key. Define it ' + 'as an instance property instead; it will still be accessible on the ' + 'constructor.', name) : invariant(false) : undefined; + + var isInherited = (name in Constructor); + !!isInherited ? "production" !== 'production' ? invariant(false, 'ReactClass: You are attempting to define ' + '`%s` on your component more than once. This conflict may be ' + 'due to a mixin.', name) : invariant(false) : undefined; + Constructor[name] = property; + } +} + +/** + * Merge two objects, but throw if both contain the same key. + * + * @param {object} one The first object, which is mutated. + * @param {object} two The second object + * @return {object} one after it has been mutated to contain everything in two. + */ +function mergeIntoWithNoDuplicateKeys(one, two) { + !(one && two && typeof one === 'object' && typeof two === 'object') ? "production" !== 'production' ? invariant(false, 'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.') : invariant(false) : undefined; + + for (var key in two) { + if (two.hasOwnProperty(key)) { + !(one[key] === undefined) ? "production" !== 'production' ? invariant(false, 'mergeIntoWithNoDuplicateKeys(): ' + 'Tried to merge two objects with the same key: `%s`. This conflict ' + 'may be due to a mixin; in particular, this may be caused by two ' + 'getInitialState() or getDefaultProps() methods returning objects ' + 'with clashing keys.', key) : invariant(false) : undefined; + one[key] = two[key]; + } + } + return one; +} + +/** + * Creates a function that invokes two functions and merges their return values. + * + * @param {function} one Function to invoke first. + * @param {function} two Function to invoke second. + * @return {function} Function that invokes the two argument functions. + * @private + */ +function createMergedResultFunction(one, two) { + return function mergedResult() { + var a = one.apply(this, arguments); + var b = two.apply(this, arguments); + if (a == null) { + return b; + } else if (b == null) { + return a; + } + var c = {}; + mergeIntoWithNoDuplicateKeys(c, a); + mergeIntoWithNoDuplicateKeys(c, b); + return c; + }; +} + +/** + * Creates a function that invokes two functions and ignores their return vales. + * + * @param {function} one Function to invoke first. + * @param {function} two Function to invoke second. + * @return {function} Function that invokes the two argument functions. + * @private + */ +function createChainedFunction(one, two) { + return function chainedFunction() { + one.apply(this, arguments); + two.apply(this, arguments); + }; +} + +/** + * Binds a method to the component. + * + * @param {object} component Component whose method is going to be bound. + * @param {function} method Method to be bound. + * @return {function} The bound method. + */ +function bindAutoBindMethod(component, method) { + var boundMethod = method.bind(component); + if ("production" !== 'production') { + boundMethod.__reactBoundContext = component; + boundMethod.__reactBoundMethod = method; + boundMethod.__reactBoundArguments = null; + var componentName = component.constructor.displayName; + var _bind = boundMethod.bind; + /* eslint-disable block-scoped-var, no-undef */ + boundMethod.bind = function (newThis) { + for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + + // User is trying to bind() an autobound method; we effectively will + // ignore the value of "this" that the user is trying to use, so + // let's warn. + if (newThis !== component && newThis !== null) { + "production" !== 'production' ? warning(false, 'bind(): React component methods may only be bound to the ' + 'component instance. See %s', componentName) : undefined; + } else if (!args.length) { + "production" !== 'production' ? warning(false, 'bind(): You are binding a component method to the component. ' + 'React does this for you automatically in a high-performance ' + 'way, so you can safely remove this call. See %s', componentName) : undefined; + return boundMethod; + } + var reboundMethod = _bind.apply(boundMethod, arguments); + reboundMethod.__reactBoundContext = component; + reboundMethod.__reactBoundMethod = method; + reboundMethod.__reactBoundArguments = args; + return reboundMethod; + /* eslint-enable */ + }; + } + return boundMethod; +} + +/** + * Binds all auto-bound methods in a component. + * + * @param {object} component Component whose method is going to be bound. + */ +function bindAutoBindMethods(component) { + for (var autoBindKey in component.__reactAutoBindMap) { + if (component.__reactAutoBindMap.hasOwnProperty(autoBindKey)) { + var method = component.__reactAutoBindMap[autoBindKey]; + component[autoBindKey] = bindAutoBindMethod(component, method); + } + } +} + +/** + * Add more to the ReactClass base class. These are all legacy features and + * therefore not already part of the modern ReactComponent. + */ +var ReactClassMixin = { + + /** + * TODO: This will be deprecated because state should always keep a consistent + * type signature and the only use case for this, is to avoid that. + */ + replaceState: function (newState, callback) { + this.updater.enqueueReplaceState(this, newState); + if (callback) { + this.updater.enqueueCallback(this, callback); + } + }, + + /** + * Checks whether or not this composite component is mounted. + * @return {boolean} True if mounted, false otherwise. + * @protected + * @final + */ + isMounted: function () { + return this.updater.isMounted(this); + }, + + /** + * Sets a subset of the props. + * + * @param {object} partialProps Subset of the next props. + * @param {?function} callback Called after props are updated. + * @final + * @public + * @deprecated + */ + setProps: function (partialProps, callback) { + if ("production" !== 'production') { + warnSetProps(); + } + this.updater.enqueueSetProps(this, partialProps); + if (callback) { + this.updater.enqueueCallback(this, callback); + } + }, + + /** + * Replace all the props. + * + * @param {object} newProps Subset of the next props. + * @param {?function} callback Called after props are updated. + * @final + * @public + * @deprecated + */ + replaceProps: function (newProps, callback) { + if ("production" !== 'production') { + warnSetProps(); + } + this.updater.enqueueReplaceProps(this, newProps); + if (callback) { + this.updater.enqueueCallback(this, callback); + } + } +}; + +var ReactClassComponent = function () {}; +assign(ReactClassComponent.prototype, ReactComponent.prototype, ReactClassMixin); + +/** + * Module for creating composite components. + * + * @class ReactClass + */ +var ReactClass = { + + /** + * Creates a composite component class given a class specification. + * + * @param {object} spec Class specification (which must define `render`). + * @return {function} Component constructor function. + * @public + */ + createClass: function (spec) { + var Constructor = function (props, context, updater) { + // This constructor is overridden by mocks. The argument is used + // by mocks to assert on what gets mounted. + + if ("production" !== 'production') { + "production" !== 'production' ? warning(this instanceof Constructor, 'Something is calling a React component directly. Use a factory or ' + 'JSX instead. See: https://fb.me/react-legacyfactory') : undefined; + } + + // Wire up auto-binding + if (this.__reactAutoBindMap) { + bindAutoBindMethods(this); + } + + this.props = props; + this.context = context; + this.refs = emptyObject; + this.updater = updater || ReactNoopUpdateQueue; + + this.state = null; + + // ReactClasses doesn't have constructors. Instead, they use the + // getInitialState and componentWillMount methods for initialization. + + var initialState = this.getInitialState ? this.getInitialState() : null; + if ("production" !== 'production') { + // We allow auto-mocks to proceed as if they're returning null. + if (typeof initialState === 'undefined' && this.getInitialState._isMockFunction) { + // This is probably bad practice. Consider warning here and + // deprecating this convenience. + initialState = null; + } + } + !(typeof initialState === 'object' && !Array.isArray(initialState)) ? "production" !== 'production' ? invariant(false, '%s.getInitialState(): must return an object or null', Constructor.displayName || 'ReactCompositeComponent') : invariant(false) : undefined; + + this.state = initialState; + }; + Constructor.prototype = new ReactClassComponent(); + Constructor.prototype.constructor = Constructor; + + injectedMixins.forEach(mixSpecIntoComponent.bind(null, Constructor)); + + mixSpecIntoComponent(Constructor, spec); + + // Initialize the defaultProps property after all mixins have been merged. + if (Constructor.getDefaultProps) { + Constructor.defaultProps = Constructor.getDefaultProps(); + } + + if ("production" !== 'production') { + // This is a tag to indicate that the use of these method names is ok, + // since it's used with createClass. If it's not, then it's likely a + // mistake so we'll warn you to use the static property, property + // initializer or constructor respectively. + if (Constructor.getDefaultProps) { + Constructor.getDefaultProps.isReactClassApproved = {}; + } + if (Constructor.prototype.getInitialState) { + Constructor.prototype.getInitialState.isReactClassApproved = {}; + } + } + + !Constructor.prototype.render ? "production" !== 'production' ? invariant(false, 'createClass(...): Class specification must implement a `render` method.') : invariant(false) : undefined; + + if ("production" !== 'production') { + "production" !== 'production' ? warning(!Constructor.prototype.componentShouldUpdate, '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', spec.displayName || 'A component') : undefined; + "production" !== 'production' ? warning(!Constructor.prototype.componentWillRecieveProps, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', spec.displayName || 'A component') : undefined; + } + + // Reduce time spent doing lookups by setting these on the prototype. + for (var methodName in ReactClassInterface) { + if (!Constructor.prototype[methodName]) { + Constructor.prototype[methodName] = null; + } + } + + return Constructor; + }, + + injection: { + injectMixin: function (mixin) { + injectedMixins.push(mixin); + } + } + +}; + +module.exports = ReactClass; +},{"154":154,"161":161,"165":165,"166":166,"173":173,"24":24,"34":34,"57":57,"76":76,"80":80,"81":81}],34:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactComponent + */ + +'use strict'; + +var ReactNoopUpdateQueue = _dereq_(76); + +var canDefineProperty = _dereq_(117); +var emptyObject = _dereq_(154); +var invariant = _dereq_(161); +var warning = _dereq_(173); + +/** + * Base class helpers for the updating state of a component. + */ +function ReactComponent(props, context, updater) { + this.props = props; + this.context = context; + this.refs = emptyObject; + // We initialize the default updater but the real one gets injected by the + // renderer. + this.updater = updater || ReactNoopUpdateQueue; +} + +ReactComponent.prototype.isReactComponent = {}; + +/** + * Sets a subset of the state. Always use this to mutate + * state. You should treat `this.state` as immutable. + * + * There is no guarantee that `this.state` will be immediately updated, so + * accessing `this.state` after calling this method may return the old value. + * + * There is no guarantee that calls to `setState` will run synchronously, + * as they may eventually be batched together. You can provide an optional + * callback that will be executed when the call to setState is actually + * completed. + * + * When a function is provided to setState, it will be called at some point in + * the future (not synchronously). It will be called with the up to date + * component arguments (state, props, context). These values can be different + * from this.* because your function may be called after receiveProps but before + * shouldComponentUpdate, and this new state, props, and context will not yet be + * assigned to this. + * + * @param {object|function} partialState Next partial state or function to + * produce next partial state to be merged with current state. + * @param {?function} callback Called after state is updated. + * @final + * @protected + */ +ReactComponent.prototype.setState = function (partialState, callback) { + !(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null) ? "production" !== 'production' ? invariant(false, 'setState(...): takes an object of state variables to update or a ' + 'function which returns an object of state variables.') : invariant(false) : undefined; + if ("production" !== 'production') { + "production" !== 'production' ? warning(partialState != null, 'setState(...): You passed an undefined or null state object; ' + 'instead, use forceUpdate().') : undefined; + } + this.updater.enqueueSetState(this, partialState); + if (callback) { + this.updater.enqueueCallback(this, callback); + } +}; + +/** + * Forces an update. This should only be invoked when it is known with + * certainty that we are **not** in a DOM transaction. + * + * You may want to call this when you know that some deeper aspect of the + * component's state has changed but `setState` was not called. + * + * This will not invoke `shouldComponentUpdate`, but it will invoke + * `componentWillUpdate` and `componentDidUpdate`. + * + * @param {?function} callback Called after update is complete. + * @final + * @protected + */ +ReactComponent.prototype.forceUpdate = function (callback) { + this.updater.enqueueForceUpdate(this); + if (callback) { + this.updater.enqueueCallback(this, callback); + } +}; + +/** + * Deprecated APIs. These APIs used to exist on classic React classes but since + * we would like to deprecate them, we're not going to move them over to this + * modern base class. Instead, we define a getter that warns if it's accessed. + */ +if ("production" !== 'production') { + var deprecatedAPIs = { + getDOMNode: ['getDOMNode', 'Use ReactDOM.findDOMNode(component) instead.'], + isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'], + replaceProps: ['replaceProps', 'Instead, call render again at the top level.'], + replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).'], + setProps: ['setProps', 'Instead, call render again at the top level.'] + }; + var defineDeprecationWarning = function (methodName, info) { + if (canDefineProperty) { + Object.defineProperty(ReactComponent.prototype, methodName, { + get: function () { + "production" !== 'production' ? warning(false, '%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]) : undefined; + return undefined; + } + }); + } + }; + for (var fnName in deprecatedAPIs) { + if (deprecatedAPIs.hasOwnProperty(fnName)) { + defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); + } + } +} + +module.exports = ReactComponent; +},{"117":117,"154":154,"161":161,"173":173,"76":76}],35:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactComponentBrowserEnvironment + */ + +'use strict'; + +var ReactDOMIDOperations = _dereq_(45); +var ReactMount = _dereq_(72); + +/** + * Abstracts away all functionality of the reconciler that requires knowledge of + * the browser context. TODO: These callers should be refactored to avoid the + * need for this injection. + */ +var ReactComponentBrowserEnvironment = { + + processChildrenUpdates: ReactDOMIDOperations.dangerouslyProcessChildrenUpdates, + + replaceNodeWithMarkupByID: ReactDOMIDOperations.dangerouslyReplaceNodeWithMarkupByID, + + /** + * If a particular environment requires that some resources be cleaned up, + * specify this in the injected Mixin. In the DOM, we would likely want to + * purge any cached node ID lookups. + * + * @private + */ + unmountIDFromEnvironment: function (rootNodeID) { + ReactMount.purgeID(rootNodeID); + } + +}; + +module.exports = ReactComponentBrowserEnvironment; +},{"45":45,"72":72}],36:[function(_dereq_,module,exports){ +/** + * Copyright 2014-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactComponentEnvironment + */ + +'use strict'; + +var invariant = _dereq_(161); + +var injected = false; + +var ReactComponentEnvironment = { + + /** + * Optionally injectable environment dependent cleanup hook. (server vs. + * browser etc). Example: A browser system caches DOM nodes based on component + * ID and must remove that cache entry when this instance is unmounted. + */ + unmountIDFromEnvironment: null, + + /** + * Optionally injectable hook for swapping out mount images in the middle of + * the tree. + */ + replaceNodeWithMarkupByID: null, + + /** + * Optionally injectable hook for processing a queue of child updates. Will + * later move into MultiChildComponents. + */ + processChildrenUpdates: null, + + injection: { + injectEnvironment: function (environment) { + !!injected ? "production" !== 'production' ? invariant(false, 'ReactCompositeComponent: injectEnvironment() can only be called once.') : invariant(false) : undefined; + ReactComponentEnvironment.unmountIDFromEnvironment = environment.unmountIDFromEnvironment; + ReactComponentEnvironment.replaceNodeWithMarkupByID = environment.replaceNodeWithMarkupByID; + ReactComponentEnvironment.processChildrenUpdates = environment.processChildrenUpdates; + injected = true; + } + } + +}; + +module.exports = ReactComponentEnvironment; +},{"161":161}],37:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactComponentWithPureRenderMixin + */ + +'use strict'; + +var shallowCompare = _dereq_(140); + +/** + * If your React component's render function is "pure", e.g. it will render the + * same result given the same props and state, provide this Mixin for a + * considerable performance boost. + * + * Most React components have pure render functions. + * + * Example: + * + * var ReactComponentWithPureRenderMixin = + * require('ReactComponentWithPureRenderMixin'); + * React.createClass({ + * mixins: [ReactComponentWithPureRenderMixin], + * + * render: function() { + * return <div className={this.props.className}>foo</div>; + * } + * }); + * + * Note: This only checks shallow equality for props and state. If these contain + * complex data structures this mixin may have false-negatives for deeper + * differences. Only mixin to components which have simple props and state, or + * use `forceUpdate()` when you know deep data structures have changed. + */ +var ReactComponentWithPureRenderMixin = { + shouldComponentUpdate: function (nextProps, nextState) { + return shallowCompare(this, nextProps, nextState); + } +}; + +module.exports = ReactComponentWithPureRenderMixin; +},{"140":140}],38:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactCompositeComponent + */ + +'use strict'; + +var ReactComponentEnvironment = _dereq_(36); +var ReactCurrentOwner = _dereq_(39); +var ReactElement = _dereq_(57); +var ReactInstanceMap = _dereq_(68); +var ReactPerf = _dereq_(78); +var ReactPropTypeLocations = _dereq_(81); +var ReactPropTypeLocationNames = _dereq_(80); +var ReactReconciler = _dereq_(84); +var ReactUpdateQueue = _dereq_(95); + +var assign = _dereq_(24); +var emptyObject = _dereq_(154); +var invariant = _dereq_(161); +var shouldUpdateReactComponent = _dereq_(141); +var warning = _dereq_(173); + +function getDeclarationErrorAddendum(component) { + var owner = component._currentElement._owner || null; + if (owner) { + var name = owner.getName(); + if (name) { + return ' Check the render method of `' + name + '`.'; + } + } + return ''; +} + +function StatelessComponent(Component) {} +StatelessComponent.prototype.render = function () { + var Component = ReactInstanceMap.get(this)._currentElement.type; + return Component(this.props, this.context, this.updater); +}; + +/** + * ------------------ The Life-Cycle of a Composite Component ------------------ + * + * - constructor: Initialization of state. The instance is now retained. + * - componentWillMount + * - render + * - [children's constructors] + * - [children's componentWillMount and render] + * - [children's componentDidMount] + * - componentDidMount + * + * Update Phases: + * - componentWillReceiveProps (only called if parent updated) + * - shouldComponentUpdate + * - componentWillUpdate + * - render + * - [children's constructors or receive props phases] + * - componentDidUpdate + * + * - componentWillUnmount + * - [children's componentWillUnmount] + * - [children destroyed] + * - (destroyed): The instance is now blank, released by React and ready for GC. + * + * ----------------------------------------------------------------------------- + */ + +/** + * An incrementing ID assigned to each component when it is mounted. This is + * used to enforce the order in which `ReactUpdates` updates dirty components. + * + * @private + */ +var nextMountID = 1; + +/** + * @lends {ReactCompositeComponent.prototype} + */ +var ReactCompositeComponentMixin = { + + /** + * Base constructor for all composite component. + * + * @param {ReactElement} element + * @final + * @internal + */ + construct: function (element) { + this._currentElement = element; + this._rootNodeID = null; + this._instance = null; + + // See ReactUpdateQueue + this._pendingElement = null; + this._pendingStateQueue = null; + this._pendingReplaceState = false; + this._pendingForceUpdate = false; + + this._renderedComponent = null; + + this._context = null; + this._mountOrder = 0; + this._topLevelWrapper = null; + + // See ReactUpdates and ReactUpdateQueue. + this._pendingCallbacks = null; + }, + + /** + * Initializes the component, renders markup, and registers event listeners. + * + * @param {string} rootID DOM ID of the root node. + * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction + * @return {?string} Rendered markup to be inserted into the DOM. + * @final + * @internal + */ + mountComponent: function (rootID, transaction, context) { + this._context = context; + this._mountOrder = nextMountID++; + this._rootNodeID = rootID; + + var publicProps = this._processProps(this._currentElement.props); + var publicContext = this._processContext(context); + + var Component = this._currentElement.type; + + // Initialize the public class + var inst; + var renderedElement; + + // This is a way to detect if Component is a stateless arrow function + // component, which is not newable. It might not be 100% reliable but is + // something we can do until we start detecting that Component extends + // React.Component. We already assume that typeof Component === 'function'. + var canInstantiate = ('prototype' in Component); + + if (canInstantiate) { + if ("production" !== 'production') { + ReactCurrentOwner.current = this; + try { + inst = new Component(publicProps, publicContext, ReactUpdateQueue); + } finally { + ReactCurrentOwner.current = null; + } + } else { + inst = new Component(publicProps, publicContext, ReactUpdateQueue); + } + } + + if (!canInstantiate || inst === null || inst === false || ReactElement.isValidElement(inst)) { + renderedElement = inst; + inst = new StatelessComponent(Component); + } + + if ("production" !== 'production') { + // This will throw later in _renderValidatedComponent, but add an early + // warning now to help debugging + if (inst.render == null) { + "production" !== 'production' ? warning(false, '%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`, returned ' + 'null/false from a stateless component, or tried to render an ' + 'element whose type is a function that isn\'t a React component.', Component.displayName || Component.name || 'Component') : undefined; + } else { + // We support ES6 inheriting from React.Component, the module pattern, + // and stateless components, but not ES6 classes that don't extend + "production" !== 'production' ? warning(Component.prototype && Component.prototype.isReactComponent || !canInstantiate || !(inst instanceof Component), '%s(...): React component classes must extend React.Component.', Component.displayName || Component.name || 'Component') : undefined; + } + } + + // These should be set up in the constructor, but as a convenience for + // simpler class abstractions, we set them up after the fact. + inst.props = publicProps; + inst.context = publicContext; + inst.refs = emptyObject; + inst.updater = ReactUpdateQueue; + + this._instance = inst; + + // Store a reference from the instance back to the internal representation + ReactInstanceMap.set(inst, this); + + if ("production" !== 'production') { + // Since plain JS classes are defined without any special initialization + // logic, we can not catch common errors early. Therefore, we have to + // catch them here, at initialization time, instead. + "production" !== 'production' ? warning(!inst.getInitialState || inst.getInitialState.isReactClassApproved, 'getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', this.getName() || 'a component') : undefined; + "production" !== 'production' ? warning(!inst.getDefaultProps || inst.getDefaultProps.isReactClassApproved, 'getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', this.getName() || 'a component') : undefined; + "production" !== 'production' ? warning(!inst.propTypes, 'propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', this.getName() || 'a component') : undefined; + "production" !== 'production' ? warning(!inst.contextTypes, 'contextTypes was defined as an instance property on %s. Use a ' + 'static property to define contextTypes instead.', this.getName() || 'a component') : undefined; + "production" !== 'production' ? warning(typeof inst.componentShouldUpdate !== 'function', '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', this.getName() || 'A component') : undefined; + "production" !== 'production' ? warning(typeof inst.componentDidUnmount !== 'function', '%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', this.getName() || 'A component') : undefined; + "production" !== 'production' ? warning(typeof inst.componentWillRecieveProps !== 'function', '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', this.getName() || 'A component') : undefined; + } + + var initialState = inst.state; + if (initialState === undefined) { + inst.state = initialState = null; + } + !(typeof initialState === 'object' && !Array.isArray(initialState)) ? "production" !== 'production' ? invariant(false, '%s.state: must be set to an object or null', this.getName() || 'ReactCompositeComponent') : invariant(false) : undefined; + + this._pendingStateQueue = null; + this._pendingReplaceState = false; + this._pendingForceUpdate = false; + + if (inst.componentWillMount) { + inst.componentWillMount(); + // When mounting, calls to `setState` by `componentWillMount` will set + // `this._pendingStateQueue` without triggering a re-render. + if (this._pendingStateQueue) { + inst.state = this._processPendingState(inst.props, inst.context); + } + } + + // If not a stateless component, we now render + if (renderedElement === undefined) { + renderedElement = this._renderValidatedComponent(); + } + + this._renderedComponent = this._instantiateReactComponent(renderedElement); + + var markup = ReactReconciler.mountComponent(this._renderedComponent, rootID, transaction, this._processChildContext(context)); + if (inst.componentDidMount) { + transaction.getReactMountReady().enqueue(inst.componentDidMount, inst); + } + + return markup; + }, + + /** + * Releases any resources allocated by `mountComponent`. + * + * @final + * @internal + */ + unmountComponent: function () { + var inst = this._instance; + + if (inst.componentWillUnmount) { + inst.componentWillUnmount(); + } + + ReactReconciler.unmountComponent(this._renderedComponent); + this._renderedComponent = null; + this._instance = null; + + // Reset pending fields + // Even if this component is scheduled for another update in ReactUpdates, + // it would still be ignored because these fields are reset. + this._pendingStateQueue = null; + this._pendingReplaceState = false; + this._pendingForceUpdate = false; + this._pendingCallbacks = null; + this._pendingElement = null; + + // These fields do not really need to be reset since this object is no + // longer accessible. + this._context = null; + this._rootNodeID = null; + this._topLevelWrapper = null; + + // Delete the reference from the instance to this internal representation + // which allow the internals to be properly cleaned up even if the user + // leaks a reference to the public instance. + ReactInstanceMap.remove(inst); + + // Some existing components rely on inst.props even after they've been + // destroyed (in event handlers). + // TODO: inst.props = null; + // TODO: inst.state = null; + // TODO: inst.context = null; + }, + + /** + * Filters the context object to only contain keys specified in + * `contextTypes` + * + * @param {object} context + * @return {?object} + * @private + */ + _maskContext: function (context) { + var maskedContext = null; + var Component = this._currentElement.type; + var contextTypes = Component.contextTypes; + if (!contextTypes) { + return emptyObject; + } + maskedContext = {}; + for (var contextName in contextTypes) { + maskedContext[contextName] = context[contextName]; + } + return maskedContext; + }, + + /** + * Filters the context object to only contain keys specified in + * `contextTypes`, and asserts that they are valid. + * + * @param {object} context + * @return {?object} + * @private + */ + _processContext: function (context) { + var maskedContext = this._maskContext(context); + if ("production" !== 'production') { + var Component = this._currentElement.type; + if (Component.contextTypes) { + this._checkPropTypes(Component.contextTypes, maskedContext, ReactPropTypeLocations.context); + } + } + return maskedContext; + }, + + /** + * @param {object} currentContext + * @return {object} + * @private + */ + _processChildContext: function (currentContext) { + var Component = this._currentElement.type; + var inst = this._instance; + var childContext = inst.getChildContext && inst.getChildContext(); + if (childContext) { + !(typeof Component.childContextTypes === 'object') ? "production" !== 'production' ? invariant(false, '%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', this.getName() || 'ReactCompositeComponent') : invariant(false) : undefined; + if ("production" !== 'production') { + this._checkPropTypes(Component.childContextTypes, childContext, ReactPropTypeLocations.childContext); + } + for (var name in childContext) { + !(name in Component.childContextTypes) ? "production" !== 'production' ? invariant(false, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', this.getName() || 'ReactCompositeComponent', name) : invariant(false) : undefined; + } + return assign({}, currentContext, childContext); + } + return currentContext; + }, + + /** + * Processes props by setting default values for unspecified props and + * asserting that the props are valid. Does not mutate its argument; returns + * a new props object with defaults merged in. + * + * @param {object} newProps + * @return {object} + * @private + */ + _processProps: function (newProps) { + if ("production" !== 'production') { + var Component = this._currentElement.type; + if (Component.propTypes) { + this._checkPropTypes(Component.propTypes, newProps, ReactPropTypeLocations.prop); + } + } + return newProps; + }, + + /** + * Assert that the props are valid + * + * @param {object} propTypes Map of prop name to a ReactPropType + * @param {object} props + * @param {string} location e.g. "prop", "context", "child context" + * @private + */ + _checkPropTypes: function (propTypes, props, location) { + // TODO: Stop validating prop types here and only use the element + // validation. + var componentName = this.getName(); + for (var propName in propTypes) { + if (propTypes.hasOwnProperty(propName)) { + var error; + try { + // This is intentionally an invariant that gets caught. It's the same + // behavior as without this statement except with a better message. + !(typeof propTypes[propName] === 'function') ? "production" !== 'production' ? invariant(false, '%s: %s type `%s` is invalid; it must be a function, usually ' + 'from React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], propName) : invariant(false) : undefined; + error = propTypes[propName](props, propName, componentName, location); + } catch (ex) { + error = ex; + } + if (error instanceof Error) { + // We may want to extend this logic for similar errors in + // top-level render calls, so I'm abstracting it away into + // a function to minimize refactoring in the future + var addendum = getDeclarationErrorAddendum(this); + + if (location === ReactPropTypeLocations.prop) { + // Preface gives us something to blacklist in warning module + "production" !== 'production' ? warning(false, 'Failed Composite propType: %s%s', error.message, addendum) : undefined; + } else { + "production" !== 'production' ? warning(false, 'Failed Context Types: %s%s', error.message, addendum) : undefined; + } + } + } + } + }, + + receiveComponent: function (nextElement, transaction, nextContext) { + var prevElement = this._currentElement; + var prevContext = this._context; + + this._pendingElement = null; + + this.updateComponent(transaction, prevElement, nextElement, prevContext, nextContext); + }, + + /** + * If any of `_pendingElement`, `_pendingStateQueue`, or `_pendingForceUpdate` + * is set, update the component. + * + * @param {ReactReconcileTransaction} transaction + * @internal + */ + performUpdateIfNecessary: function (transaction) { + if (this._pendingElement != null) { + ReactReconciler.receiveComponent(this, this._pendingElement || this._currentElement, transaction, this._context); + } + + if (this._pendingStateQueue !== null || this._pendingForceUpdate) { + this.updateComponent(transaction, this._currentElement, this._currentElement, this._context, this._context); + } + }, + + /** + * Perform an update to a mounted component. The componentWillReceiveProps and + * shouldComponentUpdate methods are called, then (assuming the update isn't + * skipped) the remaining update lifecycle methods are called and the DOM + * representation is updated. + * + * By default, this implements React's rendering and reconciliation algorithm. + * Sophisticated clients may wish to override this. + * + * @param {ReactReconcileTransaction} transaction + * @param {ReactElement} prevParentElement + * @param {ReactElement} nextParentElement + * @internal + * @overridable + */ + updateComponent: function (transaction, prevParentElement, nextParentElement, prevUnmaskedContext, nextUnmaskedContext) { + var inst = this._instance; + + var nextContext = this._context === nextUnmaskedContext ? inst.context : this._processContext(nextUnmaskedContext); + var nextProps; + + // Distinguish between a props update versus a simple state update + if (prevParentElement === nextParentElement) { + // Skip checking prop types again -- we don't read inst.props to avoid + // warning for DOM component props in this upgrade + nextProps = nextParentElement.props; + } else { + nextProps = this._processProps(nextParentElement.props); + // An update here will schedule an update but immediately set + // _pendingStateQueue which will ensure that any state updates gets + // immediately reconciled instead of waiting for the next batch. + + if (inst.componentWillReceiveProps) { + inst.componentWillReceiveProps(nextProps, nextContext); + } + } + + var nextState = this._processPendingState(nextProps, nextContext); + + var shouldUpdate = this._pendingForceUpdate || !inst.shouldComponentUpdate || inst.shouldComponentUpdate(nextProps, nextState, nextContext); + + if ("production" !== 'production') { + "production" !== 'production' ? warning(typeof shouldUpdate !== 'undefined', '%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', this.getName() || 'ReactCompositeComponent') : undefined; + } + + if (shouldUpdate) { + this._pendingForceUpdate = false; + // Will set `this.props`, `this.state` and `this.context`. + this._performComponentUpdate(nextParentElement, nextProps, nextState, nextContext, transaction, nextUnmaskedContext); + } else { + // If it's determined that a component should not update, we still want + // to set props and state but we shortcut the rest of the update. + this._currentElement = nextParentElement; + this._context = nextUnmaskedContext; + inst.props = nextProps; + inst.state = nextState; + inst.context = nextContext; + } + }, + + _processPendingState: function (props, context) { + var inst = this._instance; + var queue = this._pendingStateQueue; + var replace = this._pendingReplaceState; + this._pendingReplaceState = false; + this._pendingStateQueue = null; + + if (!queue) { + return inst.state; + } + + if (replace && queue.length === 1) { + return queue[0]; + } + + var nextState = assign({}, replace ? queue[0] : inst.state); + for (var i = replace ? 1 : 0; i < queue.length; i++) { + var partial = queue[i]; + assign(nextState, typeof partial === 'function' ? partial.call(inst, nextState, props, context) : partial); + } + + return nextState; + }, + + /** + * Merges new props and state, notifies delegate methods of update and + * performs update. + * + * @param {ReactElement} nextElement Next element + * @param {object} nextProps Next public object to set as properties. + * @param {?object} nextState Next object to set as state. + * @param {?object} nextContext Next public object to set as context. + * @param {ReactReconcileTransaction} transaction + * @param {?object} unmaskedContext + * @private + */ + _performComponentUpdate: function (nextElement, nextProps, nextState, nextContext, transaction, unmaskedContext) { + var inst = this._instance; + + var hasComponentDidUpdate = Boolean(inst.componentDidUpdate); + var prevProps; + var prevState; + var prevContext; + if (hasComponentDidUpdate) { + prevProps = inst.props; + prevState = inst.state; + prevContext = inst.context; + } + + if (inst.componentWillUpdate) { + inst.componentWillUpdate(nextProps, nextState, nextContext); + } + + this._currentElement = nextElement; + this._context = unmaskedContext; + inst.props = nextProps; + inst.state = nextState; + inst.context = nextContext; + + this._updateRenderedComponent(transaction, unmaskedContext); + + if (hasComponentDidUpdate) { + transaction.getReactMountReady().enqueue(inst.componentDidUpdate.bind(inst, prevProps, prevState, prevContext), inst); + } + }, + + /** + * Call the component's `render` method and update the DOM accordingly. + * + * @param {ReactReconcileTransaction} transaction + * @internal + */ + _updateRenderedComponent: function (transaction, context) { + var prevComponentInstance = this._renderedComponent; + var prevRenderedElement = prevComponentInstance._currentElement; + var nextRenderedElement = this._renderValidatedComponent(); + if (shouldUpdateReactComponent(prevRenderedElement, nextRenderedElement)) { + ReactReconciler.receiveComponent(prevComponentInstance, nextRenderedElement, transaction, this._processChildContext(context)); + } else { + // These two IDs are actually the same! But nothing should rely on that. + var thisID = this._rootNodeID; + var prevComponentID = prevComponentInstance._rootNodeID; + ReactReconciler.unmountComponent(prevComponentInstance); + + this._renderedComponent = this._instantiateReactComponent(nextRenderedElement); + var nextMarkup = ReactReconciler.mountComponent(this._renderedComponent, thisID, transaction, this._processChildContext(context)); + this._replaceNodeWithMarkupByID(prevComponentID, nextMarkup); + } + }, + + /** + * @protected + */ + _replaceNodeWithMarkupByID: function (prevComponentID, nextMarkup) { + ReactComponentEnvironment.replaceNodeWithMarkupByID(prevComponentID, nextMarkup); + }, + + /** + * @protected + */ + _renderValidatedComponentWithoutOwnerOrContext: function () { + var inst = this._instance; + var renderedComponent = inst.render(); + if ("production" !== 'production') { + // We allow auto-mocks to proceed as if they're returning null. + if (typeof renderedComponent === 'undefined' && inst.render._isMockFunction) { + // This is probably bad practice. Consider warning here and + // deprecating this convenience. + renderedComponent = null; + } + } + + return renderedComponent; + }, + + /** + * @private + */ + _renderValidatedComponent: function () { + var renderedComponent; + ReactCurrentOwner.current = this; + try { + renderedComponent = this._renderValidatedComponentWithoutOwnerOrContext(); + } finally { + ReactCurrentOwner.current = null; + } + !( + // TODO: An `isValidNode` function would probably be more appropriate + renderedComponent === null || renderedComponent === false || ReactElement.isValidElement(renderedComponent)) ? "production" !== 'production' ? invariant(false, '%s.render(): A valid ReactComponent must be returned. You may have ' + 'returned undefined, an array or some other invalid object.', this.getName() || 'ReactCompositeComponent') : invariant(false) : undefined; + return renderedComponent; + }, + + /** + * Lazily allocates the refs object and stores `component` as `ref`. + * + * @param {string} ref Reference name. + * @param {component} component Component to store as `ref`. + * @final + * @private + */ + attachRef: function (ref, component) { + var inst = this.getPublicInstance(); + !(inst != null) ? "production" !== 'production' ? invariant(false, 'Stateless function components cannot have refs.') : invariant(false) : undefined; + var publicComponentInstance = component.getPublicInstance(); + if ("production" !== 'production') { + var componentName = component && component.getName ? component.getName() : 'a component'; + "production" !== 'production' ? warning(publicComponentInstance != null, 'Stateless function components cannot be given refs ' + '(See ref "%s" in %s created by %s). ' + 'Attempts to access this ref will fail.', ref, componentName, this.getName()) : undefined; + } + var refs = inst.refs === emptyObject ? inst.refs = {} : inst.refs; + refs[ref] = publicComponentInstance; + }, + + /** + * Detaches a reference name. + * + * @param {string} ref Name to dereference. + * @final + * @private + */ + detachRef: function (ref) { + var refs = this.getPublicInstance().refs; + delete refs[ref]; + }, + + /** + * Get a text description of the component that can be used to identify it + * in error messages. + * @return {string} The name or null. + * @internal + */ + getName: function () { + var type = this._currentElement.type; + var constructor = this._instance && this._instance.constructor; + return type.displayName || constructor && constructor.displayName || type.name || constructor && constructor.name || null; + }, + + /** + * Get the publicly accessible representation of this component - i.e. what + * is exposed by refs and returned by render. Can be null for stateless + * components. + * + * @return {ReactComponent} the public component instance. + * @internal + */ + getPublicInstance: function () { + var inst = this._instance; + if (inst instanceof StatelessComponent) { + return null; + } + return inst; + }, + + // Stub + _instantiateReactComponent: null + +}; + +ReactPerf.measureMethods(ReactCompositeComponentMixin, 'ReactCompositeComponent', { + mountComponent: 'mountComponent', + updateComponent: 'updateComponent', + _renderValidatedComponent: '_renderValidatedComponent' +}); + +var ReactCompositeComponent = { + + Mixin: ReactCompositeComponentMixin + +}; + +module.exports = ReactCompositeComponent; +},{"141":141,"154":154,"161":161,"173":173,"24":24,"36":36,"39":39,"57":57,"68":68,"78":78,"80":80,"81":81,"84":84,"95":95}],39:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactCurrentOwner + */ + +'use strict'; + +/** + * Keeps track of the current owner. + * + * The current owner is the component who should own any components that are + * currently being constructed. + */ +var ReactCurrentOwner = { + + /** + * @internal + * @type {ReactComponent} + */ + current: null + +}; + +module.exports = ReactCurrentOwner; +},{}],40:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactDOM + */ + +/* globals __REACT_DEVTOOLS_GLOBAL_HOOK__*/ + +'use strict'; + +var ReactCurrentOwner = _dereq_(39); +var ReactDOMTextComponent = _dereq_(51); +var ReactDefaultInjection = _dereq_(54); +var ReactInstanceHandles = _dereq_(67); +var ReactMount = _dereq_(72); +var ReactPerf = _dereq_(78); +var ReactReconciler = _dereq_(84); +var ReactUpdates = _dereq_(96); +var ReactVersion = _dereq_(97); + +var findDOMNode = _dereq_(122); +var renderSubtreeIntoContainer = _dereq_(137); +var warning = _dereq_(173); + +ReactDefaultInjection.inject(); + +var render = ReactPerf.measure('React', 'render', ReactMount.render); + +var React = { + findDOMNode: findDOMNode, + render: render, + unmountComponentAtNode: ReactMount.unmountComponentAtNode, + version: ReactVersion, + + /* eslint-disable camelcase */ + unstable_batchedUpdates: ReactUpdates.batchedUpdates, + unstable_renderSubtreeIntoContainer: renderSubtreeIntoContainer +}; + +// Inject the runtime into a devtools global hook regardless of browser. +// Allows for debugging when the hook is injected on the page. +/* eslint-enable camelcase */ +if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject === 'function') { + __REACT_DEVTOOLS_GLOBAL_HOOK__.inject({ + CurrentOwner: ReactCurrentOwner, + InstanceHandles: ReactInstanceHandles, + Mount: ReactMount, + Reconciler: ReactReconciler, + TextComponent: ReactDOMTextComponent + }); +} + +if ("production" !== 'production') { + var ExecutionEnvironment = _dereq_(147); + if (ExecutionEnvironment.canUseDOM && window.top === window.self) { + + // First check if devtools is not installed + if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') { + // If we're in Chrome or Firefox, provide a download link if not installed. + if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) { + console.debug('Download the React DevTools for a better development experience: ' + 'https://fb.me/react-devtools'); + } + } + + // If we're in IE8, check to see if we are in compatibility mode and provide + // information on preventing compatibility mode + var ieCompatibilityMode = document.documentMode && document.documentMode < 8; + + "production" !== 'production' ? warning(!ieCompatibilityMode, 'Internet Explorer is running in compatibility mode; please add the ' + 'following tag to your HTML to prevent this from happening: ' + '<meta http-equiv="X-UA-Compatible" content="IE=edge" />') : undefined; + + var expectedFeatures = [ + // shims + Array.isArray, Array.prototype.every, Array.prototype.forEach, Array.prototype.indexOf, Array.prototype.map, Date.now, Function.prototype.bind, Object.keys, String.prototype.split, String.prototype.trim, + + // shams + Object.create, Object.freeze]; + + for (var i = 0; i < expectedFeatures.length; i++) { + if (!expectedFeatures[i]) { + console.error('One or more ES5 shim/shams expected by React are not available: ' + 'https://fb.me/react-warning-polyfills'); + break; + } + } + } +} + +module.exports = React; +},{"122":122,"137":137,"147":147,"173":173,"39":39,"51":51,"54":54,"67":67,"72":72,"78":78,"84":84,"96":96,"97":97}],41:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactDOMButton + */ + +'use strict'; + +var mouseListenerNames = { + onClick: true, + onDoubleClick: true, + onMouseDown: true, + onMouseMove: true, + onMouseUp: true, + + onClickCapture: true, + onDoubleClickCapture: true, + onMouseDownCapture: true, + onMouseMoveCapture: true, + onMouseUpCapture: true +}; + +/** + * Implements a <button> native component that does not receive mouse events + * when `disabled` is set. + */ +var ReactDOMButton = { + getNativeProps: function (inst, props, context) { + if (!props.disabled) { + return props; + } + + // Copy the props, except the mouse listeners + var nativeProps = {}; + for (var key in props) { + if (props.hasOwnProperty(key) && !mouseListenerNames[key]) { + nativeProps[key] = props[key]; + } + } + + return nativeProps; + } +}; + +module.exports = ReactDOMButton; +},{}],42:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactDOMComponent + * @typechecks static-only + */ + +/* global hasOwnProperty:true */ + +'use strict'; + +var AutoFocusUtils = _dereq_(2); +var CSSPropertyOperations = _dereq_(5); +var DOMProperty = _dereq_(10); +var DOMPropertyOperations = _dereq_(11); +var EventConstants = _dereq_(15); +var ReactBrowserEventEmitter = _dereq_(28); +var ReactComponentBrowserEnvironment = _dereq_(35); +var ReactDOMButton = _dereq_(41); +var ReactDOMInput = _dereq_(46); +var ReactDOMOption = _dereq_(47); +var ReactDOMSelect = _dereq_(48); +var ReactDOMTextarea = _dereq_(52); +var ReactMount = _dereq_(72); +var ReactMultiChild = _dereq_(73); +var ReactPerf = _dereq_(78); +var ReactUpdateQueue = _dereq_(95); + +var assign = _dereq_(24); +var canDefineProperty = _dereq_(117); +var escapeTextContentForBrowser = _dereq_(121); +var invariant = _dereq_(161); +var isEventSupported = _dereq_(133); +var keyOf = _dereq_(166); +var setInnerHTML = _dereq_(138); +var setTextContent = _dereq_(139); +var shallowEqual = _dereq_(171); +var validateDOMNesting = _dereq_(144); +var warning = _dereq_(173); + +var deleteListener = ReactBrowserEventEmitter.deleteListener; +var listenTo = ReactBrowserEventEmitter.listenTo; +var registrationNameModules = ReactBrowserEventEmitter.registrationNameModules; + +// For quickly matching children type, to test if can be treated as content. +var CONTENT_TYPES = { 'string': true, 'number': true }; + +var CHILDREN = keyOf({ children: null }); +var STYLE = keyOf({ style: null }); +var HTML = keyOf({ __html: null }); + +var ELEMENT_NODE_TYPE = 1; + +function getDeclarationErrorAddendum(internalInstance) { + if (internalInstance) { + var owner = internalInstance._currentElement._owner || null; + if (owner) { + var name = owner.getName(); + if (name) { + return ' This DOM node was rendered by `' + name + '`.'; + } + } + } + return ''; +} + +var legacyPropsDescriptor; +if ("production" !== 'production') { + legacyPropsDescriptor = { + props: { + enumerable: false, + get: function () { + var component = this._reactInternalComponent; + "production" !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .props of a DOM node; instead, ' + 'recreate the props as `render` did originally or read the DOM ' + 'properties/attributes directly from this node (e.g., ' + 'this.refs.box.className).%s', getDeclarationErrorAddendum(component)) : undefined; + return component._currentElement.props; + } + } + }; +} + +function legacyGetDOMNode() { + if ("production" !== 'production') { + var component = this._reactInternalComponent; + "production" !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .getDOMNode() of a DOM node; ' + 'instead, use the node directly.%s', getDeclarationErrorAddendum(component)) : undefined; + } + return this; +} + +function legacyIsMounted() { + var component = this._reactInternalComponent; + if ("production" !== 'production') { + "production" !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .isMounted() of a DOM node.%s', getDeclarationErrorAddendum(component)) : undefined; + } + return !!component; +} + +function legacySetStateEtc() { + if ("production" !== 'production') { + var component = this._reactInternalComponent; + "production" !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .setState(), .replaceState(), or ' + '.forceUpdate() of a DOM node. This is a no-op.%s', getDeclarationErrorAddendum(component)) : undefined; + } +} + +function legacySetProps(partialProps, callback) { + var component = this._reactInternalComponent; + if ("production" !== 'production') { + "production" !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .setProps() of a DOM node. ' + 'Instead, call ReactDOM.render again at the top level.%s', getDeclarationErrorAddendum(component)) : undefined; + } + if (!component) { + return; + } + ReactUpdateQueue.enqueueSetPropsInternal(component, partialProps); + if (callback) { + ReactUpdateQueue.enqueueCallbackInternal(component, callback); + } +} + +function legacyReplaceProps(partialProps, callback) { + var component = this._reactInternalComponent; + if ("production" !== 'production') { + "production" !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .replaceProps() of a DOM node. ' + 'Instead, call ReactDOM.render again at the top level.%s', getDeclarationErrorAddendum(component)) : undefined; + } + if (!component) { + return; + } + ReactUpdateQueue.enqueueReplacePropsInternal(component, partialProps); + if (callback) { + ReactUpdateQueue.enqueueCallbackInternal(component, callback); + } +} + +function friendlyStringify(obj) { + if (typeof obj === 'object') { + if (Array.isArray(obj)) { + return '[' + obj.map(friendlyStringify).join(', ') + ']'; + } else { + var pairs = []; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var keyEscaped = /^[a-z$_][\w$_]*$/i.test(key) ? key : JSON.stringify(key); + pairs.push(keyEscaped + ': ' + friendlyStringify(obj[key])); + } + } + return '{' + pairs.join(', ') + '}'; + } + } else if (typeof obj === 'string') { + return JSON.stringify(obj); + } else if (typeof obj === 'function') { + return '[function object]'; + } + // Differs from JSON.stringify in that undefined becauses undefined and that + // inf and nan don't become null + return String(obj); +} + +var styleMutationWarning = {}; + +function checkAndWarnForMutatedStyle(style1, style2, component) { + if (style1 == null || style2 == null) { + return; + } + if (shallowEqual(style1, style2)) { + return; + } + + var componentName = component._tag; + var owner = component._currentElement._owner; + var ownerName; + if (owner) { + ownerName = owner.getName(); + } + + var hash = ownerName + '|' + componentName; + + if (styleMutationWarning.hasOwnProperty(hash)) { + return; + } + + styleMutationWarning[hash] = true; + + "production" !== 'production' ? warning(false, '`%s` was passed a style object that has previously been mutated. ' + 'Mutating `style` is deprecated. Consider cloning it beforehand. Check ' + 'the `render` %s. Previous style: %s. Mutated style: %s.', componentName, owner ? 'of `' + ownerName + '`' : 'using <' + componentName + '>', friendlyStringify(style1), friendlyStringify(style2)) : undefined; +} + +/** + * @param {object} component + * @param {?object} props + */ +function assertValidProps(component, props) { + if (!props) { + return; + } + // Note the use of `==` which checks for null or undefined. + if ("production" !== 'production') { + if (voidElementTags[component._tag]) { + "production" !== 'production' ? warning(props.children == null && props.dangerouslySetInnerHTML == null, '%s is a void element tag and must not have `children` or ' + 'use `props.dangerouslySetInnerHTML`.%s', component._tag, component._currentElement._owner ? ' Check the render method of ' + component._currentElement._owner.getName() + '.' : '') : undefined; + } + } + if (props.dangerouslySetInnerHTML != null) { + !(props.children == null) ? "production" !== 'production' ? invariant(false, 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.') : invariant(false) : undefined; + !(typeof props.dangerouslySetInnerHTML === 'object' && HTML in props.dangerouslySetInnerHTML) ? "production" !== 'production' ? invariant(false, '`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' + 'Please visit https://fb.me/react-invariant-dangerously-set-inner-html ' + 'for more information.') : invariant(false) : undefined; + } + if ("production" !== 'production') { + "production" !== 'production' ? warning(props.innerHTML == null, 'Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.') : undefined; + "production" !== 'production' ? warning(!props.contentEditable || props.children == null, 'A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of ' + 'those nodes are unexpectedly modified or duplicated. This is ' + 'probably not intentional.') : undefined; + } + !(props.style == null || typeof props.style === 'object') ? "production" !== 'production' ? invariant(false, 'The `style` prop expects a mapping from style properties to values, ' + 'not a string. For example, style={{marginRight: spacing + \'em\'}} when ' + 'using JSX.%s', getDeclarationErrorAddendum(component)) : invariant(false) : undefined; +} + +function enqueuePutListener(id, registrationName, listener, transaction) { + if ("production" !== 'production') { + // IE8 has no API for event capturing and the `onScroll` event doesn't + // bubble. + "production" !== 'production' ? warning(registrationName !== 'onScroll' || isEventSupported('scroll', true), 'This browser doesn\'t support the `onScroll` event') : undefined; + } + var container = ReactMount.findReactContainerForID(id); + if (container) { + var doc = container.nodeType === ELEMENT_NODE_TYPE ? container.ownerDocument : container; + listenTo(registrationName, doc); + } + transaction.getReactMountReady().enqueue(putListener, { + id: id, + registrationName: registrationName, + listener: listener + }); +} + +function putListener() { + var listenerToPut = this; + ReactBrowserEventEmitter.putListener(listenerToPut.id, listenerToPut.registrationName, listenerToPut.listener); +} + +// There are so many media events, it makes sense to just +// maintain a list rather than create a `trapBubbledEvent` for each +var mediaEvents = { + topAbort: 'abort', + topCanPlay: 'canplay', + topCanPlayThrough: 'canplaythrough', + topDurationChange: 'durationchange', + topEmptied: 'emptied', + topEncrypted: 'encrypted', + topEnded: 'ended', + topError: 'error', + topLoadedData: 'loadeddata', + topLoadedMetadata: 'loadedmetadata', + topLoadStart: 'loadstart', + topPause: 'pause', + topPlay: 'play', + topPlaying: 'playing', + topProgress: 'progress', + topRateChange: 'ratechange', + topSeeked: 'seeked', + topSeeking: 'seeking', + topStalled: 'stalled', + topSuspend: 'suspend', + topTimeUpdate: 'timeupdate', + topVolumeChange: 'volumechange', + topWaiting: 'waiting' +}; + +function trapBubbledEventsLocal() { + var inst = this; + // If a component renders to null or if another component fatals and causes + // the state of the tree to be corrupted, `node` here can be null. + !inst._rootNodeID ? "production" !== 'production' ? invariant(false, 'Must be mounted to trap events') : invariant(false) : undefined; + var node = ReactMount.getNode(inst._rootNodeID); + !node ? "production" !== 'production' ? invariant(false, 'trapBubbledEvent(...): Requires node to be rendered.') : invariant(false) : undefined; + + switch (inst._tag) { + case 'iframe': + inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, 'load', node)]; + break; + case 'video': + case 'audio': + + inst._wrapperState.listeners = []; + // create listener for each media event + for (var event in mediaEvents) { + if (mediaEvents.hasOwnProperty(event)) { + inst._wrapperState.listeners.push(ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes[event], mediaEvents[event], node)); + } + } + + break; + case 'img': + inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topError, 'error', node), ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, 'load', node)]; + break; + case 'form': + inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topReset, 'reset', node), ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topSubmit, 'submit', node)]; + break; + } +} + +function mountReadyInputWrapper() { + ReactDOMInput.mountReadyWrapper(this); +} + +function postUpdateSelectWrapper() { + ReactDOMSelect.postUpdateWrapper(this); +} + +// For HTML, certain tags should omit their close tag. We keep a whitelist for +// those special cased tags. + +var omittedCloseTags = { + 'area': true, + 'base': true, + 'br': true, + 'col': true, + 'embed': true, + 'hr': true, + 'img': true, + 'input': true, + 'keygen': true, + 'link': true, + 'meta': true, + 'param': true, + 'source': true, + 'track': true, + 'wbr': true +}; + +// NOTE: menuitem's close tag should be omitted, but that causes problems. +var newlineEatingTags = { + 'listing': true, + 'pre': true, + 'textarea': true +}; + +// For HTML, certain tags cannot have children. This has the same purpose as +// `omittedCloseTags` except that `menuitem` should still have its closing tag. + +var voidElementTags = assign({ + 'menuitem': true +}, omittedCloseTags); + +// We accept any tag to be rendered but since this gets injected into arbitrary +// HTML, we want to make sure that it's a safe tag. +// http://www.w3.org/TR/REC-xml/#NT-Name + +var VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset +var validatedTagCache = {}; +var hasOwnProperty = ({}).hasOwnProperty; + +function validateDangerousTag(tag) { + if (!hasOwnProperty.call(validatedTagCache, tag)) { + !VALID_TAG_REGEX.test(tag) ? "production" !== 'production' ? invariant(false, 'Invalid tag: %s', tag) : invariant(false) : undefined; + validatedTagCache[tag] = true; + } +} + +function processChildContextDev(context, inst) { + // Pass down our tag name to child components for validation purposes + context = assign({}, context); + var info = context[validateDOMNesting.ancestorInfoContextKey]; + context[validateDOMNesting.ancestorInfoContextKey] = validateDOMNesting.updatedAncestorInfo(info, inst._tag, inst); + return context; +} + +function isCustomComponent(tagName, props) { + return tagName.indexOf('-') >= 0 || props.is != null; +} + +/** + * Creates a new React class that is idempotent and capable of containing other + * React components. It accepts event listeners and DOM properties that are + * valid according to `DOMProperty`. + * + * - Event listeners: `onClick`, `onMouseDown`, etc. + * - DOM properties: `className`, `name`, `title`, etc. + * + * The `style` property functions differently from the DOM API. It accepts an + * object mapping of style properties to values. + * + * @constructor ReactDOMComponent + * @extends ReactMultiChild + */ +function ReactDOMComponent(tag) { + validateDangerousTag(tag); + this._tag = tag.toLowerCase(); + this._renderedChildren = null; + this._previousStyle = null; + this._previousStyleCopy = null; + this._rootNodeID = null; + this._wrapperState = null; + this._topLevelWrapper = null; + this._nodeWithLegacyProperties = null; + if ("production" !== 'production') { + this._unprocessedContextDev = null; + this._processedContextDev = null; + } +} + +ReactDOMComponent.displayName = 'ReactDOMComponent'; + +ReactDOMComponent.Mixin = { + + construct: function (element) { + this._currentElement = element; + }, + + /** + * Generates root tag markup then recurses. This method has side effects and + * is not idempotent. + * + * @internal + * @param {string} rootID The root DOM ID for this node. + * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction + * @param {object} context + * @return {string} The computed markup. + */ + mountComponent: function (rootID, transaction, context) { + this._rootNodeID = rootID; + + var props = this._currentElement.props; + + switch (this._tag) { + case 'iframe': + case 'img': + case 'form': + case 'video': + case 'audio': + this._wrapperState = { + listeners: null + }; + transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); + break; + case 'button': + props = ReactDOMButton.getNativeProps(this, props, context); + break; + case 'input': + ReactDOMInput.mountWrapper(this, props, context); + props = ReactDOMInput.getNativeProps(this, props, context); + break; + case 'option': + ReactDOMOption.mountWrapper(this, props, context); + props = ReactDOMOption.getNativeProps(this, props, context); + break; + case 'select': + ReactDOMSelect.mountWrapper(this, props, context); + props = ReactDOMSelect.getNativeProps(this, props, context); + context = ReactDOMSelect.processChildContext(this, props, context); + break; + case 'textarea': + ReactDOMTextarea.mountWrapper(this, props, context); + props = ReactDOMTextarea.getNativeProps(this, props, context); + break; + } + + assertValidProps(this, props); + if ("production" !== 'production') { + if (context[validateDOMNesting.ancestorInfoContextKey]) { + validateDOMNesting(this._tag, this, context[validateDOMNesting.ancestorInfoContextKey]); + } + } + + if ("production" !== 'production') { + this._unprocessedContextDev = context; + this._processedContextDev = processChildContextDev(context, this); + context = this._processedContextDev; + } + + var mountImage; + if (transaction.useCreateElement) { + var ownerDocument = context[ReactMount.ownerDocumentContextKey]; + var el = ownerDocument.createElementNS('http://www.w3.org/1999/xhtml', this._currentElement.type); + DOMPropertyOperations.setAttributeForID(el, this._rootNodeID); + // Populate node cache + ReactMount.getID(el); + this._updateDOMProperties({}, props, transaction, el); + this._createInitialChildren(transaction, props, context, el); + mountImage = el; + } else { + var tagOpen = this._createOpenTagMarkupAndPutListeners(transaction, props); + var tagContent = this._createContentMarkup(transaction, props, context); + if (!tagContent && omittedCloseTags[this._tag]) { + mountImage = tagOpen + '/>'; + } else { + mountImage = tagOpen + '>' + tagContent + '</' + this._currentElement.type + '>'; + } + } + + switch (this._tag) { + case 'input': + transaction.getReactMountReady().enqueue(mountReadyInputWrapper, this); + // falls through + case 'button': + case 'select': + case 'textarea': + if (props.autoFocus) { + transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this); + } + break; + } + + return mountImage; + }, + + /** + * Creates markup for the open tag and all attributes. + * + * This method has side effects because events get registered. + * + * Iterating over object properties is faster than iterating over arrays. + * @see http://jsperf.com/obj-vs-arr-iteration + * + * @private + * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction + * @param {object} props + * @return {string} Markup of opening tag. + */ + _createOpenTagMarkupAndPutListeners: function (transaction, props) { + var ret = '<' + this._currentElement.type; + + for (var propKey in props) { + if (!props.hasOwnProperty(propKey)) { + continue; + } + var propValue = props[propKey]; + if (propValue == null) { + continue; + } + if (registrationNameModules.hasOwnProperty(propKey)) { + if (propValue) { + enqueuePutListener(this._rootNodeID, propKey, propValue, transaction); + } + } else { + if (propKey === STYLE) { + if (propValue) { + if ("production" !== 'production') { + // See `_updateDOMProperties`. style block + this._previousStyle = propValue; + } + propValue = this._previousStyleCopy = assign({}, props.style); + } + propValue = CSSPropertyOperations.createMarkupForStyles(propValue); + } + var markup = null; + if (this._tag != null && isCustomComponent(this._tag, props)) { + if (propKey !== CHILDREN) { + markup = DOMPropertyOperations.createMarkupForCustomAttribute(propKey, propValue); + } + } else { + markup = DOMPropertyOperations.createMarkupForProperty(propKey, propValue); + } + if (markup) { + ret += ' ' + markup; + } + } + } + + // For static pages, no need to put React ID and checksum. Saves lots of + // bytes. + if (transaction.renderToStaticMarkup) { + return ret; + } + + var markupForID = DOMPropertyOperations.createMarkupForID(this._rootNodeID); + return ret + ' ' + markupForID; + }, + + /** + * Creates markup for the content between the tags. + * + * @private + * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction + * @param {object} props + * @param {object} context + * @return {string} Content markup. + */ + _createContentMarkup: function (transaction, props, context) { + var ret = ''; + + // Intentional use of != to avoid catching zero/false. + var innerHTML = props.dangerouslySetInnerHTML; + if (innerHTML != null) { + if (innerHTML.__html != null) { + ret = innerHTML.__html; + } + } else { + var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null; + var childrenToUse = contentToUse != null ? null : props.children; + if (contentToUse != null) { + // TODO: Validate that text is allowed as a child of this node + ret = escapeTextContentForBrowser(contentToUse); + } else if (childrenToUse != null) { + var mountImages = this.mountChildren(childrenToUse, transaction, context); + ret = mountImages.join(''); + } + } + if (newlineEatingTags[this._tag] && ret.charAt(0) === '\n') { + // text/html ignores the first character in these tags if it's a newline + // Prefer to break application/xml over text/html (for now) by adding + // a newline specifically to get eaten by the parser. (Alternately for + // textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first + // \r is normalized out by HTMLTextAreaElement#value.) + // See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre> + // See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions> + // See: <http://www.w3.org/TR/html5/syntax.html#newlines> + // See: Parsing of "textarea" "listing" and "pre" elements + // from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody> + return '\n' + ret; + } else { + return ret; + } + }, + + _createInitialChildren: function (transaction, props, context, el) { + // Intentional use of != to avoid catching zero/false. + var innerHTML = props.dangerouslySetInnerHTML; + if (innerHTML != null) { + if (innerHTML.__html != null) { + setInnerHTML(el, innerHTML.__html); + } + } else { + var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null; + var childrenToUse = contentToUse != null ? null : props.children; + if (contentToUse != null) { + // TODO: Validate that text is allowed as a child of this node + setTextContent(el, contentToUse); + } else if (childrenToUse != null) { + var mountImages = this.mountChildren(childrenToUse, transaction, context); + for (var i = 0; i < mountImages.length; i++) { + el.appendChild(mountImages[i]); + } + } + } + }, + + /** + * Receives a next element and updates the component. + * + * @internal + * @param {ReactElement} nextElement + * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction + * @param {object} context + */ + receiveComponent: function (nextElement, transaction, context) { + var prevElement = this._currentElement; + this._currentElement = nextElement; + this.updateComponent(transaction, prevElement, nextElement, context); + }, + + /** + * Updates a native DOM component after it has already been allocated and + * attached to the DOM. Reconciles the root DOM node, then recurses. + * + * @param {ReactReconcileTransaction} transaction + * @param {ReactElement} prevElement + * @param {ReactElement} nextElement + * @internal + * @overridable + */ + updateComponent: function (transaction, prevElement, nextElement, context) { + var lastProps = prevElement.props; + var nextProps = this._currentElement.props; + + switch (this._tag) { + case 'button': + lastProps = ReactDOMButton.getNativeProps(this, lastProps); + nextProps = ReactDOMButton.getNativeProps(this, nextProps); + break; + case 'input': + ReactDOMInput.updateWrapper(this); + lastProps = ReactDOMInput.getNativeProps(this, lastProps); + nextProps = ReactDOMInput.getNativeProps(this, nextProps); + break; + case 'option': + lastProps = ReactDOMOption.getNativeProps(this, lastProps); + nextProps = ReactDOMOption.getNativeProps(this, nextProps); + break; + case 'select': + lastProps = ReactDOMSelect.getNativeProps(this, lastProps); + nextProps = ReactDOMSelect.getNativeProps(this, nextProps); + break; + case 'textarea': + ReactDOMTextarea.updateWrapper(this); + lastProps = ReactDOMTextarea.getNativeProps(this, lastProps); + nextProps = ReactDOMTextarea.getNativeProps(this, nextProps); + break; + } + + if ("production" !== 'production') { + // If the context is reference-equal to the old one, pass down the same + // processed object so the update bailout in ReactReconciler behaves + // correctly (and identically in dev and prod). See #5005. + if (this._unprocessedContextDev !== context) { + this._unprocessedContextDev = context; + this._processedContextDev = processChildContextDev(context, this); + } + context = this._processedContextDev; + } + + assertValidProps(this, nextProps); + this._updateDOMProperties(lastProps, nextProps, transaction, null); + this._updateDOMChildren(lastProps, nextProps, transaction, context); + + if (!canDefineProperty && this._nodeWithLegacyProperties) { + this._nodeWithLegacyProperties.props = nextProps; + } + + if (this._tag === 'select') { + // <select> value update needs to occur after <option> children + // reconciliation + transaction.getReactMountReady().enqueue(postUpdateSelectWrapper, this); + } + }, + + /** + * Reconciles the properties by detecting differences in property values and + * updating the DOM as necessary. This function is probably the single most + * critical path for performance optimization. + * + * TODO: Benchmark whether checking for changed values in memory actually + * improves performance (especially statically positioned elements). + * TODO: Benchmark the effects of putting this at the top since 99% of props + * do not change for a given reconciliation. + * TODO: Benchmark areas that can be improved with caching. + * + * @private + * @param {object} lastProps + * @param {object} nextProps + * @param {ReactReconcileTransaction} transaction + * @param {?DOMElement} node + */ + _updateDOMProperties: function (lastProps, nextProps, transaction, node) { + var propKey; + var styleName; + var styleUpdates; + for (propKey in lastProps) { + if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey)) { + continue; + } + if (propKey === STYLE) { + var lastStyle = this._previousStyleCopy; + for (styleName in lastStyle) { + if (lastStyle.hasOwnProperty(styleName)) { + styleUpdates = styleUpdates || {}; + styleUpdates[styleName] = ''; + } + } + this._previousStyleCopy = null; + } else if (registrationNameModules.hasOwnProperty(propKey)) { + if (lastProps[propKey]) { + // Only call deleteListener if there was a listener previously or + // else willDeleteListener gets called when there wasn't actually a + // listener (e.g., onClick={null}) + deleteListener(this._rootNodeID, propKey); + } + } else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) { + if (!node) { + node = ReactMount.getNode(this._rootNodeID); + } + DOMPropertyOperations.deleteValueForProperty(node, propKey); + } + } + for (propKey in nextProps) { + var nextProp = nextProps[propKey]; + var lastProp = propKey === STYLE ? this._previousStyleCopy : lastProps[propKey]; + if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp) { + continue; + } + if (propKey === STYLE) { + if (nextProp) { + if ("production" !== 'production') { + checkAndWarnForMutatedStyle(this._previousStyleCopy, this._previousStyle, this); + this._previousStyle = nextProp; + } + nextProp = this._previousStyleCopy = assign({}, nextProp); + } else { + this._previousStyleCopy = null; + } + if (lastProp) { + // Unset styles on `lastProp` but not on `nextProp`. + for (styleName in lastProp) { + if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) { + styleUpdates = styleUpdates || {}; + styleUpdates[styleName] = ''; + } + } + // Update styles that changed since `lastProp`. + for (styleName in nextProp) { + if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) { + styleUpdates = styleUpdates || {}; + styleUpdates[styleName] = nextProp[styleName]; + } + } + } else { + // Relies on `updateStylesByID` not mutating `styleUpdates`. + styleUpdates = nextProp; + } + } else if (registrationNameModules.hasOwnProperty(propKey)) { + if (nextProp) { + enqueuePutListener(this._rootNodeID, propKey, nextProp, transaction); + } else if (lastProp) { + deleteListener(this._rootNodeID, propKey); + } + } else if (isCustomComponent(this._tag, nextProps)) { + if (!node) { + node = ReactMount.getNode(this._rootNodeID); + } + if (propKey === CHILDREN) { + nextProp = null; + } + DOMPropertyOperations.setValueForAttribute(node, propKey, nextProp); + } else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) { + if (!node) { + node = ReactMount.getNode(this._rootNodeID); + } + // If we're updating to null or undefined, we should remove the property + // from the DOM node instead of inadvertantly setting to a string. This + // brings us in line with the same behavior we have on initial render. + if (nextProp != null) { + DOMPropertyOperations.setValueForProperty(node, propKey, nextProp); + } else { + DOMPropertyOperations.deleteValueForProperty(node, propKey); + } + } + } + if (styleUpdates) { + if (!node) { + node = ReactMount.getNode(this._rootNodeID); + } + CSSPropertyOperations.setValueForStyles(node, styleUpdates); + } + }, + + /** + * Reconciles the children with the various properties that affect the + * children content. + * + * @param {object} lastProps + * @param {object} nextProps + * @param {ReactReconcileTransaction} transaction + * @param {object} context + */ + _updateDOMChildren: function (lastProps, nextProps, transaction, context) { + var lastContent = CONTENT_TYPES[typeof lastProps.children] ? lastProps.children : null; + var nextContent = CONTENT_TYPES[typeof nextProps.children] ? nextProps.children : null; + + var lastHtml = lastProps.dangerouslySetInnerHTML && lastProps.dangerouslySetInnerHTML.__html; + var nextHtml = nextProps.dangerouslySetInnerHTML && nextProps.dangerouslySetInnerHTML.__html; + + // Note the use of `!=` which checks for null or undefined. + var lastChildren = lastContent != null ? null : lastProps.children; + var nextChildren = nextContent != null ? null : nextProps.children; + + // 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, context); + } else if (lastHasContentOrHtml && !nextHasContentOrHtml) { + this.updateTextContent(''); + } + + if (nextContent != null) { + if (lastContent !== nextContent) { + this.updateTextContent('' + nextContent); + } + } else if (nextHtml != null) { + if (lastHtml !== nextHtml) { + this.updateMarkup('' + nextHtml); + } + } else if (nextChildren != null) { + this.updateChildren(nextChildren, transaction, context); + } + }, + + /** + * Destroys all event registrations for this instance. Does not remove from + * the DOM. That must be done by the parent. + * + * @internal + */ + unmountComponent: function () { + switch (this._tag) { + case 'iframe': + case 'img': + case 'form': + case 'video': + case 'audio': + var listeners = this._wrapperState.listeners; + if (listeners) { + for (var i = 0; i < listeners.length; i++) { + listeners[i].remove(); + } + } + break; + case 'input': + ReactDOMInput.unmountWrapper(this); + break; + case 'html': + case 'head': + case 'body': + /** + * Components like <html> <head> and <body> can't be removed or added + * easily in a cross-browser way, however it's valuable to be able to + * take advantage of React's reconciliation for styling and <title> + * management. So we just document it and throw in dangerous cases. + */ + !false ? "production" !== 'production' ? invariant(false, '<%s> tried to unmount. Because of cross-browser quirks it is ' + 'impossible to unmount some top-level components (eg <html>, ' + '<head>, and <body>) reliably and efficiently. To fix this, have a ' + 'single top-level component that never unmounts render these ' + 'elements.', this._tag) : invariant(false) : undefined; + break; + } + + this.unmountChildren(); + ReactBrowserEventEmitter.deleteAllListeners(this._rootNodeID); + ReactComponentBrowserEnvironment.unmountIDFromEnvironment(this._rootNodeID); + this._rootNodeID = null; + this._wrapperState = null; + if (this._nodeWithLegacyProperties) { + var node = this._nodeWithLegacyProperties; + node._reactInternalComponent = null; + this._nodeWithLegacyProperties = null; + } + }, + + getPublicInstance: function () { + if (!this._nodeWithLegacyProperties) { + var node = ReactMount.getNode(this._rootNodeID); + + node._reactInternalComponent = this; + node.getDOMNode = legacyGetDOMNode; + node.isMounted = legacyIsMounted; + node.setState = legacySetStateEtc; + node.replaceState = legacySetStateEtc; + node.forceUpdate = legacySetStateEtc; + node.setProps = legacySetProps; + node.replaceProps = legacyReplaceProps; + + if ("production" !== 'production') { + if (canDefineProperty) { + Object.defineProperties(node, legacyPropsDescriptor); + } else { + // updateComponent will update this property on subsequent renders + node.props = this._currentElement.props; + } + } else { + // updateComponent will update this property on subsequent renders + node.props = this._currentElement.props; + } + + this._nodeWithLegacyProperties = node; + } + return this._nodeWithLegacyProperties; + } + +}; + +ReactPerf.measureMethods(ReactDOMComponent, 'ReactDOMComponent', { + mountComponent: 'mountComponent', + updateComponent: 'updateComponent' +}); + +assign(ReactDOMComponent.prototype, ReactDOMComponent.Mixin, ReactMultiChild.Mixin); + +module.exports = ReactDOMComponent; +},{"10":10,"11":11,"117":117,"121":121,"133":133,"138":138,"139":139,"144":144,"15":15,"161":161,"166":166,"171":171,"173":173,"2":2,"24":24,"28":28,"35":35,"41":41,"46":46,"47":47,"48":48,"5":5,"52":52,"72":72,"73":73,"78":78,"95":95}],43:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactDOMFactories + * @typechecks static-only + */ + +'use strict'; + +var ReactElement = _dereq_(57); +var ReactElementValidator = _dereq_(58); + +var mapObject = _dereq_(167); + +/** + * Create a factory that creates HTML tag elements. + * + * @param {string} tag Tag name (e.g. `div`). + * @private + */ +function createDOMFactory(tag) { + if ("production" !== 'production') { + return ReactElementValidator.createFactory(tag); + } + return ReactElement.createFactory(tag); +} + +/** + * Creates a mapping from supported HTML tags to `ReactDOMComponent` classes. + * This is also accessible via `React.DOM`. + * + * @public + */ +var ReactDOMFactories = mapObject({ + a: 'a', + abbr: 'abbr', + address: 'address', + area: 'area', + article: 'article', + aside: 'aside', + audio: 'audio', + b: 'b', + base: 'base', + bdi: 'bdi', + bdo: 'bdo', + big: 'big', + blockquote: 'blockquote', + body: 'body', + br: 'br', + button: 'button', + canvas: 'canvas', + caption: 'caption', + cite: 'cite', + code: 'code', + col: 'col', + colgroup: 'colgroup', + data: 'data', + datalist: 'datalist', + dd: 'dd', + del: 'del', + details: 'details', + dfn: 'dfn', + dialog: 'dialog', + div: 'div', + dl: 'dl', + dt: 'dt', + em: 'em', + embed: 'embed', + fieldset: 'fieldset', + figcaption: 'figcaption', + figure: 'figure', + footer: 'footer', + form: 'form', + h1: 'h1', + h2: 'h2', + h3: 'h3', + h4: 'h4', + h5: 'h5', + h6: 'h6', + head: 'head', + header: 'header', + hgroup: 'hgroup', + hr: 'hr', + html: 'html', + i: 'i', + iframe: 'iframe', + img: 'img', + input: 'input', + ins: 'ins', + kbd: 'kbd', + keygen: 'keygen', + label: 'label', + legend: 'legend', + li: 'li', + link: 'link', + main: 'main', + map: 'map', + mark: 'mark', + menu: 'menu', + menuitem: 'menuitem', + meta: 'meta', + meter: 'meter', + nav: 'nav', + noscript: 'noscript', + object: 'object', + ol: 'ol', + optgroup: 'optgroup', + option: 'option', + output: 'output', + p: 'p', + param: 'param', + picture: 'picture', + pre: 'pre', + progress: 'progress', + q: 'q', + rp: 'rp', + rt: 'rt', + ruby: 'ruby', + s: 's', + samp: 'samp', + script: 'script', + section: 'section', + select: 'select', + small: 'small', + source: 'source', + span: 'span', + strong: 'strong', + style: 'style', + sub: 'sub', + summary: 'summary', + sup: 'sup', + table: 'table', + tbody: 'tbody', + td: 'td', + textarea: 'textarea', + tfoot: 'tfoot', + th: 'th', + thead: 'thead', + time: 'time', + title: 'title', + tr: 'tr', + track: 'track', + u: 'u', + ul: 'ul', + 'var': 'var', + video: 'video', + wbr: 'wbr', + + // SVG + circle: 'circle', + clipPath: 'clipPath', + defs: 'defs', + ellipse: 'ellipse', + g: 'g', + image: 'image', + line: 'line', + linearGradient: 'linearGradient', + mask: 'mask', + path: 'path', + pattern: 'pattern', + polygon: 'polygon', + polyline: 'polyline', + radialGradient: 'radialGradient', + rect: 'rect', + stop: 'stop', + svg: 'svg', + text: 'text', + tspan: 'tspan' + +}, createDOMFactory); + +module.exports = ReactDOMFactories; +},{"167":167,"57":57,"58":58}],44:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactDOMFeatureFlags + */ + +'use strict'; + +var ReactDOMFeatureFlags = { + useCreateElement: false +}; + +module.exports = ReactDOMFeatureFlags; +},{}],45:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactDOMIDOperations + * @typechecks static-only + */ + +'use strict'; + +var DOMChildrenOperations = _dereq_(9); +var DOMPropertyOperations = _dereq_(11); +var ReactMount = _dereq_(72); +var ReactPerf = _dereq_(78); + +var invariant = _dereq_(161); + +/** + * Errors for properties that should not be updated with `updatePropertyByID()`. + * + * @type {object} + * @private + */ +var INVALID_PROPERTY_ERRORS = { + dangerouslySetInnerHTML: '`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.', + style: '`style` must be set using `updateStylesByID()`.' +}; + +/** + * Operations used to process updates to DOM nodes. + */ +var ReactDOMIDOperations = { + + /** + * Updates a DOM node with new property values. This should only be used to + * update DOM properties in `DOMProperty`. + * + * @param {string} id ID of the node to update. + * @param {string} name A valid property name, see `DOMProperty`. + * @param {*} value New value of the property. + * @internal + */ + updatePropertyByID: function (id, name, value) { + var node = ReactMount.getNode(id); + !!INVALID_PROPERTY_ERRORS.hasOwnProperty(name) ? "production" !== 'production' ? invariant(false, 'updatePropertyByID(...): %s', INVALID_PROPERTY_ERRORS[name]) : invariant(false) : undefined; + + // If we're updating to null or undefined, we should remove the property + // from the DOM node instead of inadvertantly setting to a string. This + // brings us in line with the same behavior we have on initial render. + if (value != null) { + DOMPropertyOperations.setValueForProperty(node, name, value); + } else { + DOMPropertyOperations.deleteValueForProperty(node, name); + } + }, + + /** + * Replaces a DOM node that exists in the document with markup. + * + * @param {string} id ID of child to be replaced. + * @param {string} markup Dangerous markup to inject in place of child. + * @internal + * @see {Danger.dangerouslyReplaceNodeWithMarkup} + */ + dangerouslyReplaceNodeWithMarkupByID: function (id, markup) { + var node = ReactMount.getNode(id); + DOMChildrenOperations.dangerouslyReplaceNodeWithMarkup(node, markup); + }, + + /** + * Updates a component's children by processing a series of updates. + * + * @param {array<object>} updates List of update configurations. + * @param {array<string>} markup List of markup strings. + * @internal + */ + dangerouslyProcessChildrenUpdates: function (updates, markup) { + for (var i = 0; i < updates.length; i++) { + updates[i].parentNode = ReactMount.getNode(updates[i].parentID); + } + DOMChildrenOperations.processUpdates(updates, markup); + } +}; + +ReactPerf.measureMethods(ReactDOMIDOperations, 'ReactDOMIDOperations', { + dangerouslyReplaceNodeWithMarkupByID: 'dangerouslyReplaceNodeWithMarkupByID', + dangerouslyProcessChildrenUpdates: 'dangerouslyProcessChildrenUpdates' +}); + +module.exports = ReactDOMIDOperations; +},{"11":11,"161":161,"72":72,"78":78,"9":9}],46:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactDOMInput + */ + +'use strict'; + +var ReactDOMIDOperations = _dereq_(45); +var LinkedValueUtils = _dereq_(23); +var ReactMount = _dereq_(72); +var ReactUpdates = _dereq_(96); + +var assign = _dereq_(24); +var invariant = _dereq_(161); + +var instancesByReactID = {}; + +function forceUpdateIfMounted() { + if (this._rootNodeID) { + // DOM component is still mounted; update + ReactDOMInput.updateWrapper(this); + } +} + +/** + * Implements an <input> native component that allows setting these optional + * props: `checked`, `value`, `defaultChecked`, and `defaultValue`. + * + * If `checked` or `value` are not supplied (or null/undefined), user actions + * that affect the checked state or value will trigger updates to the element. + * + * If they are supplied (and not null/undefined), the rendered element will not + * trigger updates to the element. Instead, the props must change in order for + * the rendered element to be updated. + * + * The rendered element will be initialized as unchecked (or `defaultChecked`) + * with an empty value (or `defaultValue`). + * + * @see http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html + */ +var ReactDOMInput = { + getNativeProps: function (inst, props, context) { + var value = LinkedValueUtils.getValue(props); + var checked = LinkedValueUtils.getChecked(props); + + var nativeProps = assign({}, props, { + defaultChecked: undefined, + defaultValue: undefined, + value: value != null ? value : inst._wrapperState.initialValue, + checked: checked != null ? checked : inst._wrapperState.initialChecked, + onChange: inst._wrapperState.onChange + }); + + return nativeProps; + }, + + mountWrapper: function (inst, props) { + if ("production" !== 'production') { + LinkedValueUtils.checkPropTypes('input', props, inst._currentElement._owner); + } + + var defaultValue = props.defaultValue; + inst._wrapperState = { + initialChecked: props.defaultChecked || false, + initialValue: defaultValue != null ? defaultValue : null, + onChange: _handleChange.bind(inst) + }; + }, + + mountReadyWrapper: function (inst) { + // Can't be in mountWrapper or else server rendering leaks. + instancesByReactID[inst._rootNodeID] = inst; + }, + + unmountWrapper: function (inst) { + delete instancesByReactID[inst._rootNodeID]; + }, + + updateWrapper: function (inst) { + var props = inst._currentElement.props; + + // TODO: Shouldn't this be getChecked(props)? + var checked = props.checked; + if (checked != null) { + ReactDOMIDOperations.updatePropertyByID(inst._rootNodeID, 'checked', checked || false); + } + + var value = LinkedValueUtils.getValue(props); + if (value != null) { + // Cast `value` to a string to ensure the value is set correctly. While + // browsers typically do this as necessary, jsdom doesn't. + ReactDOMIDOperations.updatePropertyByID(inst._rootNodeID, 'value', '' + value); + } + } +}; + +function _handleChange(event) { + var props = this._currentElement.props; + + var returnValue = LinkedValueUtils.executeOnChange(props, event); + + // Here we use asap to wait until all updates have propagated, which + // is important when using controlled components within layers: + // https://github.com/facebook/react/issues/1698 + ReactUpdates.asap(forceUpdateIfMounted, this); + + var name = props.name; + if (props.type === 'radio' && name != null) { + var rootNode = ReactMount.getNode(this._rootNodeID); + var queryRoot = rootNode; + + while (queryRoot.parentNode) { + queryRoot = queryRoot.parentNode; + } + + // If `rootNode.form` was non-null, then we could try `form.elements`, + // but that sometimes behaves strangely in IE8. We could also try using + // `form.getElementsByName`, but that will only return direct children + // and won't include inputs that use the HTML5 `form=` attribute. Since + // the input might not even be in a form, let's just use the global + // `querySelectorAll` to ensure we don't miss anything. + var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type="radio"]'); + + for (var i = 0; i < group.length; i++) { + var otherNode = group[i]; + if (otherNode === rootNode || otherNode.form !== rootNode.form) { + continue; + } + // This will throw if radio buttons rendered by different copies of React + // and the same name are rendered into the same form (same as #1939). + // That's probably okay; we don't support it just as we don't support + // mixing React with non-React. + var otherID = ReactMount.getID(otherNode); + !otherID ? "production" !== 'production' ? invariant(false, 'ReactDOMInput: Mixing React and non-React radio inputs with the ' + 'same `name` is not supported.') : invariant(false) : undefined; + var otherInstance = instancesByReactID[otherID]; + !otherInstance ? "production" !== 'production' ? invariant(false, 'ReactDOMInput: Unknown radio button ID %s.', otherID) : invariant(false) : undefined; + // If this is a controlled radio button group, forcing the input that + // was previously checked to update will cause it to be come re-checked + // as appropriate. + ReactUpdates.asap(forceUpdateIfMounted, otherInstance); + } + } + + return returnValue; +} + +module.exports = ReactDOMInput; +},{"161":161,"23":23,"24":24,"45":45,"72":72,"96":96}],47:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactDOMOption + */ + +'use strict'; + +var ReactChildren = _dereq_(32); +var ReactDOMSelect = _dereq_(48); + +var assign = _dereq_(24); +var warning = _dereq_(173); + +var valueContextKey = ReactDOMSelect.valueContextKey; + +/** + * Implements an <option> native component that warns when `selected` is set. + */ +var ReactDOMOption = { + mountWrapper: function (inst, props, context) { + // TODO (yungsters): Remove support for `selected` in <option>. + if ("production" !== 'production') { + "production" !== 'production' ? warning(props.selected == null, 'Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.') : undefined; + } + + // Look up whether this option is 'selected' via context + var selectValue = context[valueContextKey]; + + // If context key is null (e.g., no specified value or after initial mount) + // or missing (e.g., for <datalist>), we don't change props.selected + var selected = null; + if (selectValue != null) { + selected = false; + if (Array.isArray(selectValue)) { + // multiple + for (var i = 0; i < selectValue.length; i++) { + if ('' + selectValue[i] === '' + props.value) { + selected = true; + break; + } + } + } else { + selected = '' + selectValue === '' + props.value; + } + } + + inst._wrapperState = { selected: selected }; + }, + + getNativeProps: function (inst, props, context) { + var nativeProps = assign({ selected: undefined, children: undefined }, props); + + // Read state only from initial mount because <select> updates value + // manually; we need the initial state only for server rendering + if (inst._wrapperState.selected != null) { + nativeProps.selected = inst._wrapperState.selected; + } + + var content = ''; + + // Flatten children and warn if they aren't strings or numbers; + // invalid types are ignored. + ReactChildren.forEach(props.children, function (child) { + if (child == null) { + return; + } + if (typeof child === 'string' || typeof child === 'number') { + content += child; + } else { + "production" !== 'production' ? warning(false, 'Only strings and numbers are supported as <option> children.') : undefined; + } + }); + + nativeProps.children = content; + return nativeProps; + } + +}; + +module.exports = ReactDOMOption; +},{"173":173,"24":24,"32":32,"48":48}],48:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactDOMSelect + */ + +'use strict'; + +var LinkedValueUtils = _dereq_(23); +var ReactMount = _dereq_(72); +var ReactUpdates = _dereq_(96); + +var assign = _dereq_(24); +var warning = _dereq_(173); + +var valueContextKey = '__ReactDOMSelect_value$' + Math.random().toString(36).slice(2); + +function updateOptionsIfPendingUpdateAndMounted() { + if (this._rootNodeID && this._wrapperState.pendingUpdate) { + this._wrapperState.pendingUpdate = false; + + var props = this._currentElement.props; + var value = LinkedValueUtils.getValue(props); + + if (value != null) { + updateOptions(this, Boolean(props.multiple), value); + } + } +} + +function getDeclarationErrorAddendum(owner) { + if (owner) { + var name = owner.getName(); + if (name) { + return ' Check the render method of `' + name + '`.'; + } + } + return ''; +} + +var valuePropNames = ['value', 'defaultValue']; + +/** + * Validation function for `value` and `defaultValue`. + * @private + */ +function checkSelectPropTypes(inst, props) { + var owner = inst._currentElement._owner; + LinkedValueUtils.checkPropTypes('select', props, owner); + + for (var i = 0; i < valuePropNames.length; i++) { + var propName = valuePropNames[i]; + if (props[propName] == null) { + continue; + } + if (props.multiple) { + "production" !== 'production' ? warning(Array.isArray(props[propName]), 'The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, getDeclarationErrorAddendum(owner)) : undefined; + } else { + "production" !== 'production' ? warning(!Array.isArray(props[propName]), 'The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, getDeclarationErrorAddendum(owner)) : undefined; + } + } +} + +/** + * @param {ReactDOMComponent} inst + * @param {boolean} multiple + * @param {*} propValue A stringable (with `multiple`, a list of stringables). + * @private + */ +function updateOptions(inst, multiple, propValue) { + var selectedValue, i; + var options = ReactMount.getNode(inst._rootNodeID).options; + + if (multiple) { + selectedValue = {}; + for (i = 0; i < propValue.length; i++) { + selectedValue['' + propValue[i]] = true; + } + for (i = 0; i < options.length; i++) { + var selected = selectedValue.hasOwnProperty(options[i].value); + if (options[i].selected !== selected) { + options[i].selected = selected; + } + } + } else { + // Do not set `select.value` as exact behavior isn't consistent across all + // browsers for all cases. + selectedValue = '' + propValue; + for (i = 0; i < options.length; i++) { + if (options[i].value === selectedValue) { + options[i].selected = true; + return; + } + } + if (options.length) { + options[0].selected = true; + } + } +} + +/** + * Implements a <select> native component that allows optionally setting the + * props `value` and `defaultValue`. If `multiple` is false, the prop must be a + * stringable. If `multiple` is true, the prop must be an array of stringables. + * + * If `value` is not supplied (or null/undefined), user actions that change the + * selected option will trigger updates to the rendered options. + * + * If it is supplied (and not null/undefined), the rendered options will not + * update in response to user actions. Instead, the `value` prop must change in + * order for the rendered options to update. + * + * If `defaultValue` is provided, any options with the supplied values will be + * selected. + */ +var ReactDOMSelect = { + valueContextKey: valueContextKey, + + getNativeProps: function (inst, props, context) { + return assign({}, props, { + onChange: inst._wrapperState.onChange, + value: undefined + }); + }, + + mountWrapper: function (inst, props) { + if ("production" !== 'production') { + checkSelectPropTypes(inst, props); + } + + var value = LinkedValueUtils.getValue(props); + inst._wrapperState = { + pendingUpdate: false, + initialValue: value != null ? value : props.defaultValue, + onChange: _handleChange.bind(inst), + wasMultiple: Boolean(props.multiple) + }; + }, + + processChildContext: function (inst, props, context) { + // Pass down initial value so initial generated markup has correct + // `selected` attributes + var childContext = assign({}, context); + childContext[valueContextKey] = inst._wrapperState.initialValue; + return childContext; + }, + + postUpdateWrapper: function (inst) { + var props = inst._currentElement.props; + + // After the initial mount, we control selected-ness manually so don't pass + // the context value down + inst._wrapperState.initialValue = undefined; + + var wasMultiple = inst._wrapperState.wasMultiple; + inst._wrapperState.wasMultiple = Boolean(props.multiple); + + var value = LinkedValueUtils.getValue(props); + if (value != null) { + inst._wrapperState.pendingUpdate = false; + updateOptions(inst, Boolean(props.multiple), value); + } else if (wasMultiple !== Boolean(props.multiple)) { + // For simplicity, reapply `defaultValue` if `multiple` is toggled. + if (props.defaultValue != null) { + updateOptions(inst, Boolean(props.multiple), props.defaultValue); + } else { + // Revert the select back to its default unselected state. + updateOptions(inst, Boolean(props.multiple), props.multiple ? [] : ''); + } + } + } +}; + +function _handleChange(event) { + var props = this._currentElement.props; + var returnValue = LinkedValueUtils.executeOnChange(props, event); + + this._wrapperState.pendingUpdate = true; + ReactUpdates.asap(updateOptionsIfPendingUpdateAndMounted, this); + return returnValue; +} + +module.exports = ReactDOMSelect; +},{"173":173,"23":23,"24":24,"72":72,"96":96}],49:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactDOMSelection + */ + +'use strict'; + +var ExecutionEnvironment = _dereq_(147); + +var getNodeForCharacterOffset = _dereq_(130); +var getTextContentAccessor = _dereq_(131); + +/** + * While `isCollapsed` is available on the Selection object and `collapsed` + * is available on the Range object, IE11 sometimes gets them wrong. + * If the anchor/focus nodes and offsets are the same, the range is collapsed. + */ +function isCollapsed(anchorNode, anchorOffset, focusNode, focusOffset) { + return anchorNode === focusNode && anchorOffset === focusOffset; +} + +/** + * Get the appropriate anchor and focus node/offset pairs for IE. + * + * The catch here is that IE's selection API doesn't provide information + * about whether the selection is forward or backward, so we have to + * behave as though it's always forward. + * + * IE text differs from modern selection in that it behaves as though + * block elements end with a new line. This means character offsets will + * differ between the two APIs. + * + * @param {DOMElement} node + * @return {object} + */ +function getIEOffsets(node) { + var selection = document.selection; + var selectedRange = selection.createRange(); + var selectedLength = selectedRange.text.length; + + // Duplicate selection so we can move range without breaking user selection. + var fromStart = selectedRange.duplicate(); + fromStart.moveToElementText(node); + fromStart.setEndPoint('EndToStart', selectedRange); + + var startOffset = fromStart.text.length; + var endOffset = startOffset + selectedLength; + + return { + start: startOffset, + end: endOffset + }; +} + +/** + * @param {DOMElement} node + * @return {?object} + */ +function getModernOffsets(node) { + var selection = window.getSelection && window.getSelection(); + + if (!selection || selection.rangeCount === 0) { + return null; + } + + var anchorNode = selection.anchorNode; + var anchorOffset = selection.anchorOffset; + var focusNode = selection.focusNode; + var focusOffset = selection.focusOffset; + + var currentRange = selection.getRangeAt(0); + + // In Firefox, range.startContainer and range.endContainer can be "anonymous + // divs", e.g. the up/down buttons on an <input type="number">. Anonymous + // divs do not seem to expose properties, triggering a "Permission denied + // error" if any of its properties are accessed. The only seemingly possible + // way to avoid erroring is to access a property that typically works for + // non-anonymous divs and catch any error that may otherwise arise. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=208427 + try { + /* eslint-disable no-unused-expressions */ + currentRange.startContainer.nodeType; + currentRange.endContainer.nodeType; + /* eslint-enable no-unused-expressions */ + } catch (e) { + return null; + } + + // If the node and offset values are the same, the selection is collapsed. + // `Selection.isCollapsed` is available natively, but IE sometimes gets + // this value wrong. + var isSelectionCollapsed = isCollapsed(selection.anchorNode, selection.anchorOffset, selection.focusNode, selection.focusOffset); + + var rangeLength = isSelectionCollapsed ? 0 : currentRange.toString().length; + + var tempRange = currentRange.cloneRange(); + tempRange.selectNodeContents(node); + tempRange.setEnd(currentRange.startContainer, currentRange.startOffset); + + var isTempRangeCollapsed = isCollapsed(tempRange.startContainer, tempRange.startOffset, tempRange.endContainer, tempRange.endOffset); + + var start = isTempRangeCollapsed ? 0 : tempRange.toString().length; + var end = start + rangeLength; + + // Detect whether the selection is backward. + var detectionRange = document.createRange(); + detectionRange.setStart(anchorNode, anchorOffset); + detectionRange.setEnd(focusNode, focusOffset); + var isBackward = detectionRange.collapsed; + + return { + start: isBackward ? end : start, + end: isBackward ? start : end + }; +} + +/** + * @param {DOMElement|DOMTextNode} node + * @param {object} offsets + */ +function setIEOffsets(node, offsets) { + var range = document.selection.createRange().duplicate(); + var start, end; + + if (typeof offsets.end === 'undefined') { + start = offsets.start; + end = start; + } else if (offsets.start > offsets.end) { + start = offsets.end; + end = offsets.start; + } else { + start = offsets.start; + end = offsets.end; + } + + range.moveToElementText(node); + range.moveStart('character', start); + range.setEndPoint('EndToStart', range); + range.moveEnd('character', end - start); + range.select(); +} + +/** + * In modern non-IE browsers, we can support both forward and backward + * selections. + * + * Note: IE10+ supports the Selection object, but it does not support + * the `extend` method, which means that even in modern IE, it's not possible + * to programatically create a backward selection. Thus, for all IE + * versions, we use the old IE API to create our selections. + * + * @param {DOMElement|DOMTextNode} node + * @param {object} offsets + */ +function setModernOffsets(node, offsets) { + if (!window.getSelection) { + return; + } + + var selection = window.getSelection(); + var length = node[getTextContentAccessor()].length; + var start = Math.min(offsets.start, length); + var end = typeof offsets.end === 'undefined' ? start : Math.min(offsets.end, length); + + // IE 11 uses modern selection, but doesn't support the extend method. + // Flip backward selections, so we can set with a single range. + if (!selection.extend && start > end) { + var temp = end; + end = start; + start = temp; + } + + var startMarker = getNodeForCharacterOffset(node, start); + var endMarker = getNodeForCharacterOffset(node, end); + + if (startMarker && endMarker) { + var range = document.createRange(); + range.setStart(startMarker.node, startMarker.offset); + selection.removeAllRanges(); + + if (start > end) { + selection.addRange(range); + selection.extend(endMarker.node, endMarker.offset); + } else { + range.setEnd(endMarker.node, endMarker.offset); + selection.addRange(range); + } + } +} + +var useIEOffsets = ExecutionEnvironment.canUseDOM && 'selection' in document && !('getSelection' in window); + +var ReactDOMSelection = { + /** + * @param {DOMElement} node + */ + getOffsets: useIEOffsets ? getIEOffsets : getModernOffsets, + + /** + * @param {DOMElement|DOMTextNode} node + * @param {object} offsets + */ + setOffsets: useIEOffsets ? setIEOffsets : setModernOffsets +}; + +module.exports = ReactDOMSelection; +},{"130":130,"131":131,"147":147}],50:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactDOMServer + */ + +'use strict'; + +var ReactDefaultInjection = _dereq_(54); +var ReactServerRendering = _dereq_(88); +var ReactVersion = _dereq_(97); + +ReactDefaultInjection.inject(); + +var ReactDOMServer = { + renderToString: ReactServerRendering.renderToString, + renderToStaticMarkup: ReactServerRendering.renderToStaticMarkup, + version: ReactVersion +}; + +module.exports = ReactDOMServer; +},{"54":54,"88":88,"97":97}],51:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactDOMTextComponent + * @typechecks static-only + */ + +'use strict'; + +var DOMChildrenOperations = _dereq_(9); +var DOMPropertyOperations = _dereq_(11); +var ReactComponentBrowserEnvironment = _dereq_(35); +var ReactMount = _dereq_(72); + +var assign = _dereq_(24); +var escapeTextContentForBrowser = _dereq_(121); +var setTextContent = _dereq_(139); +var validateDOMNesting = _dereq_(144); + +/** + * Text nodes violate a couple assumptions that React makes about components: + * + * - When mounting text into the DOM, adjacent text nodes are merged. + * - Text nodes cannot be assigned a React root ID. + * + * This component is used to wrap strings in elements so that they can undergo + * the same reconciliation that is applied to elements. + * + * TODO: Investigate representing React components in the DOM with text nodes. + * + * @class ReactDOMTextComponent + * @extends ReactComponent + * @internal + */ +var ReactDOMTextComponent = function (props) { + // This constructor and its argument is currently used by mocks. +}; + +assign(ReactDOMTextComponent.prototype, { + + /** + * @param {ReactText} text + * @internal + */ + construct: function (text) { + // TODO: This is really a ReactText (ReactNode), not a ReactElement + this._currentElement = text; + this._stringText = '' + text; + + // Properties + this._rootNodeID = null; + this._mountIndex = 0; + }, + + /** + * Creates the markup for this text node. This node is not intended to have + * any features besides containing text content. + * + * @param {string} rootID DOM ID of the root node. + * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction + * @return {string} Markup for this text node. + * @internal + */ + mountComponent: function (rootID, transaction, context) { + if ("production" !== 'production') { + if (context[validateDOMNesting.ancestorInfoContextKey]) { + validateDOMNesting('span', null, context[validateDOMNesting.ancestorInfoContextKey]); + } + } + + this._rootNodeID = rootID; + if (transaction.useCreateElement) { + var ownerDocument = context[ReactMount.ownerDocumentContextKey]; + var el = ownerDocument.createElementNS('http://www.w3.org/1999/xhtml', 'span'); + DOMPropertyOperations.setAttributeForID(el, rootID); + // Populate node cache + ReactMount.getID(el); + setTextContent(el, this._stringText); + return el; + } else { + var escapedText = escapeTextContentForBrowser(this._stringText); + + if (transaction.renderToStaticMarkup) { + // Normally we'd wrap this in a `span` for the reasons stated above, but + // since this is a situation where React won't take over (static pages), + // we can simply return the text as it is. + return escapedText; + } + + return '<span ' + DOMPropertyOperations.createMarkupForID(rootID) + '>' + escapedText + '</span>'; + } + }, + + /** + * Updates this component by updating the text content. + * + * @param {ReactText} nextText The next text content + * @param {ReactReconcileTransaction} transaction + * @internal + */ + receiveComponent: function (nextText, transaction) { + if (nextText !== this._currentElement) { + this._currentElement = nextText; + var nextStringText = '' + nextText; + if (nextStringText !== this._stringText) { + // TODO: Save this as pending props and use performUpdateIfNecessary + // and/or updateComponent to do the actual update for consistency with + // other component types? + this._stringText = nextStringText; + var node = ReactMount.getNode(this._rootNodeID); + DOMChildrenOperations.updateTextContent(node, nextStringText); + } + } + }, + + unmountComponent: function () { + ReactComponentBrowserEnvironment.unmountIDFromEnvironment(this._rootNodeID); + } + +}); + +module.exports = ReactDOMTextComponent; +},{"11":11,"121":121,"139":139,"144":144,"24":24,"35":35,"72":72,"9":9}],52:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactDOMTextarea + */ + +'use strict'; + +var LinkedValueUtils = _dereq_(23); +var ReactDOMIDOperations = _dereq_(45); +var ReactUpdates = _dereq_(96); + +var assign = _dereq_(24); +var invariant = _dereq_(161); +var warning = _dereq_(173); + +function forceUpdateIfMounted() { + if (this._rootNodeID) { + // DOM component is still mounted; update + ReactDOMTextarea.updateWrapper(this); + } +} + +/** + * Implements a <textarea> native component that allows setting `value`, and + * `defaultValue`. This differs from the traditional DOM API because value is + * usually set as PCDATA children. + * + * If `value` is not supplied (or null/undefined), user actions that affect the + * value will trigger updates to the element. + * + * If `value` is supplied (and not null/undefined), the rendered element will + * not trigger updates to the element. Instead, the `value` prop must change in + * order for the rendered element to be updated. + * + * The rendered element will be initialized with an empty value, the prop + * `defaultValue` if specified, or the children content (deprecated). + */ +var ReactDOMTextarea = { + getNativeProps: function (inst, props, context) { + !(props.dangerouslySetInnerHTML == null) ? "production" !== 'production' ? invariant(false, '`dangerouslySetInnerHTML` does not make sense on <textarea>.') : invariant(false) : undefined; + + // Always set children to the same thing. In IE9, the selection range will + // get reset if `textContent` is mutated. + var nativeProps = assign({}, props, { + defaultValue: undefined, + value: undefined, + children: inst._wrapperState.initialValue, + onChange: inst._wrapperState.onChange + }); + + return nativeProps; + }, + + mountWrapper: function (inst, props) { + if ("production" !== 'production') { + LinkedValueUtils.checkPropTypes('textarea', props, inst._currentElement._owner); + } + + var defaultValue = props.defaultValue; + // TODO (yungsters): Remove support for children content in <textarea>. + var children = props.children; + if (children != null) { + if ("production" !== 'production') { + "production" !== 'production' ? warning(false, 'Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.') : undefined; + } + !(defaultValue == null) ? "production" !== 'production' ? invariant(false, 'If you supply `defaultValue` on a <textarea>, do not pass children.') : invariant(false) : undefined; + if (Array.isArray(children)) { + !(children.length <= 1) ? "production" !== 'production' ? invariant(false, '<textarea> can only have at most one child.') : invariant(false) : undefined; + children = children[0]; + } + + defaultValue = '' + children; + } + if (defaultValue == null) { + defaultValue = ''; + } + var value = LinkedValueUtils.getValue(props); + + inst._wrapperState = { + // We save the initial value so that `ReactDOMComponent` doesn't update + // `textContent` (unnecessary since we update value). + // The initial value can be a boolean or object so that's why it's + // forced to be a string. + initialValue: '' + (value != null ? value : defaultValue), + onChange: _handleChange.bind(inst) + }; + }, + + updateWrapper: function (inst) { + var props = inst._currentElement.props; + var value = LinkedValueUtils.getValue(props); + if (value != null) { + // Cast `value` to a string to ensure the value is set correctly. While + // browsers typically do this as necessary, jsdom doesn't. + ReactDOMIDOperations.updatePropertyByID(inst._rootNodeID, 'value', '' + value); + } + } +}; + +function _handleChange(event) { + var props = this._currentElement.props; + var returnValue = LinkedValueUtils.executeOnChange(props, event); + ReactUpdates.asap(forceUpdateIfMounted, this); + return returnValue; +} + +module.exports = ReactDOMTextarea; +},{"161":161,"173":173,"23":23,"24":24,"45":45,"96":96}],53:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactDefaultBatchingStrategy + */ + +'use strict'; + +var ReactUpdates = _dereq_(96); +var Transaction = _dereq_(113); + +var assign = _dereq_(24); +var emptyFunction = _dereq_(153); + +var RESET_BATCHED_UPDATES = { + initialize: emptyFunction, + close: function () { + ReactDefaultBatchingStrategy.isBatchingUpdates = false; + } +}; + +var FLUSH_BATCHED_UPDATES = { + initialize: emptyFunction, + close: ReactUpdates.flushBatchedUpdates.bind(ReactUpdates) +}; + +var TRANSACTION_WRAPPERS = [FLUSH_BATCHED_UPDATES, RESET_BATCHED_UPDATES]; + +function ReactDefaultBatchingStrategyTransaction() { + this.reinitializeTransaction(); +} + +assign(ReactDefaultBatchingStrategyTransaction.prototype, Transaction.Mixin, { + getTransactionWrappers: function () { + return TRANSACTION_WRAPPERS; + } +}); + +var transaction = new ReactDefaultBatchingStrategyTransaction(); + +var ReactDefaultBatchingStrategy = { + isBatchingUpdates: false, + + /** + * Call the provided function in a context within which calls to `setState` + * and friends are batched such that components aren't updated unnecessarily. + */ + batchedUpdates: function (callback, a, b, c, d, e) { + var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates; + + ReactDefaultBatchingStrategy.isBatchingUpdates = true; + + // The code is written this way to avoid extra allocations + if (alreadyBatchingUpdates) { + callback(a, b, c, d, e); + } else { + transaction.perform(callback, null, a, b, c, d, e); + } + } +}; + +module.exports = ReactDefaultBatchingStrategy; +},{"113":113,"153":153,"24":24,"96":96}],54:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactDefaultInjection + */ + +'use strict'; + +var BeforeInputEventPlugin = _dereq_(3); +var ChangeEventPlugin = _dereq_(7); +var ClientReactRootIndex = _dereq_(8); +var DefaultEventPluginOrder = _dereq_(13); +var EnterLeaveEventPlugin = _dereq_(14); +var ExecutionEnvironment = _dereq_(147); +var HTMLDOMPropertyConfig = _dereq_(21); +var ReactBrowserComponentMixin = _dereq_(27); +var ReactComponentBrowserEnvironment = _dereq_(35); +var ReactDefaultBatchingStrategy = _dereq_(53); +var ReactDOMComponent = _dereq_(42); +var ReactDOMTextComponent = _dereq_(51); +var ReactEventListener = _dereq_(63); +var ReactInjection = _dereq_(65); +var ReactInstanceHandles = _dereq_(67); +var ReactMount = _dereq_(72); +var ReactReconcileTransaction = _dereq_(83); +var SelectEventPlugin = _dereq_(99); +var ServerReactRootIndex = _dereq_(100); +var SimpleEventPlugin = _dereq_(101); +var SVGDOMPropertyConfig = _dereq_(98); + +var alreadyInjected = false; + +function inject() { + if (alreadyInjected) { + // TODO: This is currently true because these injections are shared between + // the client and the server package. They should be built independently + // and not share any injection state. Then this problem will be solved. + return; + } + alreadyInjected = true; + + ReactInjection.EventEmitter.injectReactEventListener(ReactEventListener); + + /** + * Inject modules for resolving DOM hierarchy and plugin ordering. + */ + ReactInjection.EventPluginHub.injectEventPluginOrder(DefaultEventPluginOrder); + ReactInjection.EventPluginHub.injectInstanceHandle(ReactInstanceHandles); + ReactInjection.EventPluginHub.injectMount(ReactMount); + + /** + * Some important event plugins included by default (without having to require + * them). + */ + ReactInjection.EventPluginHub.injectEventPluginsByName({ + SimpleEventPlugin: SimpleEventPlugin, + EnterLeaveEventPlugin: EnterLeaveEventPlugin, + ChangeEventPlugin: ChangeEventPlugin, + SelectEventPlugin: SelectEventPlugin, + BeforeInputEventPlugin: BeforeInputEventPlugin + }); + + ReactInjection.NativeComponent.injectGenericComponentClass(ReactDOMComponent); + + ReactInjection.NativeComponent.injectTextComponentClass(ReactDOMTextComponent); + + ReactInjection.Class.injectMixin(ReactBrowserComponentMixin); + + ReactInjection.DOMProperty.injectDOMPropertyConfig(HTMLDOMPropertyConfig); + ReactInjection.DOMProperty.injectDOMPropertyConfig(SVGDOMPropertyConfig); + + ReactInjection.EmptyComponent.injectEmptyComponent('noscript'); + + ReactInjection.Updates.injectReconcileTransaction(ReactReconcileTransaction); + ReactInjection.Updates.injectBatchingStrategy(ReactDefaultBatchingStrategy); + + ReactInjection.RootIndex.injectCreateReactRootIndex(ExecutionEnvironment.canUseDOM ? ClientReactRootIndex.createReactRootIndex : ServerReactRootIndex.createReactRootIndex); + + ReactInjection.Component.injectEnvironment(ReactComponentBrowserEnvironment); + + if ("production" !== 'production') { + var url = ExecutionEnvironment.canUseDOM && window.location.href || ''; + if (/[?&]react_perf\b/.test(url)) { + var ReactDefaultPerf = _dereq_(55); + ReactDefaultPerf.start(); + } + } +} + +module.exports = { + inject: inject +}; +},{"100":100,"101":101,"13":13,"14":14,"147":147,"21":21,"27":27,"3":3,"35":35,"42":42,"51":51,"53":53,"55":55,"63":63,"65":65,"67":67,"7":7,"72":72,"8":8,"83":83,"98":98,"99":99}],55:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactDefaultPerf + * @typechecks static-only + */ + +'use strict'; + +var DOMProperty = _dereq_(10); +var ReactDefaultPerfAnalysis = _dereq_(56); +var ReactMount = _dereq_(72); +var ReactPerf = _dereq_(78); + +var performanceNow = _dereq_(170); + +function roundFloat(val) { + return Math.floor(val * 100) / 100; +} + +function addValue(obj, key, val) { + obj[key] = (obj[key] || 0) + val; +} + +var ReactDefaultPerf = { + _allMeasurements: [], // last item in the list is the current one + _mountStack: [0], + _injected: false, + + start: function () { + if (!ReactDefaultPerf._injected) { + ReactPerf.injection.injectMeasure(ReactDefaultPerf.measure); + } + + ReactDefaultPerf._allMeasurements.length = 0; + ReactPerf.enableMeasure = true; + }, + + stop: function () { + ReactPerf.enableMeasure = false; + }, + + getLastMeasurements: function () { + return ReactDefaultPerf._allMeasurements; + }, + + printExclusive: function (measurements) { + measurements = measurements || ReactDefaultPerf._allMeasurements; + var summary = ReactDefaultPerfAnalysis.getExclusiveSummary(measurements); + console.table(summary.map(function (item) { + return { + 'Component class name': item.componentName, + 'Total inclusive time (ms)': roundFloat(item.inclusive), + 'Exclusive mount time (ms)': roundFloat(item.exclusive), + 'Exclusive render time (ms)': roundFloat(item.render), + 'Mount time per instance (ms)': roundFloat(item.exclusive / item.count), + 'Render time per instance (ms)': roundFloat(item.render / item.count), + 'Instances': item.count + }; + })); + // TODO: ReactDefaultPerfAnalysis.getTotalTime() does not return the correct + // number. + }, + + printInclusive: function (measurements) { + measurements = measurements || ReactDefaultPerf._allMeasurements; + var summary = ReactDefaultPerfAnalysis.getInclusiveSummary(measurements); + console.table(summary.map(function (item) { + return { + 'Owner > component': item.componentName, + 'Inclusive time (ms)': roundFloat(item.time), + 'Instances': item.count + }; + })); + console.log('Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms'); + }, + + getMeasurementsSummaryMap: function (measurements) { + var summary = ReactDefaultPerfAnalysis.getInclusiveSummary(measurements, true); + return summary.map(function (item) { + return { + 'Owner > component': item.componentName, + 'Wasted time (ms)': item.time, + 'Instances': item.count + }; + }); + }, + + printWasted: function (measurements) { + measurements = measurements || ReactDefaultPerf._allMeasurements; + console.table(ReactDefaultPerf.getMeasurementsSummaryMap(measurements)); + console.log('Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms'); + }, + + printDOM: function (measurements) { + measurements = measurements || ReactDefaultPerf._allMeasurements; + var summary = ReactDefaultPerfAnalysis.getDOMSummary(measurements); + console.table(summary.map(function (item) { + var result = {}; + result[DOMProperty.ID_ATTRIBUTE_NAME] = item.id; + result.type = item.type; + result.args = JSON.stringify(item.args); + return result; + })); + console.log('Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms'); + }, + + _recordWrite: function (id, fnName, totalTime, args) { + // TODO: totalTime isn't that useful since it doesn't count paints/reflows + var writes = ReactDefaultPerf._allMeasurements[ReactDefaultPerf._allMeasurements.length - 1].writes; + writes[id] = writes[id] || []; + writes[id].push({ + type: fnName, + time: totalTime, + args: args + }); + }, + + measure: function (moduleName, fnName, func) { + return function () { + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + var totalTime; + var rv; + var start; + + if (fnName === '_renderNewRootComponent' || fnName === 'flushBatchedUpdates') { + // A "measurement" is a set of metrics recorded for each flush. We want + // to group the metrics for a given flush together so we can look at the + // components that rendered and the DOM operations that actually + // happened to determine the amount of "wasted work" performed. + ReactDefaultPerf._allMeasurements.push({ + exclusive: {}, + inclusive: {}, + render: {}, + counts: {}, + writes: {}, + displayNames: {}, + totalTime: 0, + created: {} + }); + start = performanceNow(); + rv = func.apply(this, args); + ReactDefaultPerf._allMeasurements[ReactDefaultPerf._allMeasurements.length - 1].totalTime = performanceNow() - start; + return rv; + } else if (fnName === '_mountImageIntoNode' || moduleName === 'ReactBrowserEventEmitter' || moduleName === 'ReactDOMIDOperations' || moduleName === 'CSSPropertyOperations' || moduleName === 'DOMChildrenOperations' || moduleName === 'DOMPropertyOperations') { + start = performanceNow(); + rv = func.apply(this, args); + totalTime = performanceNow() - start; + + if (fnName === '_mountImageIntoNode') { + var mountID = ReactMount.getID(args[1]); + ReactDefaultPerf._recordWrite(mountID, fnName, totalTime, args[0]); + } else if (fnName === 'dangerouslyProcessChildrenUpdates') { + // special format + args[0].forEach(function (update) { + var writeArgs = {}; + if (update.fromIndex !== null) { + writeArgs.fromIndex = update.fromIndex; + } + if (update.toIndex !== null) { + writeArgs.toIndex = update.toIndex; + } + if (update.textContent !== null) { + writeArgs.textContent = update.textContent; + } + if (update.markupIndex !== null) { + writeArgs.markup = args[1][update.markupIndex]; + } + ReactDefaultPerf._recordWrite(update.parentID, update.type, totalTime, writeArgs); + }); + } else { + // basic format + var id = args[0]; + if (typeof id === 'object') { + id = ReactMount.getID(args[0]); + } + ReactDefaultPerf._recordWrite(id, fnName, totalTime, Array.prototype.slice.call(args, 1)); + } + return rv; + } else if (moduleName === 'ReactCompositeComponent' && (fnName === 'mountComponent' || fnName === 'updateComponent' || // TODO: receiveComponent()? + fnName === '_renderValidatedComponent')) { + + if (this._currentElement.type === ReactMount.TopLevelWrapper) { + return func.apply(this, args); + } + + var rootNodeID = fnName === 'mountComponent' ? args[0] : this._rootNodeID; + var isRender = fnName === '_renderValidatedComponent'; + var isMount = fnName === 'mountComponent'; + + var mountStack = ReactDefaultPerf._mountStack; + var entry = ReactDefaultPerf._allMeasurements[ReactDefaultPerf._allMeasurements.length - 1]; + + if (isRender) { + addValue(entry.counts, rootNodeID, 1); + } else if (isMount) { + entry.created[rootNodeID] = true; + mountStack.push(0); + } + + start = performanceNow(); + rv = func.apply(this, args); + totalTime = performanceNow() - start; + + if (isRender) { + addValue(entry.render, rootNodeID, totalTime); + } else if (isMount) { + var subMountTime = mountStack.pop(); + mountStack[mountStack.length - 1] += totalTime; + addValue(entry.exclusive, rootNodeID, totalTime - subMountTime); + addValue(entry.inclusive, rootNodeID, totalTime); + } else { + addValue(entry.inclusive, rootNodeID, totalTime); + } + + entry.displayNames[rootNodeID] = { + current: this.getName(), + owner: this._currentElement._owner ? this._currentElement._owner.getName() : '<root>' + }; + + return rv; + } else { + return func.apply(this, args); + } + }; + } +}; + +module.exports = ReactDefaultPerf; +},{"10":10,"170":170,"56":56,"72":72,"78":78}],56:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactDefaultPerfAnalysis + */ + +'use strict'; + +var assign = _dereq_(24); + +// Don't try to save users less than 1.2ms (a number I made up) +var DONT_CARE_THRESHOLD = 1.2; +var DOM_OPERATION_TYPES = { + '_mountImageIntoNode': 'set innerHTML', + INSERT_MARKUP: 'set innerHTML', + MOVE_EXISTING: 'move', + REMOVE_NODE: 'remove', + SET_MARKUP: 'set innerHTML', + TEXT_CONTENT: 'set textContent', + 'setValueForProperty': 'update attribute', + 'setValueForAttribute': 'update attribute', + 'deleteValueForProperty': 'remove attribute', + 'setValueForStyles': 'update styles', + 'replaceNodeWithMarkup': 'replace', + 'updateTextContent': 'set textContent' +}; + +function getTotalTime(measurements) { + // TODO: return number of DOM ops? could be misleading. + // TODO: measure dropped frames after reconcile? + // TODO: log total time of each reconcile and the top-level component + // class that triggered it. + var totalTime = 0; + for (var i = 0; i < measurements.length; i++) { + var measurement = measurements[i]; + totalTime += measurement.totalTime; + } + return totalTime; +} + +function getDOMSummary(measurements) { + var items = []; + measurements.forEach(function (measurement) { + Object.keys(measurement.writes).forEach(function (id) { + measurement.writes[id].forEach(function (write) { + items.push({ + id: id, + type: DOM_OPERATION_TYPES[write.type] || write.type, + args: write.args + }); + }); + }); + }); + return items; +} + +function getExclusiveSummary(measurements) { + var candidates = {}; + var displayName; + + for (var i = 0; i < measurements.length; i++) { + var measurement = measurements[i]; + var allIDs = assign({}, measurement.exclusive, measurement.inclusive); + + for (var id in allIDs) { + displayName = measurement.displayNames[id].current; + + candidates[displayName] = candidates[displayName] || { + componentName: displayName, + inclusive: 0, + exclusive: 0, + render: 0, + count: 0 + }; + if (measurement.render[id]) { + candidates[displayName].render += measurement.render[id]; + } + if (measurement.exclusive[id]) { + candidates[displayName].exclusive += measurement.exclusive[id]; + } + if (measurement.inclusive[id]) { + candidates[displayName].inclusive += measurement.inclusive[id]; + } + if (measurement.counts[id]) { + candidates[displayName].count += measurement.counts[id]; + } + } + } + + // Now make a sorted array with the results. + var arr = []; + for (displayName in candidates) { + if (candidates[displayName].exclusive >= DONT_CARE_THRESHOLD) { + arr.push(candidates[displayName]); + } + } + + arr.sort(function (a, b) { + return b.exclusive - a.exclusive; + }); + + return arr; +} + +function getInclusiveSummary(measurements, onlyClean) { + var candidates = {}; + var inclusiveKey; + + for (var i = 0; i < measurements.length; i++) { + var measurement = measurements[i]; + var allIDs = assign({}, measurement.exclusive, measurement.inclusive); + var cleanComponents; + + if (onlyClean) { + cleanComponents = getUnchangedComponents(measurement); + } + + for (var id in allIDs) { + if (onlyClean && !cleanComponents[id]) { + continue; + } + + var displayName = measurement.displayNames[id]; + + // Inclusive time is not useful for many components without knowing where + // they are instantiated. So we aggregate inclusive time with both the + // owner and current displayName as the key. + inclusiveKey = displayName.owner + ' > ' + displayName.current; + + candidates[inclusiveKey] = candidates[inclusiveKey] || { + componentName: inclusiveKey, + time: 0, + count: 0 + }; + + if (measurement.inclusive[id]) { + candidates[inclusiveKey].time += measurement.inclusive[id]; + } + if (measurement.counts[id]) { + candidates[inclusiveKey].count += measurement.counts[id]; + } + } + } + + // Now make a sorted array with the results. + var arr = []; + for (inclusiveKey in candidates) { + if (candidates[inclusiveKey].time >= DONT_CARE_THRESHOLD) { + arr.push(candidates[inclusiveKey]); + } + } + + arr.sort(function (a, b) { + return b.time - a.time; + }); + + return arr; +} + +function getUnchangedComponents(measurement) { + // For a given reconcile, look at which components did not actually + // render anything to the DOM and return a mapping of their ID to + // the amount of time it took to render the entire subtree. + var cleanComponents = {}; + var dirtyLeafIDs = Object.keys(measurement.writes); + var allIDs = assign({}, measurement.exclusive, measurement.inclusive); + + for (var id in allIDs) { + var isDirty = false; + // For each component that rendered, see if a component that triggered + // a DOM op is in its subtree. + for (var i = 0; i < dirtyLeafIDs.length; i++) { + if (dirtyLeafIDs[i].indexOf(id) === 0) { + isDirty = true; + break; + } + } + // check if component newly created + if (measurement.created[id]) { + isDirty = true; + } + if (!isDirty && measurement.counts[id] > 0) { + cleanComponents[id] = true; + } + } + return cleanComponents; +} + +var ReactDefaultPerfAnalysis = { + getExclusiveSummary: getExclusiveSummary, + getInclusiveSummary: getInclusiveSummary, + getDOMSummary: getDOMSummary, + getTotalTime: getTotalTime +}; + +module.exports = ReactDefaultPerfAnalysis; +},{"24":24}],57:[function(_dereq_,module,exports){ +/** + * Copyright 2014-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactElement + */ + +'use strict'; + +var ReactCurrentOwner = _dereq_(39); + +var assign = _dereq_(24); +var canDefineProperty = _dereq_(117); + +// The Symbol used to tag the ReactElement type. If there is no native Symbol +// nor polyfill, then a plain number is used for performance. +var REACT_ELEMENT_TYPE = typeof Symbol === 'function' && Symbol['for'] && Symbol['for']('react.element') || 0xeac7; + +var RESERVED_PROPS = { + key: true, + ref: true, + __self: true, + __source: true +}; + +/** + * Base constructor for all React elements. This is only used to make this + * work with a dynamic instanceof check. Nothing should live on this prototype. + * + * @param {*} type + * @param {*} key + * @param {string|object} ref + * @param {*} self A *temporary* helper to detect places where `this` is + * different from the `owner` when React.createElement is called, so that we + * can warn. We want to get rid of owner and replace string `ref`s with arrow + * functions, and as long as `this` and owner are the same, there will be no + * change in behavior. + * @param {*} source An annotation object (added by a transpiler or otherwise) + * indicating filename, line number, and/or other information. + * @param {*} owner + * @param {*} props + * @internal + */ +var ReactElement = function (type, key, ref, self, source, owner, props) { + var element = { + // This tag allow us to uniquely identify this as a React Element + $$typeof: REACT_ELEMENT_TYPE, + + // Built-in properties that belong on the element + type: type, + key: key, + ref: ref, + props: props, + + // Record the component responsible for creating this element. + _owner: owner + }; + + if ("production" !== 'production') { + // The validation flag is currently mutative. We put it on + // an external backing store so that we can freeze the whole object. + // This can be replaced with a WeakMap once they are implemented in + // commonly used development environments. + element._store = {}; + + // To make comparing ReactElements easier for testing purposes, we make + // the validation flag non-enumerable (where possible, which should + // include every environment we run tests in), so the test framework + // ignores it. + if (canDefineProperty) { + Object.defineProperty(element._store, 'validated', { + configurable: false, + enumerable: false, + writable: true, + value: false + }); + // self and source are DEV only properties. + Object.defineProperty(element, '_self', { + configurable: false, + enumerable: false, + writable: false, + value: self + }); + // Two elements created in two different places should be considered + // equal for testing purposes and therefore we hide it from enumeration. + Object.defineProperty(element, '_source', { + configurable: false, + enumerable: false, + writable: false, + value: source + }); + } else { + element._store.validated = false; + element._self = self; + element._source = source; + } + Object.freeze(element.props); + Object.freeze(element); + } + + return element; +}; + +ReactElement.createElement = function (type, config, children) { + var propName; + + // Reserved names are extracted + var props = {}; + + var key = null; + var ref = null; + var self = null; + var source = null; + + if (config != null) { + ref = config.ref === undefined ? null : config.ref; + key = config.key === undefined ? null : '' + config.key; + self = config.__self === undefined ? null : config.__self; + source = config.__source === undefined ? null : config.__source; + // Remaining properties are added to a new props object + for (propName in config) { + if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { + props[propName] = config[propName]; + } + } + } + + // Children can be more than one argument, and those are transferred onto + // the newly allocated props object. + var childrenLength = arguments.length - 2; + if (childrenLength === 1) { + props.children = children; + } else if (childrenLength > 1) { + var childArray = Array(childrenLength); + for (var i = 0; i < childrenLength; i++) { + childArray[i] = arguments[i + 2]; + } + props.children = childArray; + } + + // Resolve default props + if (type && type.defaultProps) { + var defaultProps = type.defaultProps; + for (propName in defaultProps) { + if (typeof props[propName] === 'undefined') { + props[propName] = defaultProps[propName]; + } + } + } + + return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); +}; + +ReactElement.createFactory = function (type) { + var factory = ReactElement.createElement.bind(null, type); + // Expose the type on the factory and the prototype so that it can be + // easily accessed on elements. E.g. `<Foo />.type === Foo`. + // This should not be named `constructor` since this may not be the function + // that created the element, and it may not even be a constructor. + // Legacy hook TODO: Warn if this is accessed + factory.type = type; + return factory; +}; + +ReactElement.cloneAndReplaceKey = function (oldElement, newKey) { + var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props); + + return newElement; +}; + +ReactElement.cloneAndReplaceProps = function (oldElement, newProps) { + var newElement = ReactElement(oldElement.type, oldElement.key, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, newProps); + + if ("production" !== 'production') { + // If the key on the original is valid, then the clone is valid + newElement._store.validated = oldElement._store.validated; + } + + return newElement; +}; + +ReactElement.cloneElement = function (element, config, children) { + var propName; + + // Original props are copied + var props = assign({}, element.props); + + // Reserved names are extracted + var key = element.key; + var ref = element.ref; + // Self is preserved since the owner is preserved. + var self = element._self; + // Source is preserved since cloneElement is unlikely to be targeted by a + // transpiler, and the original source is probably a better indicator of the + // true owner. + var source = element._source; + + // Owner will be preserved, unless ref is overridden + var owner = element._owner; + + if (config != null) { + if (config.ref !== undefined) { + // Silently steal the ref from the parent. + ref = config.ref; + owner = ReactCurrentOwner.current; + } + if (config.key !== undefined) { + key = '' + config.key; + } + // Remaining properties override existing props + for (propName in config) { + if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { + props[propName] = config[propName]; + } + } + } + + // Children can be more than one argument, and those are transferred onto + // the newly allocated props object. + var childrenLength = arguments.length - 2; + if (childrenLength === 1) { + props.children = children; + } else if (childrenLength > 1) { + var childArray = Array(childrenLength); + for (var i = 0; i < childrenLength; i++) { + childArray[i] = arguments[i + 2]; + } + props.children = childArray; + } + + return ReactElement(element.type, key, ref, self, source, owner, props); +}; + +/** + * @param {?object} object + * @return {boolean} True if `object` is a valid component. + * @final + */ +ReactElement.isValidElement = function (object) { + return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; +}; + +module.exports = ReactElement; +},{"117":117,"24":24,"39":39}],58:[function(_dereq_,module,exports){ +/** + * Copyright 2014-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactElementValidator + */ + +/** + * ReactElementValidator provides a wrapper around a element factory + * which validates the props passed to the element. This is intended to be + * used only in DEV and could be replaced by a static type checker for languages + * that support it. + */ + +'use strict'; + +var ReactElement = _dereq_(57); +var ReactPropTypeLocations = _dereq_(81); +var ReactPropTypeLocationNames = _dereq_(80); +var ReactCurrentOwner = _dereq_(39); + +var canDefineProperty = _dereq_(117); +var getIteratorFn = _dereq_(129); +var invariant = _dereq_(161); +var warning = _dereq_(173); + +function getDeclarationErrorAddendum() { + if (ReactCurrentOwner.current) { + var name = ReactCurrentOwner.current.getName(); + if (name) { + return ' Check the render method of `' + name + '`.'; + } + } + return ''; +} + +/** + * Warn if there's no key explicitly set on dynamic arrays of children or + * object keys are not valid. This allows us to keep track of children between + * updates. + */ +var ownerHasKeyUseWarning = {}; + +var loggedTypeFailures = {}; + +/** + * Warn if the element doesn't have an explicit key assigned to it. + * This element is in an array. The array could grow and shrink or be + * reordered. All children that haven't already been validated are required to + * have a "key" property assigned to it. + * + * @internal + * @param {ReactElement} element Element that requires a key. + * @param {*} parentType element's parent's type. + */ +function validateExplicitKey(element, parentType) { + if (!element._store || element._store.validated || element.key != null) { + return; + } + element._store.validated = true; + + var addenda = getAddendaForKeyUse('uniqueKey', element, parentType); + if (addenda === null) { + // we already showed the warning + return; + } + "production" !== 'production' ? warning(false, 'Each child in an array or iterator should have a unique "key" prop.' + '%s%s%s', addenda.parentOrOwner || '', addenda.childOwner || '', addenda.url || '') : undefined; +} + +/** + * Shared warning and monitoring code for the key warnings. + * + * @internal + * @param {string} messageType A key used for de-duping warnings. + * @param {ReactElement} element Component that requires a key. + * @param {*} parentType element's parent's type. + * @returns {?object} A set of addenda to use in the warning message, or null + * if the warning has already been shown before (and shouldn't be shown again). + */ +function getAddendaForKeyUse(messageType, element, parentType) { + var addendum = getDeclarationErrorAddendum(); + if (!addendum) { + var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name; + if (parentName) { + addendum = ' Check the top-level render call using <' + parentName + '>.'; + } + } + + var memoizer = ownerHasKeyUseWarning[messageType] || (ownerHasKeyUseWarning[messageType] = {}); + if (memoizer[addendum]) { + return null; + } + memoizer[addendum] = true; + + var addenda = { + parentOrOwner: addendum, + url: ' See https://fb.me/react-warning-keys for more information.', + childOwner: null + }; + + // Usually the current owner is the offender, but if it accepts children as a + // property, it may be the creator of the child that's responsible for + // assigning it a key. + if (element && element._owner && element._owner !== ReactCurrentOwner.current) { + // Give the component that originally created this child. + addenda.childOwner = ' It was passed a child from ' + element._owner.getName() + '.'; + } + + return addenda; +} + +/** + * Ensure that every element either is passed in a static location, in an + * array with an explicit keys property defined, or in an object literal + * with valid key property. + * + * @internal + * @param {ReactNode} node Statically passed child of any type. + * @param {*} parentType node's parent's type. + */ +function validateChildKeys(node, parentType) { + if (typeof node !== 'object') { + return; + } + if (Array.isArray(node)) { + for (var i = 0; i < node.length; i++) { + var child = node[i]; + if (ReactElement.isValidElement(child)) { + validateExplicitKey(child, parentType); + } + } + } else if (ReactElement.isValidElement(node)) { + // This element was passed in a valid location. + if (node._store) { + node._store.validated = true; + } + } else if (node) { + var iteratorFn = getIteratorFn(node); + // Entry iterators provide implicit keys. + if (iteratorFn) { + if (iteratorFn !== node.entries) { + var iterator = iteratorFn.call(node); + var step; + while (!(step = iterator.next()).done) { + if (ReactElement.isValidElement(step.value)) { + validateExplicitKey(step.value, parentType); + } + } + } + } + } +} + +/** + * Assert that the props are valid + * + * @param {string} componentName Name of the component for error messages. + * @param {object} propTypes Map of prop name to a ReactPropType + * @param {object} props + * @param {string} location e.g. "prop", "context", "child context" + * @private + */ +function checkPropTypes(componentName, propTypes, props, location) { + for (var propName in propTypes) { + if (propTypes.hasOwnProperty(propName)) { + var error; + // Prop type validation may throw. In case they do, we don't want to + // fail the render phase where it didn't fail before. So we log it. + // After these have been cleaned up, we'll let them throw. + try { + // This is intentionally an invariant that gets caught. It's the same + // behavior as without this statement except with a better message. + !(typeof propTypes[propName] === 'function') ? "production" !== 'production' ? invariant(false, '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], propName) : invariant(false) : undefined; + error = propTypes[propName](props, propName, componentName, location); + } catch (ex) { + error = ex; + } + "production" !== 'production' ? warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', ReactPropTypeLocationNames[location], propName, typeof error) : undefined; + if (error instanceof Error && !(error.message in loggedTypeFailures)) { + // Only monitor this failure once because there tends to be a lot of the + // same error. + loggedTypeFailures[error.message] = true; + + var addendum = getDeclarationErrorAddendum(); + "production" !== 'production' ? warning(false, 'Failed propType: %s%s', error.message, addendum) : undefined; + } + } + } +} + +/** + * Given an element, validate that its props follow the propTypes definition, + * provided by the type. + * + * @param {ReactElement} element + */ +function validatePropTypes(element) { + var componentClass = element.type; + if (typeof componentClass !== 'function') { + return; + } + var name = componentClass.displayName || componentClass.name; + if (componentClass.propTypes) { + checkPropTypes(name, componentClass.propTypes, element.props, ReactPropTypeLocations.prop); + } + if (typeof componentClass.getDefaultProps === 'function') { + "production" !== 'production' ? warning(componentClass.getDefaultProps.isReactClassApproved, 'getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.') : undefined; + } +} + +var ReactElementValidator = { + + createElement: function (type, props, children) { + var validType = typeof type === 'string' || typeof type === 'function'; + // We warn in this case but don't throw. We expect the element creation to + // succeed and there will likely be errors in render. + "production" !== 'production' ? warning(validType, 'React.createElement: type should not be null, undefined, boolean, or ' + 'number. It should be a string (for DOM elements) or a ReactClass ' + '(for composite components).%s', getDeclarationErrorAddendum()) : undefined; + + var element = ReactElement.createElement.apply(this, arguments); + + // The result can be nullish if a mock or a custom function is used. + // TODO: Drop this when these are no longer allowed as the type argument. + if (element == null) { + return element; + } + + // Skip key warning if the type isn't valid since our key validation logic + // doesn't expect a non-string/function type and can throw confusing errors. + // We don't want exception behavior to differ between dev and prod. + // (Rendering will throw with a helpful message and as soon as the type is + // fixed, the key warnings will appear.) + if (validType) { + for (var i = 2; i < arguments.length; i++) { + validateChildKeys(arguments[i], type); + } + } + + validatePropTypes(element); + + return element; + }, + + createFactory: function (type) { + var validatedFactory = ReactElementValidator.createElement.bind(null, type); + // Legacy hook TODO: Warn if this is accessed + validatedFactory.type = type; + + if ("production" !== 'production') { + if (canDefineProperty) { + Object.defineProperty(validatedFactory, 'type', { + enumerable: false, + get: function () { + "production" !== 'production' ? warning(false, 'Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.') : undefined; + Object.defineProperty(this, 'type', { + value: type + }); + return type; + } + }); + } + } + + return validatedFactory; + }, + + cloneElement: function (element, props, children) { + var newElement = ReactElement.cloneElement.apply(this, arguments); + for (var i = 2; i < arguments.length; i++) { + validateChildKeys(arguments[i], newElement.type); + } + validatePropTypes(newElement); + return newElement; + } + +}; + +module.exports = ReactElementValidator; +},{"117":117,"129":129,"161":161,"173":173,"39":39,"57":57,"80":80,"81":81}],59:[function(_dereq_,module,exports){ +/** + * Copyright 2014-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactEmptyComponent + */ + +'use strict'; + +var ReactElement = _dereq_(57); +var ReactEmptyComponentRegistry = _dereq_(60); +var ReactReconciler = _dereq_(84); + +var assign = _dereq_(24); + +var placeholderElement; + +var ReactEmptyComponentInjection = { + injectEmptyComponent: function (component) { + placeholderElement = ReactElement.createElement(component); + } +}; + +var ReactEmptyComponent = function (instantiate) { + this._currentElement = null; + this._rootNodeID = null; + this._renderedComponent = instantiate(placeholderElement); +}; +assign(ReactEmptyComponent.prototype, { + construct: function (element) {}, + mountComponent: function (rootID, transaction, context) { + ReactEmptyComponentRegistry.registerNullComponentID(rootID); + this._rootNodeID = rootID; + return ReactReconciler.mountComponent(this._renderedComponent, rootID, transaction, context); + }, + receiveComponent: function () {}, + unmountComponent: function (rootID, transaction, context) { + ReactReconciler.unmountComponent(this._renderedComponent); + ReactEmptyComponentRegistry.deregisterNullComponentID(this._rootNodeID); + this._rootNodeID = null; + this._renderedComponent = null; + } +}); + +ReactEmptyComponent.injection = ReactEmptyComponentInjection; + +module.exports = ReactEmptyComponent; +},{"24":24,"57":57,"60":60,"84":84}],60:[function(_dereq_,module,exports){ +/** + * Copyright 2014-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactEmptyComponentRegistry + */ + +'use strict'; + +// This registry keeps track of the React IDs of the components that rendered to +// `null` (in reality a placeholder such as `noscript`) +var nullComponentIDsRegistry = {}; + +/** + * @param {string} id Component's `_rootNodeID`. + * @return {boolean} True if the component is rendered to null. + */ +function isNullComponentID(id) { + return !!nullComponentIDsRegistry[id]; +} + +/** + * Mark the component as having rendered to null. + * @param {string} id Component's `_rootNodeID`. + */ +function registerNullComponentID(id) { + nullComponentIDsRegistry[id] = true; +} + +/** + * Unmark the component as having rendered to null: it renders to something now. + * @param {string} id Component's `_rootNodeID`. + */ +function deregisterNullComponentID(id) { + delete nullComponentIDsRegistry[id]; +} + +var ReactEmptyComponentRegistry = { + isNullComponentID: isNullComponentID, + registerNullComponentID: registerNullComponentID, + deregisterNullComponentID: deregisterNullComponentID +}; + +module.exports = ReactEmptyComponentRegistry; +},{}],61:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactErrorUtils + * @typechecks + */ + +'use strict'; + +var caughtError = null; + +/** + * Call a function while guarding against errors that happens within it. + * + * @param {?String} name of the guard to use for logging or debugging + * @param {Function} func The function to invoke + * @param {*} a First argument + * @param {*} b Second argument + */ +function invokeGuardedCallback(name, func, a, b) { + try { + return func(a, b); + } catch (x) { + if (caughtError === null) { + caughtError = x; + } + return undefined; + } +} + +var ReactErrorUtils = { + invokeGuardedCallback: invokeGuardedCallback, + + /** + * Invoked by ReactTestUtils.Simulate so that any errors thrown by the event + * handler are sure to be rethrown by rethrowCaughtError. + */ + invokeGuardedCallbackWithCatch: invokeGuardedCallback, + + /** + * During execution of guarded functions we will capture the first error which + * we will rethrow to be handled by the top level error handler. + */ + rethrowCaughtError: function () { + if (caughtError) { + var error = caughtError; + caughtError = null; + throw error; + } + } +}; + +if ("production" !== 'production') { + /** + * To help development we can get better devtools integration by simulating a + * real browser event. + */ + if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') { + var fakeNode = document.createElementNS('http://www.w3.org/1999/xhtml', 'react'); + ReactErrorUtils.invokeGuardedCallback = function (name, func, a, b) { + var boundFunc = func.bind(null, a, b); + var evtType = 'react-' + name; + fakeNode.addEventListener(evtType, boundFunc, false); + var evt = document.createEvent('Event'); + evt.initEvent(evtType, false, false); + fakeNode.dispatchEvent(evt); + fakeNode.removeEventListener(evtType, boundFunc, false); + }; + } +} + +module.exports = ReactErrorUtils; +},{}],62:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactEventEmitterMixin + */ + +'use strict'; + +var EventPluginHub = _dereq_(16); + +function runEventQueueInBatch(events) { + EventPluginHub.enqueueEvents(events); + EventPluginHub.processEventQueue(false); +} + +var ReactEventEmitterMixin = { + + /** + * Streams a fired top-level event to `EventPluginHub` where plugins have the + * opportunity to create `ReactEvent`s to be dispatched. + * + * @param {string} topLevelType Record from `EventConstants`. + * @param {object} topLevelTarget The listening component root node. + * @param {string} topLevelTargetID ID of `topLevelTarget`. + * @param {object} nativeEvent Native environment event. + */ + handleTopLevel: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) { + var events = EventPluginHub.extractEvents(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget); + runEventQueueInBatch(events); + } +}; + +module.exports = ReactEventEmitterMixin; +},{"16":16}],63:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactEventListener + * @typechecks static-only + */ + +'use strict'; + +var EventListener = _dereq_(146); +var ExecutionEnvironment = _dereq_(147); +var PooledClass = _dereq_(25); +var ReactInstanceHandles = _dereq_(67); +var ReactMount = _dereq_(72); +var ReactUpdates = _dereq_(96); + +var assign = _dereq_(24); +var getEventTarget = _dereq_(128); +var getUnboundedScrollPosition = _dereq_(158); + +var DOCUMENT_FRAGMENT_NODE_TYPE = 11; + +/** + * Finds the parent React component of `node`. + * + * @param {*} node + * @return {?DOMEventTarget} Parent container, or `null` if the specified node + * is not nested. + */ +function findParent(node) { + // TODO: It may be a good idea to cache this to prevent unnecessary DOM + // traversal, but caching is difficult to do correctly without using a + // mutation observer to listen for all DOM changes. + var nodeID = ReactMount.getID(node); + var rootID = ReactInstanceHandles.getReactRootIDFromNodeID(nodeID); + var container = ReactMount.findReactContainerForID(rootID); + var parent = ReactMount.getFirstReactDOM(container); + return parent; +} + +// Used to store ancestor hierarchy in top level callback +function TopLevelCallbackBookKeeping(topLevelType, nativeEvent) { + this.topLevelType = topLevelType; + this.nativeEvent = nativeEvent; + this.ancestors = []; +} +assign(TopLevelCallbackBookKeeping.prototype, { + destructor: function () { + this.topLevelType = null; + this.nativeEvent = null; + this.ancestors.length = 0; + } +}); +PooledClass.addPoolingTo(TopLevelCallbackBookKeeping, PooledClass.twoArgumentPooler); + +function handleTopLevelImpl(bookKeeping) { + // TODO: Re-enable event.path handling + // + // if (bookKeeping.nativeEvent.path && bookKeeping.nativeEvent.path.length > 1) { + // // New browsers have a path attribute on native events + // handleTopLevelWithPath(bookKeeping); + // } else { + // // Legacy browsers don't have a path attribute on native events + // handleTopLevelWithoutPath(bookKeeping); + // } + + void handleTopLevelWithPath; // temporarily unused + handleTopLevelWithoutPath(bookKeeping); +} + +// Legacy browsers don't have a path attribute on native events +function handleTopLevelWithoutPath(bookKeeping) { + var topLevelTarget = ReactMount.getFirstReactDOM(getEventTarget(bookKeeping.nativeEvent)) || window; + + // Loop through the hierarchy, in case there's any nested components. + // It's important that we build the array of ancestors before calling any + // event handlers, because event handlers can modify the DOM, leading to + // inconsistencies with ReactMount's node cache. See #1105. + var ancestor = topLevelTarget; + while (ancestor) { + bookKeeping.ancestors.push(ancestor); + ancestor = findParent(ancestor); + } + + for (var i = 0; i < bookKeeping.ancestors.length; i++) { + topLevelTarget = bookKeeping.ancestors[i]; + var topLevelTargetID = ReactMount.getID(topLevelTarget) || ''; + ReactEventListener._handleTopLevel(bookKeeping.topLevelType, topLevelTarget, topLevelTargetID, bookKeeping.nativeEvent, getEventTarget(bookKeeping.nativeEvent)); + } +} + +// New browsers have a path attribute on native events +function handleTopLevelWithPath(bookKeeping) { + var path = bookKeeping.nativeEvent.path; + var currentNativeTarget = path[0]; + var eventsFired = 0; + for (var i = 0; i < path.length; i++) { + var currentPathElement = path[i]; + if (currentPathElement.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE) { + currentNativeTarget = path[i + 1]; + } + // TODO: slow + var reactParent = ReactMount.getFirstReactDOM(currentPathElement); + if (reactParent === currentPathElement) { + var currentPathElementID = ReactMount.getID(currentPathElement); + var newRootID = ReactInstanceHandles.getReactRootIDFromNodeID(currentPathElementID); + bookKeeping.ancestors.push(currentPathElement); + + var topLevelTargetID = ReactMount.getID(currentPathElement) || ''; + eventsFired++; + ReactEventListener._handleTopLevel(bookKeeping.topLevelType, currentPathElement, topLevelTargetID, bookKeeping.nativeEvent, currentNativeTarget); + + // Jump to the root of this React render tree + while (currentPathElementID !== newRootID) { + i++; + currentPathElement = path[i]; + currentPathElementID = ReactMount.getID(currentPathElement); + } + } + } + if (eventsFired === 0) { + ReactEventListener._handleTopLevel(bookKeeping.topLevelType, window, '', bookKeeping.nativeEvent, getEventTarget(bookKeeping.nativeEvent)); + } +} + +function scrollValueMonitor(cb) { + var scrollPosition = getUnboundedScrollPosition(window); + cb(scrollPosition); +} + +var ReactEventListener = { + _enabled: true, + _handleTopLevel: null, + + WINDOW_HANDLE: ExecutionEnvironment.canUseDOM ? window : null, + + setHandleTopLevel: function (handleTopLevel) { + ReactEventListener._handleTopLevel = handleTopLevel; + }, + + setEnabled: function (enabled) { + ReactEventListener._enabled = !!enabled; + }, + + isEnabled: function () { + return ReactEventListener._enabled; + }, + + /** + * Traps top-level events by using event bubbling. + * + * @param {string} topLevelType Record from `EventConstants`. + * @param {string} handlerBaseName Event name (e.g. "click"). + * @param {object} handle Element on which to attach listener. + * @return {?object} An object with a remove function which will forcefully + * remove the listener. + * @internal + */ + trapBubbledEvent: function (topLevelType, handlerBaseName, handle) { + var element = handle; + if (!element) { + return null; + } + return EventListener.listen(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType)); + }, + + /** + * Traps a top-level event by using event capturing. + * + * @param {string} topLevelType Record from `EventConstants`. + * @param {string} handlerBaseName Event name (e.g. "click"). + * @param {object} handle Element on which to attach listener. + * @return {?object} An object with a remove function which will forcefully + * remove the listener. + * @internal + */ + trapCapturedEvent: function (topLevelType, handlerBaseName, handle) { + var element = handle; + if (!element) { + return null; + } + return EventListener.capture(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType)); + }, + + monitorScrollValue: function (refresh) { + var callback = scrollValueMonitor.bind(null, refresh); + EventListener.listen(window, 'scroll', callback); + }, + + dispatchEvent: function (topLevelType, nativeEvent) { + if (!ReactEventListener._enabled) { + return; + } + + var bookKeeping = TopLevelCallbackBookKeeping.getPooled(topLevelType, nativeEvent); + try { + // Event queue being processed in the same cycle allows + // `preventDefault`. + ReactUpdates.batchedUpdates(handleTopLevelImpl, bookKeeping); + } finally { + TopLevelCallbackBookKeeping.release(bookKeeping); + } + } +}; + +module.exports = ReactEventListener; +},{"128":128,"146":146,"147":147,"158":158,"24":24,"25":25,"67":67,"72":72,"96":96}],64:[function(_dereq_,module,exports){ +/** + * Copyright 2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactFragment + */ + +'use strict'; + +var ReactChildren = _dereq_(32); +var ReactElement = _dereq_(57); + +var emptyFunction = _dereq_(153); +var invariant = _dereq_(161); +var warning = _dereq_(173); + +/** + * We used to allow keyed objects to serve as a collection of ReactElements, + * or nested sets. This allowed us a way to explicitly key a set a fragment of + * components. This is now being replaced with an opaque data structure. + * The upgrade path is to call React.addons.createFragment({ key: value }) to + * create a keyed fragment. The resulting data structure is an array. + */ + +var numericPropertyRegex = /^\d+$/; + +var warnedAboutNumeric = false; + +var ReactFragment = { + // Wrap a keyed object in an opaque proxy that warns you if you access any + // of its properties. + create: function (object) { + if (typeof object !== 'object' || !object || Array.isArray(object)) { + "production" !== 'production' ? warning(false, 'React.addons.createFragment only accepts a single object. Got: %s', object) : undefined; + return object; + } + if (ReactElement.isValidElement(object)) { + "production" !== 'production' ? warning(false, 'React.addons.createFragment does not accept a ReactElement ' + 'without a wrapper object.') : undefined; + return object; + } + + !(object.nodeType !== 1) ? "production" !== 'production' ? invariant(false, 'React.addons.createFragment(...): Encountered an invalid child; DOM ' + 'elements are not valid children of React components.') : invariant(false) : undefined; + + var result = []; + + for (var key in object) { + if ("production" !== 'production') { + if (!warnedAboutNumeric && numericPropertyRegex.test(key)) { + "production" !== 'production' ? warning(false, 'React.addons.createFragment(...): Child objects should have ' + 'non-numeric keys so ordering is preserved.') : undefined; + warnedAboutNumeric = true; + } + } + ReactChildren.mapIntoWithKeyPrefixInternal(object[key], result, key, emptyFunction.thatReturnsArgument); + } + + return result; + } +}; + +module.exports = ReactFragment; +},{"153":153,"161":161,"173":173,"32":32,"57":57}],65:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactInjection + */ + +'use strict'; + +var DOMProperty = _dereq_(10); +var EventPluginHub = _dereq_(16); +var ReactComponentEnvironment = _dereq_(36); +var ReactClass = _dereq_(33); +var ReactEmptyComponent = _dereq_(59); +var ReactBrowserEventEmitter = _dereq_(28); +var ReactNativeComponent = _dereq_(75); +var ReactPerf = _dereq_(78); +var ReactRootIndex = _dereq_(86); +var ReactUpdates = _dereq_(96); + +var ReactInjection = { + Component: ReactComponentEnvironment.injection, + Class: ReactClass.injection, + DOMProperty: DOMProperty.injection, + EmptyComponent: ReactEmptyComponent.injection, + EventPluginHub: EventPluginHub.injection, + EventEmitter: ReactBrowserEventEmitter.injection, + NativeComponent: ReactNativeComponent.injection, + Perf: ReactPerf.injection, + RootIndex: ReactRootIndex.injection, + Updates: ReactUpdates.injection +}; + +module.exports = ReactInjection; +},{"10":10,"16":16,"28":28,"33":33,"36":36,"59":59,"75":75,"78":78,"86":86,"96":96}],66:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactInputSelection + */ + +'use strict'; + +var ReactDOMSelection = _dereq_(49); + +var containsNode = _dereq_(150); +var focusNode = _dereq_(155); +var getActiveElement = _dereq_(156); + +function isInDocument(node) { + return containsNode(document.documentElement, node); +} + +/** + * @ReactInputSelection: React input selection module. Based on Selection.js, + * but modified to be suitable for react and has a couple of bug fixes (doesn't + * assume buttons have range selections allowed). + * Input selection module for React. + */ +var ReactInputSelection = { + + hasSelectionCapabilities: function (elem) { + var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); + return nodeName && (nodeName === 'input' && elem.type === 'text' || nodeName === 'textarea' || elem.contentEditable === 'true'); + }, + + getSelectionInformation: function () { + var focusedElem = getActiveElement(); + return { + focusedElem: focusedElem, + selectionRange: ReactInputSelection.hasSelectionCapabilities(focusedElem) ? ReactInputSelection.getSelection(focusedElem) : null + }; + }, + + /** + * @restoreSelection: If any selection information was potentially lost, + * restore it. This is useful when performing operations that could remove dom + * nodes and place them back in, resulting in focus being lost. + */ + restoreSelection: function (priorSelectionInformation) { + var curFocusedElem = getActiveElement(); + var priorFocusedElem = priorSelectionInformation.focusedElem; + var priorSelectionRange = priorSelectionInformation.selectionRange; + if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) { + if (ReactInputSelection.hasSelectionCapabilities(priorFocusedElem)) { + ReactInputSelection.setSelection(priorFocusedElem, priorSelectionRange); + } + focusNode(priorFocusedElem); + } + }, + + /** + * @getSelection: Gets the selection bounds of a focused textarea, input or + * contentEditable node. + * -@input: Look up selection bounds of this input + * -@return {start: selectionStart, end: selectionEnd} + */ + getSelection: function (input) { + var selection; + + if ('selectionStart' in input) { + // Modern browser with input or textarea. + selection = { + start: input.selectionStart, + end: input.selectionEnd + }; + } else if (document.selection && (input.nodeName && input.nodeName.toLowerCase() === 'input')) { + // IE8 input. + var range = document.selection.createRange(); + // There can only be one selection per document in IE, so it must + // be in our element. + if (range.parentElement() === input) { + selection = { + start: -range.moveStart('character', -input.value.length), + end: -range.moveEnd('character', -input.value.length) + }; + } + } else { + // Content editable or old IE textarea. + selection = ReactDOMSelection.getOffsets(input); + } + + return selection || { start: 0, end: 0 }; + }, + + /** + * @setSelection: Sets the selection bounds of a textarea or input and focuses + * the input. + * -@input Set selection bounds of this input or textarea + * -@offsets Object of same form that is returned from get* + */ + setSelection: function (input, offsets) { + var start = offsets.start; + var end = offsets.end; + if (typeof end === 'undefined') { + end = start; + } + + if ('selectionStart' in input) { + input.selectionStart = start; + input.selectionEnd = Math.min(end, input.value.length); + } else if (document.selection && (input.nodeName && input.nodeName.toLowerCase() === 'input')) { + var range = input.createTextRange(); + range.collapse(true); + range.moveStart('character', start); + range.moveEnd('character', end - start); + range.select(); + } else { + ReactDOMSelection.setOffsets(input, offsets); + } + } +}; + +module.exports = ReactInputSelection; +},{"150":150,"155":155,"156":156,"49":49}],67:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactInstanceHandles + * @typechecks static-only + */ + +'use strict'; + +var ReactRootIndex = _dereq_(86); + +var invariant = _dereq_(161); + +var SEPARATOR = '.'; +var SEPARATOR_LENGTH = SEPARATOR.length; + +/** + * Maximum depth of traversals before we consider the possibility of a bad ID. + */ +var MAX_TREE_DEPTH = 10000; + +/** + * Creates a DOM ID prefix to use when mounting React components. + * + * @param {number} index A unique integer + * @return {string} React root ID. + * @internal + */ +function getReactRootIDString(index) { + return SEPARATOR + index.toString(36); +} + +/** + * Checks if a character in the supplied ID is a separator or the end. + * + * @param {string} id A React DOM ID. + * @param {number} index Index of the character to check. + * @return {boolean} True if the character is a separator or end of the ID. + * @private + */ +function isBoundary(id, index) { + return id.charAt(index) === SEPARATOR || index === id.length; +} + +/** + * Checks if the supplied string is a valid React DOM ID. + * + * @param {string} id A React DOM ID, maybe. + * @return {boolean} True if the string is a valid React DOM ID. + * @private + */ +function isValidID(id) { + return id === '' || id.charAt(0) === SEPARATOR && id.charAt(id.length - 1) !== SEPARATOR; +} + +/** + * Checks if the first ID is an ancestor of or equal to the second ID. + * + * @param {string} ancestorID + * @param {string} descendantID + * @return {boolean} True if `ancestorID` is an ancestor of `descendantID`. + * @internal + */ +function isAncestorIDOf(ancestorID, descendantID) { + return descendantID.indexOf(ancestorID) === 0 && isBoundary(descendantID, ancestorID.length); +} + +/** + * Gets the parent ID of the supplied React DOM ID, `id`. + * + * @param {string} id ID of a component. + * @return {string} ID of the parent, or an empty string. + * @private + */ +function getParentID(id) { + return id ? id.substr(0, id.lastIndexOf(SEPARATOR)) : ''; +} + +/** + * Gets the next DOM ID on the tree path from the supplied `ancestorID` to the + * supplied `destinationID`. If they are equal, the ID is returned. + * + * @param {string} ancestorID ID of an ancestor node of `destinationID`. + * @param {string} destinationID ID of the destination node. + * @return {string} Next ID on the path from `ancestorID` to `destinationID`. + * @private + */ +function getNextDescendantID(ancestorID, destinationID) { + !(isValidID(ancestorID) && isValidID(destinationID)) ? "production" !== 'production' ? invariant(false, 'getNextDescendantID(%s, %s): Received an invalid React DOM ID.', ancestorID, destinationID) : invariant(false) : undefined; + !isAncestorIDOf(ancestorID, destinationID) ? "production" !== 'production' ? invariant(false, 'getNextDescendantID(...): React has made an invalid assumption about ' + 'the DOM hierarchy. Expected `%s` to be an ancestor of `%s`.', ancestorID, destinationID) : invariant(false) : undefined; + if (ancestorID === destinationID) { + return ancestorID; + } + // Skip over the ancestor and the immediate separator. Traverse until we hit + // another separator or we reach the end of `destinationID`. + var start = ancestorID.length + SEPARATOR_LENGTH; + var i; + for (i = start; i < destinationID.length; i++) { + if (isBoundary(destinationID, i)) { + break; + } + } + return destinationID.substr(0, i); +} + +/** + * Gets the nearest common ancestor ID of two IDs. + * + * Using this ID scheme, the nearest common ancestor ID is the longest common + * prefix of the two IDs that immediately preceded a "marker" in both strings. + * + * @param {string} oneID + * @param {string} twoID + * @return {string} Nearest common ancestor ID, or the empty string if none. + * @private + */ +function getFirstCommonAncestorID(oneID, twoID) { + var minLength = Math.min(oneID.length, twoID.length); + if (minLength === 0) { + return ''; + } + var lastCommonMarkerIndex = 0; + // Use `<=` to traverse until the "EOL" of the shorter string. + for (var i = 0; i <= minLength; i++) { + if (isBoundary(oneID, i) && isBoundary(twoID, i)) { + lastCommonMarkerIndex = i; + } else if (oneID.charAt(i) !== twoID.charAt(i)) { + break; + } + } + var longestCommonID = oneID.substr(0, lastCommonMarkerIndex); + !isValidID(longestCommonID) ? "production" !== 'production' ? invariant(false, 'getFirstCommonAncestorID(%s, %s): Expected a valid React DOM ID: %s', oneID, twoID, longestCommonID) : invariant(false) : undefined; + return longestCommonID; +} + +/** + * Traverses the parent path between two IDs (either up or down). The IDs must + * not be the same, and there must exist a parent path between them. If the + * callback returns `false`, traversal is stopped. + * + * @param {?string} start ID at which to start traversal. + * @param {?string} stop ID at which to end traversal. + * @param {function} cb Callback to invoke each ID with. + * @param {*} arg Argument to invoke the callback with. + * @param {?boolean} skipFirst Whether or not to skip the first node. + * @param {?boolean} skipLast Whether or not to skip the last node. + * @private + */ +function traverseParentPath(start, stop, cb, arg, skipFirst, skipLast) { + start = start || ''; + stop = stop || ''; + !(start !== stop) ? "production" !== 'production' ? invariant(false, 'traverseParentPath(...): Cannot traverse from and to the same ID, `%s`.', start) : invariant(false) : undefined; + var traverseUp = isAncestorIDOf(stop, start); + !(traverseUp || isAncestorIDOf(start, stop)) ? "production" !== 'production' ? invariant(false, 'traverseParentPath(%s, %s, ...): Cannot traverse from two IDs that do ' + 'not have a parent path.', start, stop) : invariant(false) : undefined; + // Traverse from `start` to `stop` one depth at a time. + var depth = 0; + var traverse = traverseUp ? getParentID : getNextDescendantID; + for (var id = start;; /* until break */id = traverse(id, stop)) { + var ret; + if ((!skipFirst || id !== start) && (!skipLast || id !== stop)) { + ret = cb(id, traverseUp, arg); + } + if (ret === false || id === stop) { + // Only break //after// visiting `stop`. + break; + } + !(depth++ < MAX_TREE_DEPTH) ? "production" !== 'production' ? invariant(false, 'traverseParentPath(%s, %s, ...): Detected an infinite loop while ' + 'traversing the React DOM ID tree. This may be due to malformed IDs: %s', start, stop, id) : invariant(false) : undefined; + } +} + +/** + * Manages the IDs assigned to DOM representations of React components. This + * uses a specific scheme in order to traverse the DOM efficiently (e.g. in + * order to simulate events). + * + * @internal + */ +var ReactInstanceHandles = { + + /** + * Constructs a React root ID + * @return {string} A React root ID. + */ + createReactRootID: function () { + return getReactRootIDString(ReactRootIndex.createReactRootIndex()); + }, + + /** + * Constructs a React ID by joining a root ID with a name. + * + * @param {string} rootID Root ID of a parent component. + * @param {string} name A component's name (as flattened children). + * @return {string} A React ID. + * @internal + */ + createReactID: function (rootID, name) { + return rootID + name; + }, + + /** + * Gets the DOM ID of the React component that is the root of the tree that + * contains the React component with the supplied DOM ID. + * + * @param {string} id DOM ID of a React component. + * @return {?string} DOM ID of the React component that is the root. + * @internal + */ + getReactRootIDFromNodeID: function (id) { + if (id && id.charAt(0) === SEPARATOR && id.length > 1) { + var index = id.indexOf(SEPARATOR, 1); + return index > -1 ? id.substr(0, index) : id; + } + return null; + }, + + /** + * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that + * should would receive a `mouseEnter` or `mouseLeave` event. + * + * NOTE: Does not invoke the callback on the nearest common ancestor because + * nothing "entered" or "left" that element. + * + * @param {string} leaveID ID being left. + * @param {string} enterID ID being entered. + * @param {function} cb Callback to invoke on each entered/left ID. + * @param {*} upArg Argument to invoke the callback with on left IDs. + * @param {*} downArg Argument to invoke the callback with on entered IDs. + * @internal + */ + traverseEnterLeave: function (leaveID, enterID, cb, upArg, downArg) { + var ancestorID = getFirstCommonAncestorID(leaveID, enterID); + if (ancestorID !== leaveID) { + traverseParentPath(leaveID, ancestorID, cb, upArg, false, true); + } + if (ancestorID !== enterID) { + traverseParentPath(ancestorID, enterID, cb, downArg, true, false); + } + }, + + /** + * Simulates the traversal of a two-phase, capture/bubble event dispatch. + * + * NOTE: This traversal happens on IDs without touching the DOM. + * + * @param {string} targetID ID of the target node. + * @param {function} cb Callback to invoke. + * @param {*} arg Argument to invoke the callback with. + * @internal + */ + traverseTwoPhase: function (targetID, cb, arg) { + if (targetID) { + traverseParentPath('', targetID, cb, arg, true, false); + traverseParentPath(targetID, '', cb, arg, false, true); + } + }, + + /** + * Same as `traverseTwoPhase` but skips the `targetID`. + */ + traverseTwoPhaseSkipTarget: function (targetID, cb, arg) { + if (targetID) { + traverseParentPath('', targetID, cb, arg, true, true); + traverseParentPath(targetID, '', cb, arg, true, true); + } + }, + + /** + * Traverse a node ID, calling the supplied `cb` for each ancestor ID. For + * example, passing `.0.$row-0.1` would result in `cb` getting called + * with `.0`, `.0.$row-0`, and `.0.$row-0.1`. + * + * NOTE: This traversal happens on IDs without touching the DOM. + * + * @param {string} targetID ID of the target node. + * @param {function} cb Callback to invoke. + * @param {*} arg Argument to invoke the callback with. + * @internal + */ + traverseAncestors: function (targetID, cb, arg) { + traverseParentPath('', targetID, cb, arg, true, false); + }, + + getFirstCommonAncestorID: getFirstCommonAncestorID, + + /** + * Exposed for unit testing. + * @private + */ + _getNextDescendantID: getNextDescendantID, + + isAncestorIDOf: isAncestorIDOf, + + SEPARATOR: SEPARATOR + +}; + +module.exports = ReactInstanceHandles; +},{"161":161,"86":86}],68:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactInstanceMap + */ + +'use strict'; + +/** + * `ReactInstanceMap` maintains a mapping from a public facing stateful + * instance (key) and the internal representation (value). This allows public + * methods to accept the user facing instance as an argument and map them back + * to internal methods. + */ + +// TODO: Replace this with ES6: var ReactInstanceMap = new Map(); +var ReactInstanceMap = { + + /** + * This API should be called `delete` but we'd have to make sure to always + * transform these to strings for IE support. When this transform is fully + * supported we can rename it. + */ + remove: function (key) { + key._reactInternalInstance = undefined; + }, + + get: function (key) { + return key._reactInternalInstance; + }, + + has: function (key) { + return key._reactInternalInstance !== undefined; + }, + + set: function (key, value) { + key._reactInternalInstance = value; + } + +}; + +module.exports = ReactInstanceMap; +},{}],69:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactIsomorphic + */ + +'use strict'; + +var ReactChildren = _dereq_(32); +var ReactComponent = _dereq_(34); +var ReactClass = _dereq_(33); +var ReactDOMFactories = _dereq_(43); +var ReactElement = _dereq_(57); +var ReactElementValidator = _dereq_(58); +var ReactPropTypes = _dereq_(82); +var ReactVersion = _dereq_(97); + +var assign = _dereq_(24); +var onlyChild = _dereq_(135); + +var createElement = ReactElement.createElement; +var createFactory = ReactElement.createFactory; +var cloneElement = ReactElement.cloneElement; + +if ("production" !== 'production') { + createElement = ReactElementValidator.createElement; + createFactory = ReactElementValidator.createFactory; + cloneElement = ReactElementValidator.cloneElement; +} + +var React = { + + // Modern + + Children: { + map: ReactChildren.map, + forEach: ReactChildren.forEach, + count: ReactChildren.count, + toArray: ReactChildren.toArray, + only: onlyChild + }, + + Component: ReactComponent, + + createElement: createElement, + cloneElement: cloneElement, + isValidElement: ReactElement.isValidElement, + + // Classic + + PropTypes: ReactPropTypes, + createClass: ReactClass.createClass, + createFactory: createFactory, + createMixin: function (mixin) { + // Currently a noop. Will be used to validate and trace mixins. + return mixin; + }, + + // This looks DOM specific but these are actually isomorphic helpers + // since they are just generating DOM strings. + DOM: ReactDOMFactories, + + version: ReactVersion, + + // Hook for JSX spread, don't use this for anything else. + __spread: assign +}; + +module.exports = React; +},{"135":135,"24":24,"32":32,"33":33,"34":34,"43":43,"57":57,"58":58,"82":82,"97":97}],70:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactLink + * @typechecks static-only + */ + +'use strict'; + +/** + * ReactLink encapsulates a common pattern in which a component wants to modify + * a prop received from its parent. ReactLink allows the parent to pass down a + * value coupled with a callback that, when invoked, expresses an intent to + * modify that value. For example: + * + * React.createClass({ + * getInitialState: function() { + * return {value: ''}; + * }, + * render: function() { + * var valueLink = new ReactLink(this.state.value, this._handleValueChange); + * return <input valueLink={valueLink} />; + * }, + * _handleValueChange: function(newValue) { + * this.setState({value: newValue}); + * } + * }); + * + * We have provided some sugary mixins to make the creation and + * consumption of ReactLink easier; see LinkedValueUtils and LinkedStateMixin. + */ + +var React = _dereq_(26); + +/** + * @param {*} value current value of the link + * @param {function} requestChange callback to request a change + */ +function ReactLink(value, requestChange) { + this.value = value; + this.requestChange = requestChange; +} + +/** + * Creates a PropType that enforces the ReactLink API and optionally checks the + * type of the value being passed inside the link. Example: + * + * MyComponent.propTypes = { + * tabIndexLink: ReactLink.PropTypes.link(React.PropTypes.number) + * } + */ +function createLinkTypeChecker(linkType) { + var shapes = { + value: typeof linkType === 'undefined' ? React.PropTypes.any.isRequired : linkType.isRequired, + requestChange: React.PropTypes.func.isRequired + }; + return React.PropTypes.shape(shapes); +} + +ReactLink.PropTypes = { + link: createLinkTypeChecker +}; + +module.exports = ReactLink; +},{"26":26}],71:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactMarkupChecksum + */ + +'use strict'; + +var adler32 = _dereq_(116); + +var TAG_END = /\/?>/; + +var ReactMarkupChecksum = { + CHECKSUM_ATTR_NAME: 'data-react-checksum', + + /** + * @param {string} markup Markup string + * @return {string} Markup string with checksum attribute attached + */ + addChecksumToMarkup: function (markup) { + var checksum = adler32(markup); + + // Add checksum (handle both parent tags and self-closing tags) + return markup.replace(TAG_END, ' ' + ReactMarkupChecksum.CHECKSUM_ATTR_NAME + '="' + checksum + '"$&'); + }, + + /** + * @param {string} markup to use + * @param {DOMElement} element root React element + * @returns {boolean} whether or not the markup is the same + */ + canReuseMarkup: function (markup, element) { + var existingChecksum = element.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME); + existingChecksum = existingChecksum && parseInt(existingChecksum, 10); + var markupChecksum = adler32(markup); + return markupChecksum === existingChecksum; + } +}; + +module.exports = ReactMarkupChecksum; +},{"116":116}],72:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactMount + */ + +'use strict'; + +var DOMProperty = _dereq_(10); +var ReactBrowserEventEmitter = _dereq_(28); +var ReactCurrentOwner = _dereq_(39); +var ReactDOMFeatureFlags = _dereq_(44); +var ReactElement = _dereq_(57); +var ReactEmptyComponentRegistry = _dereq_(60); +var ReactInstanceHandles = _dereq_(67); +var ReactInstanceMap = _dereq_(68); +var ReactMarkupChecksum = _dereq_(71); +var ReactPerf = _dereq_(78); +var ReactReconciler = _dereq_(84); +var ReactUpdateQueue = _dereq_(95); +var ReactUpdates = _dereq_(96); + +var assign = _dereq_(24); +var emptyObject = _dereq_(154); +var containsNode = _dereq_(150); +var instantiateReactComponent = _dereq_(132); +var invariant = _dereq_(161); +var setInnerHTML = _dereq_(138); +var shouldUpdateReactComponent = _dereq_(141); +var validateDOMNesting = _dereq_(144); +var warning = _dereq_(173); + +var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME; +var nodeCache = {}; + +var ELEMENT_NODE_TYPE = 1; +var DOC_NODE_TYPE = 9; +var DOCUMENT_FRAGMENT_NODE_TYPE = 11; + +var ownerDocumentContextKey = '__ReactMount_ownerDocument$' + Math.random().toString(36).slice(2); + +/** Mapping from reactRootID to React component instance. */ +var instancesByReactRootID = {}; + +/** Mapping from reactRootID to `container` nodes. */ +var containersByReactRootID = {}; + +if ("production" !== 'production') { + /** __DEV__-only mapping from reactRootID to root elements. */ + var rootElementsByReactRootID = {}; +} + +// Used to store breadth-first search state in findComponentRoot. +var findComponentRootReusableArray = []; + +/** + * Finds the index of the first character + * that's not common between the two given strings. + * + * @return {number} the index of the character where the strings diverge + */ +function firstDifferenceIndex(string1, string2) { + var minLen = Math.min(string1.length, string2.length); + for (var i = 0; i < minLen; i++) { + if (string1.charAt(i) !== string2.charAt(i)) { + return i; + } + } + return string1.length === string2.length ? -1 : minLen; +} + +/** + * @param {DOMElement|DOMDocument} container DOM element that may contain + * a React component + * @return {?*} DOM element that may have the reactRoot ID, or null. + */ +function getReactRootElementInContainer(container) { + if (!container) { + return null; + } + + if (container.nodeType === DOC_NODE_TYPE) { + return container.documentElement; + } else { + return container.firstChild; + } +} + +/** + * @param {DOMElement} container DOM element that may contain a React component. + * @return {?string} A "reactRoot" ID, if a React component is rendered. + */ +function getReactRootID(container) { + var rootElement = getReactRootElementInContainer(container); + return rootElement && ReactMount.getID(rootElement); +} + +/** + * Accessing node[ATTR_NAME] or calling getAttribute(ATTR_NAME) on a form + * element can return its control whose name or ID equals ATTR_NAME. All + * DOM nodes support `getAttributeNode` but this can also get called on + * other objects so just return '' if we're given something other than a + * DOM node (such as window). + * + * @param {?DOMElement|DOMWindow|DOMDocument|DOMTextNode} node DOM node. + * @return {string} ID of the supplied `domNode`. + */ +function getID(node) { + var id = internalGetID(node); + if (id) { + if (nodeCache.hasOwnProperty(id)) { + var cached = nodeCache[id]; + if (cached !== node) { + !!isValid(cached, id) ? "production" !== 'production' ? invariant(false, 'ReactMount: Two valid but unequal nodes with the same `%s`: %s', ATTR_NAME, id) : invariant(false) : undefined; + + nodeCache[id] = node; + } + } else { + nodeCache[id] = node; + } + } + + return id; +} + +function internalGetID(node) { + // If node is something like a window, document, or text node, none of + // which support attributes or a .getAttribute method, gracefully return + // the empty string, as if the attribute were missing. + return node && node.getAttribute && node.getAttribute(ATTR_NAME) || ''; +} + +/** + * Sets the React-specific ID of the given node. + * + * @param {DOMElement} node The DOM node whose ID will be set. + * @param {string} id The value of the ID attribute. + */ +function setID(node, id) { + var oldID = internalGetID(node); + if (oldID !== id) { + delete nodeCache[oldID]; + } + node.setAttribute(ATTR_NAME, id); + nodeCache[id] = node; +} + +/** + * Finds the node with the supplied React-generated DOM ID. + * + * @param {string} id A React-generated DOM ID. + * @return {DOMElement} DOM node with the suppled `id`. + * @internal + */ +function getNode(id) { + if (!nodeCache.hasOwnProperty(id) || !isValid(nodeCache[id], id)) { + nodeCache[id] = ReactMount.findReactNodeByID(id); + } + return nodeCache[id]; +} + +/** + * Finds the node with the supplied public React instance. + * + * @param {*} instance A public React instance. + * @return {?DOMElement} DOM node with the suppled `id`. + * @internal + */ +function getNodeFromInstance(instance) { + var id = ReactInstanceMap.get(instance)._rootNodeID; + if (ReactEmptyComponentRegistry.isNullComponentID(id)) { + return null; + } + if (!nodeCache.hasOwnProperty(id) || !isValid(nodeCache[id], id)) { + nodeCache[id] = ReactMount.findReactNodeByID(id); + } + return nodeCache[id]; +} + +/** + * A node is "valid" if it is contained by a currently mounted container. + * + * This means that the node does not have to be contained by a document in + * order to be considered valid. + * + * @param {?DOMElement} node The candidate DOM node. + * @param {string} id The expected ID of the node. + * @return {boolean} Whether the node is contained by a mounted container. + */ +function isValid(node, id) { + if (node) { + !(internalGetID(node) === id) ? "production" !== 'production' ? invariant(false, 'ReactMount: Unexpected modification of `%s`', ATTR_NAME) : invariant(false) : undefined; + + var container = ReactMount.findReactContainerForID(id); + if (container && containsNode(container, node)) { + return true; + } + } + + return false; +} + +/** + * Causes the cache to forget about one React-specific ID. + * + * @param {string} id The ID to forget. + */ +function purgeID(id) { + delete nodeCache[id]; +} + +var deepestNodeSoFar = null; +function findDeepestCachedAncestorImpl(ancestorID) { + var ancestor = nodeCache[ancestorID]; + if (ancestor && isValid(ancestor, ancestorID)) { + deepestNodeSoFar = ancestor; + } else { + // This node isn't populated in the cache, so presumably none of its + // descendants are. Break out of the loop. + return false; + } +} + +/** + * Return the deepest cached node whose ID is a prefix of `targetID`. + */ +function findDeepestCachedAncestor(targetID) { + deepestNodeSoFar = null; + ReactInstanceHandles.traverseAncestors(targetID, findDeepestCachedAncestorImpl); + + var foundNode = deepestNodeSoFar; + deepestNodeSoFar = null; + return foundNode; +} + +/** + * Mounts this component and inserts it into the DOM. + * + * @param {ReactComponent} componentInstance The instance to mount. + * @param {string} rootID DOM ID of the root node. + * @param {DOMElement} container DOM element to mount into. + * @param {ReactReconcileTransaction} transaction + * @param {boolean} shouldReuseMarkup If true, do not insert markup + */ +function mountComponentIntoNode(componentInstance, rootID, container, transaction, shouldReuseMarkup, context) { + if (ReactDOMFeatureFlags.useCreateElement) { + context = assign({}, context); + if (container.nodeType === DOC_NODE_TYPE) { + context[ownerDocumentContextKey] = container; + } else { + context[ownerDocumentContextKey] = container.ownerDocument; + } + } + if ("production" !== 'production') { + if (context === emptyObject) { + context = {}; + } + var tag = container.nodeName.toLowerCase(); + context[validateDOMNesting.ancestorInfoContextKey] = validateDOMNesting.updatedAncestorInfo(null, tag, null); + } + var markup = ReactReconciler.mountComponent(componentInstance, rootID, transaction, context); + componentInstance._renderedComponent._topLevelWrapper = componentInstance; + ReactMount._mountImageIntoNode(markup, container, shouldReuseMarkup, transaction); +} + +/** + * Batched mount. + * + * @param {ReactComponent} componentInstance The instance to mount. + * @param {string} rootID DOM ID of the root node. + * @param {DOMElement} container DOM element to mount into. + * @param {boolean} shouldReuseMarkup If true, do not insert markup + */ +function batchedMountComponentIntoNode(componentInstance, rootID, container, shouldReuseMarkup, context) { + var transaction = ReactUpdates.ReactReconcileTransaction.getPooled( + /* forceHTML */shouldReuseMarkup); + transaction.perform(mountComponentIntoNode, null, componentInstance, rootID, container, transaction, shouldReuseMarkup, context); + ReactUpdates.ReactReconcileTransaction.release(transaction); +} + +/** + * Unmounts a component and removes it from the DOM. + * + * @param {ReactComponent} instance React component instance. + * @param {DOMElement} container DOM element to unmount from. + * @final + * @internal + * @see {ReactMount.unmountComponentAtNode} + */ +function unmountComponentFromNode(instance, container) { + ReactReconciler.unmountComponent(instance); + + if (container.nodeType === DOC_NODE_TYPE) { + container = container.documentElement; + } + + // http://jsperf.com/emptying-a-node + while (container.lastChild) { + container.removeChild(container.lastChild); + } +} + +/** + * True if the supplied DOM node has a direct React-rendered child that is + * not a React root element. Useful for warning in `render`, + * `unmountComponentAtNode`, etc. + * + * @param {?DOMElement} node The candidate DOM node. + * @return {boolean} True if the DOM element contains a direct child that was + * rendered by React but is not a root element. + * @internal + */ +function hasNonRootReactChild(node) { + var reactRootID = getReactRootID(node); + return reactRootID ? reactRootID !== ReactInstanceHandles.getReactRootIDFromNodeID(reactRootID) : false; +} + +/** + * Returns the first (deepest) ancestor of a node which is rendered by this copy + * of React. + */ +function findFirstReactDOMImpl(node) { + // This node might be from another React instance, so we make sure not to + // examine the node cache here + for (; node && node.parentNode !== node; node = node.parentNode) { + if (node.nodeType !== 1) { + // Not a DOMElement, therefore not a React component + continue; + } + var nodeID = internalGetID(node); + if (!nodeID) { + continue; + } + var reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(nodeID); + + // If containersByReactRootID contains the container we find by crawling up + // the tree, we know that this instance of React rendered the node. + // nb. isValid's strategy (with containsNode) does not work because render + // trees may be nested and we don't want a false positive in that case. + var current = node; + var lastID; + do { + lastID = internalGetID(current); + current = current.parentNode; + if (current == null) { + // The passed-in node has been detached from the container it was + // originally rendered into. + return null; + } + } while (lastID !== reactRootID); + + if (current === containersByReactRootID[reactRootID]) { + return node; + } + } + return null; +} + +/** + * Temporary (?) hack so that we can store all top-level pending updates on + * composites instead of having to worry about different types of components + * here. + */ +var TopLevelWrapper = function () {}; +TopLevelWrapper.prototype.isReactComponent = {}; +if ("production" !== 'production') { + TopLevelWrapper.displayName = 'TopLevelWrapper'; +} +TopLevelWrapper.prototype.render = function () { + // this.props is actually a ReactElement + return this.props; +}; + +/** + * Mounting is the process of initializing a React component by creating its + * representative DOM elements and inserting them into a supplied `container`. + * Any prior content inside `container` is destroyed in the process. + * + * ReactMount.render( + * component, + * document.getElementById('container') + * ); + * + * <div id="container"> <-- Supplied `container`. + * <div data-reactid=".3"> <-- Rendered reactRoot of React + * // ... component. + * </div> + * </div> + * + * Inside of `container`, the first element rendered is the "reactRoot". + */ +var ReactMount = { + + TopLevelWrapper: TopLevelWrapper, + + /** Exposed for debugging purposes **/ + _instancesByReactRootID: instancesByReactRootID, + + /** + * This is a hook provided to support rendering React components while + * ensuring that the apparent scroll position of its `container` does not + * change. + * + * @param {DOMElement} container The `container` being rendered into. + * @param {function} renderCallback This must be called once to do the render. + */ + scrollMonitor: function (container, renderCallback) { + renderCallback(); + }, + + /** + * Take a component that's already mounted into the DOM and replace its props + * @param {ReactComponent} prevComponent component instance already in the DOM + * @param {ReactElement} nextElement component instance to render + * @param {DOMElement} container container to render into + * @param {?function} callback function triggered on completion + */ + _updateRootComponent: function (prevComponent, nextElement, container, callback) { + ReactMount.scrollMonitor(container, function () { + ReactUpdateQueue.enqueueElementInternal(prevComponent, nextElement); + if (callback) { + ReactUpdateQueue.enqueueCallbackInternal(prevComponent, callback); + } + }); + + if ("production" !== 'production') { + // Record the root element in case it later gets transplanted. + rootElementsByReactRootID[getReactRootID(container)] = getReactRootElementInContainer(container); + } + + return prevComponent; + }, + + /** + * Register a component into the instance map and starts scroll value + * monitoring + * @param {ReactComponent} nextComponent component instance to render + * @param {DOMElement} container container to render into + * @return {string} reactRoot ID prefix + */ + _registerComponent: function (nextComponent, container) { + !(container && (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE || container.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)) ? "production" !== 'production' ? invariant(false, '_registerComponent(...): Target container is not a DOM element.') : invariant(false) : undefined; + + ReactBrowserEventEmitter.ensureScrollValueMonitoring(); + + var reactRootID = ReactMount.registerContainer(container); + instancesByReactRootID[reactRootID] = nextComponent; + return reactRootID; + }, + + /** + * Render a new component into the DOM. + * @param {ReactElement} nextElement element to render + * @param {DOMElement} container container to render into + * @param {boolean} shouldReuseMarkup if we should skip the markup insertion + * @return {ReactComponent} nextComponent + */ + _renderNewRootComponent: function (nextElement, container, shouldReuseMarkup, context) { + // Various parts of our code (such as ReactCompositeComponent's + // _renderValidatedComponent) assume that calls to render aren't nested; + // verify that that's the case. + "production" !== 'production' ? warning(ReactCurrentOwner.current == null, '_renderNewRootComponent(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from ' + 'render is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : undefined; + + var componentInstance = instantiateReactComponent(nextElement, null); + var reactRootID = ReactMount._registerComponent(componentInstance, container); + + // The initial render is synchronous but any updates that happen during + // rendering, in componentWillMount or componentDidMount, will be batched + // according to the current batching strategy. + + ReactUpdates.batchedUpdates(batchedMountComponentIntoNode, componentInstance, reactRootID, container, shouldReuseMarkup, context); + + if ("production" !== 'production') { + // Record the root element in case it later gets transplanted. + rootElementsByReactRootID[reactRootID] = getReactRootElementInContainer(container); + } + + return componentInstance; + }, + + /** + * Renders a React component into the DOM in the supplied `container`. + * + * If the React component was previously rendered into `container`, this will + * perform an update on it and only mutate the DOM as necessary to reflect the + * latest React component. + * + * @param {ReactComponent} parentComponent The conceptual parent of this render tree. + * @param {ReactElement} nextElement Component element to render. + * @param {DOMElement} container DOM element to render into. + * @param {?function} callback function triggered on completion + * @return {ReactComponent} Component instance rendered in `container`. + */ + renderSubtreeIntoContainer: function (parentComponent, nextElement, container, callback) { + !(parentComponent != null && parentComponent._reactInternalInstance != null) ? "production" !== 'production' ? invariant(false, 'parentComponent must be a valid React Component') : invariant(false) : undefined; + return ReactMount._renderSubtreeIntoContainer(parentComponent, nextElement, container, callback); + }, + + _renderSubtreeIntoContainer: function (parentComponent, nextElement, container, callback) { + !ReactElement.isValidElement(nextElement) ? "production" !== 'production' ? invariant(false, 'ReactDOM.render(): Invalid component element.%s', typeof nextElement === 'string' ? ' Instead of passing an element string, make sure to instantiate ' + 'it by passing it to React.createElement.' : typeof nextElement === 'function' ? ' Instead of passing a component class, make sure to instantiate ' + 'it by passing it to React.createElement.' : + // Check if it quacks like an element + nextElement != null && nextElement.props !== undefined ? ' This may be caused by unintentionally loading two independent ' + 'copies of React.' : '') : invariant(false) : undefined; + + "production" !== 'production' ? warning(!container || !container.tagName || container.tagName.toUpperCase() !== 'BODY', 'render(): Rendering components directly into document.body is ' + 'discouraged, since its children are often manipulated by third-party ' + 'scripts and browser extensions. This may lead to subtle ' + 'reconciliation issues. Try rendering into a container element created ' + 'for your app.') : undefined; + + var nextWrappedElement = new ReactElement(TopLevelWrapper, null, null, null, null, null, nextElement); + + var prevComponent = instancesByReactRootID[getReactRootID(container)]; + + if (prevComponent) { + var prevWrappedElement = prevComponent._currentElement; + var prevElement = prevWrappedElement.props; + if (shouldUpdateReactComponent(prevElement, nextElement)) { + var publicInst = prevComponent._renderedComponent.getPublicInstance(); + var updatedCallback = callback && function () { + callback.call(publicInst); + }; + ReactMount._updateRootComponent(prevComponent, nextWrappedElement, container, updatedCallback); + return publicInst; + } else { + ReactMount.unmountComponentAtNode(container); + } + } + + var reactRootElement = getReactRootElementInContainer(container); + var containerHasReactMarkup = reactRootElement && !!internalGetID(reactRootElement); + var containerHasNonRootReactChild = hasNonRootReactChild(container); + + if ("production" !== 'production') { + "production" !== 'production' ? warning(!containerHasNonRootReactChild, 'render(...): Replacing React-rendered children with a new root ' + 'component. If you intended to update the children of this node, ' + 'you should instead have the existing children update their state ' + 'and render the new components instead of calling ReactDOM.render.') : undefined; + + if (!containerHasReactMarkup || reactRootElement.nextSibling) { + var rootElementSibling = reactRootElement; + while (rootElementSibling) { + if (internalGetID(rootElementSibling)) { + "production" !== 'production' ? warning(false, 'render(): Target node has markup rendered by React, but there ' + 'are unrelated nodes as well. This is most commonly caused by ' + 'white-space inserted around server-rendered markup.') : undefined; + break; + } + rootElementSibling = rootElementSibling.nextSibling; + } + } + } + + var shouldReuseMarkup = containerHasReactMarkup && !prevComponent && !containerHasNonRootReactChild; + var component = ReactMount._renderNewRootComponent(nextWrappedElement, container, shouldReuseMarkup, parentComponent != null ? parentComponent._reactInternalInstance._processChildContext(parentComponent._reactInternalInstance._context) : emptyObject)._renderedComponent.getPublicInstance(); + if (callback) { + callback.call(component); + } + return component; + }, + + /** + * Renders a React component into the DOM in the supplied `container`. + * + * If the React component was previously rendered into `container`, this will + * perform an update on it and only mutate the DOM as necessary to reflect the + * latest React component. + * + * @param {ReactElement} nextElement Component element to render. + * @param {DOMElement} container DOM element to render into. + * @param {?function} callback function triggered on completion + * @return {ReactComponent} Component instance rendered in `container`. + */ + render: function (nextElement, container, callback) { + return ReactMount._renderSubtreeIntoContainer(null, nextElement, container, callback); + }, + + /** + * Registers a container node into which React components will be rendered. + * This also creates the "reactRoot" ID that will be assigned to the element + * rendered within. + * + * @param {DOMElement} container DOM element to register as a container. + * @return {string} The "reactRoot" ID of elements rendered within. + */ + registerContainer: function (container) { + var reactRootID = getReactRootID(container); + if (reactRootID) { + // If one exists, make sure it is a valid "reactRoot" ID. + reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(reactRootID); + } + if (!reactRootID) { + // No valid "reactRoot" ID found, create one. + reactRootID = ReactInstanceHandles.createReactRootID(); + } + containersByReactRootID[reactRootID] = container; + return reactRootID; + }, + + /** + * Unmounts and destroys the React component rendered in the `container`. + * + * @param {DOMElement} container DOM element containing a React component. + * @return {boolean} True if a component was found in and unmounted from + * `container` + */ + unmountComponentAtNode: function (container) { + // Various parts of our code (such as ReactCompositeComponent's + // _renderValidatedComponent) assume that calls to render aren't nested; + // verify that that's the case. (Strictly speaking, unmounting won't cause a + // render but we still don't expect to be in a render call here.) + "production" !== 'production' ? warning(ReactCurrentOwner.current == null, 'unmountComponentAtNode(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from render ' + 'is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : undefined; + + !(container && (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE || container.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)) ? "production" !== 'production' ? invariant(false, 'unmountComponentAtNode(...): Target container is not a DOM element.') : invariant(false) : undefined; + + var reactRootID = getReactRootID(container); + var component = instancesByReactRootID[reactRootID]; + if (!component) { + // Check if the node being unmounted was rendered by React, but isn't a + // root node. + var containerHasNonRootReactChild = hasNonRootReactChild(container); + + // Check if the container itself is a React root node. + var containerID = internalGetID(container); + var isContainerReactRoot = containerID && containerID === ReactInstanceHandles.getReactRootIDFromNodeID(containerID); + + if ("production" !== 'production') { + "production" !== 'production' ? warning(!containerHasNonRootReactChild, 'unmountComponentAtNode(): The node you\'re attempting to unmount ' + 'was rendered by React and is not a top-level container. %s', isContainerReactRoot ? 'You may have accidentally passed in a React root node instead ' + 'of its container.' : 'Instead, have the parent component update its state and ' + 'rerender in order to remove this component.') : undefined; + } + + return false; + } + ReactUpdates.batchedUpdates(unmountComponentFromNode, component, container); + delete instancesByReactRootID[reactRootID]; + delete containersByReactRootID[reactRootID]; + if ("production" !== 'production') { + delete rootElementsByReactRootID[reactRootID]; + } + return true; + }, + + /** + * Finds the container DOM element that contains React component to which the + * supplied DOM `id` belongs. + * + * @param {string} id The ID of an element rendered by a React component. + * @return {?DOMElement} DOM element that contains the `id`. + */ + findReactContainerForID: function (id) { + var reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(id); + var container = containersByReactRootID[reactRootID]; + + if ("production" !== 'production') { + var rootElement = rootElementsByReactRootID[reactRootID]; + if (rootElement && rootElement.parentNode !== container) { + "production" !== 'production' ? warning( + // Call internalGetID here because getID calls isValid which calls + // findReactContainerForID (this function). + internalGetID(rootElement) === reactRootID, 'ReactMount: Root element ID differed from reactRootID.') : undefined; + var containerChild = container.firstChild; + if (containerChild && reactRootID === internalGetID(containerChild)) { + // If the container has a new child with the same ID as the old + // root element, then rootElementsByReactRootID[reactRootID] is + // just stale and needs to be updated. The case that deserves a + // warning is when the container is empty. + rootElementsByReactRootID[reactRootID] = containerChild; + } else { + "production" !== 'production' ? warning(false, 'ReactMount: Root element has been removed from its original ' + 'container. New container: %s', rootElement.parentNode) : undefined; + } + } + } + + return container; + }, + + /** + * Finds an element rendered by React with the supplied ID. + * + * @param {string} id ID of a DOM node in the React component. + * @return {DOMElement} Root DOM node of the React component. + */ + findReactNodeByID: function (id) { + var reactRoot = ReactMount.findReactContainerForID(id); + return ReactMount.findComponentRoot(reactRoot, id); + }, + + /** + * Traverses up the ancestors of the supplied node to find a node that is a + * DOM representation of a React component rendered by this copy of React. + * + * @param {*} node + * @return {?DOMEventTarget} + * @internal + */ + getFirstReactDOM: function (node) { + return findFirstReactDOMImpl(node); + }, + + /** + * Finds a node with the supplied `targetID` inside of the supplied + * `ancestorNode`. Exploits the ID naming scheme to perform the search + * quickly. + * + * @param {DOMEventTarget} ancestorNode Search from this root. + * @pararm {string} targetID ID of the DOM representation of the component. + * @return {DOMEventTarget} DOM node with the supplied `targetID`. + * @internal + */ + findComponentRoot: function (ancestorNode, targetID) { + var firstChildren = findComponentRootReusableArray; + var childIndex = 0; + + var deepestAncestor = findDeepestCachedAncestor(targetID) || ancestorNode; + + if ("production" !== 'production') { + // This will throw on the next line; give an early warning + "production" !== 'production' ? warning(deepestAncestor != null, 'React can\'t find the root component node for data-reactid value ' + '`%s`. If you\'re seeing this message, it probably means that ' + 'you\'ve loaded two copies of React on the page. At this time, only ' + 'a single copy of React can be loaded at a time.', targetID) : undefined; + } + + firstChildren[0] = deepestAncestor.firstChild; + firstChildren.length = 1; + + while (childIndex < firstChildren.length) { + var child = firstChildren[childIndex++]; + var targetChild; + + while (child) { + var childID = ReactMount.getID(child); + if (childID) { + // Even if we find the node we're looking for, we finish looping + // through its siblings to ensure they're cached so that we don't have + // to revisit this node again. Otherwise, we make n^2 calls to getID + // when visiting the many children of a single node in order. + + if (targetID === childID) { + targetChild = child; + } else if (ReactInstanceHandles.isAncestorIDOf(childID, targetID)) { + // If we find a child whose ID is an ancestor of the given ID, + // then we can be sure that we only want to search the subtree + // rooted at this child, so we can throw out the rest of the + // search state. + firstChildren.length = childIndex = 0; + firstChildren.push(child.firstChild); + } + } else { + // If this child had no ID, then there's a chance that it was + // injected automatically by the browser, as when a `<table>` + // element sprouts an extra `<tbody>` child as a side effect of + // `.innerHTML` parsing. Optimistically continue down this + // branch, but not before examining the other siblings. + firstChildren.push(child.firstChild); + } + + child = child.nextSibling; + } + + if (targetChild) { + // Emptying firstChildren/findComponentRootReusableArray is + // not necessary for correctness, but it helps the GC reclaim + // any nodes that were left at the end of the search. + firstChildren.length = 0; + + return targetChild; + } + } + + firstChildren.length = 0; + + !false ? "production" !== 'production' ? invariant(false, 'findComponentRoot(..., %s): Unable to find element. This probably ' + 'means the DOM was unexpectedly mutated (e.g., by the browser), ' + 'usually due to forgetting a <tbody> when using tables, nesting tags ' + 'like <form>, <p>, or <a>, or using non-SVG elements in an <svg> ' + 'parent. ' + 'Try inspecting the child nodes of the element with React ID `%s`.', targetID, ReactMount.getID(ancestorNode)) : invariant(false) : undefined; + }, + + _mountImageIntoNode: function (markup, container, shouldReuseMarkup, transaction) { + !(container && (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE || container.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)) ? "production" !== 'production' ? invariant(false, 'mountComponentIntoNode(...): Target container is not valid.') : invariant(false) : undefined; + + if (shouldReuseMarkup) { + var rootElement = getReactRootElementInContainer(container); + if (ReactMarkupChecksum.canReuseMarkup(markup, rootElement)) { + return; + } else { + var checksum = rootElement.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME); + rootElement.removeAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME); + + var rootMarkup = rootElement.outerHTML; + rootElement.setAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME, checksum); + + var normalizedMarkup = markup; + if ("production" !== 'production') { + // because rootMarkup is retrieved from the DOM, various normalizations + // will have occurred which will not be present in `markup`. Here, + // insert markup into a <div> or <iframe> depending on the container + // type to perform the same normalizations before comparing. + var normalizer; + if (container.nodeType === ELEMENT_NODE_TYPE) { + normalizer = document.createElementNS('http://www.w3.org/1999/xhtml', 'div'); + normalizer.innerHTML = markup; + normalizedMarkup = normalizer.innerHTML; + } else { + normalizer = document.createElementNS('http://www.w3.org/1999/xhtml', 'iframe'); + document.body.appendChild(normalizer); + normalizer.contentDocument.write(markup); + normalizedMarkup = normalizer.contentDocument.documentElement.outerHTML; + document.body.removeChild(normalizer); + } + } + + var diffIndex = firstDifferenceIndex(normalizedMarkup, rootMarkup); + var difference = ' (client) ' + normalizedMarkup.substring(diffIndex - 20, diffIndex + 20) + '\n (server) ' + rootMarkup.substring(diffIndex - 20, diffIndex + 20); + + !(container.nodeType !== DOC_NODE_TYPE) ? "production" !== 'production' ? invariant(false, 'You\'re trying to render a component to the document using ' + 'server rendering but the checksum was invalid. This usually ' + 'means you rendered a different component type or props on ' + 'the client from the one on the server, or your render() ' + 'methods are impure. React cannot handle this case due to ' + 'cross-browser quirks by rendering at the document root. You ' + 'should look for environment dependent code in your components ' + 'and ensure the props are the same client and server side:\n%s', difference) : invariant(false) : undefined; + + if ("production" !== 'production') { + "production" !== 'production' ? warning(false, 'React attempted to reuse markup in a container but the ' + 'checksum was invalid. This generally means that you are ' + 'using server rendering and the markup generated on the ' + 'server was not what the client was expecting. React injected ' + 'new markup to compensate which works but you have lost many ' + 'of the benefits of server rendering. Instead, figure out ' + 'why the markup being generated is different on the client ' + 'or server:\n%s', difference) : undefined; + } + } + } + + !(container.nodeType !== DOC_NODE_TYPE) ? "production" !== 'production' ? invariant(false, 'You\'re trying to render a component to the document but ' + 'you didn\'t use server rendering. We can\'t do this ' + 'without using server rendering due to cross-browser quirks. ' + 'See ReactDOMServer.renderToString() for server rendering.') : invariant(false) : undefined; + + if (transaction.useCreateElement) { + while (container.lastChild) { + container.removeChild(container.lastChild); + } + container.appendChild(markup); + } else { + setInnerHTML(container, markup); + } + }, + + ownerDocumentContextKey: ownerDocumentContextKey, + + /** + * React ID utilities. + */ + + getReactRootID: getReactRootID, + + getID: getID, + + setID: setID, + + getNode: getNode, + + getNodeFromInstance: getNodeFromInstance, + + isValid: isValid, + + purgeID: purgeID +}; + +ReactPerf.measureMethods(ReactMount, 'ReactMount', { + _renderNewRootComponent: '_renderNewRootComponent', + _mountImageIntoNode: '_mountImageIntoNode' +}); + +module.exports = ReactMount; +},{"10":10,"132":132,"138":138,"141":141,"144":144,"150":150,"154":154,"161":161,"173":173,"24":24,"28":28,"39":39,"44":44,"57":57,"60":60,"67":67,"68":68,"71":71,"78":78,"84":84,"95":95,"96":96}],73:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactMultiChild + * @typechecks static-only + */ + +'use strict'; + +var ReactComponentEnvironment = _dereq_(36); +var ReactMultiChildUpdateTypes = _dereq_(74); + +var ReactCurrentOwner = _dereq_(39); +var ReactReconciler = _dereq_(84); +var ReactChildReconciler = _dereq_(31); + +var flattenChildren = _dereq_(123); + +/** + * Updating children of a component may trigger recursive updates. The depth is + * used to batch recursive updates to render markup more efficiently. + * + * @type {number} + * @private + */ +var updateDepth = 0; + +/** + * Queue of update configuration objects. + * + * Each object has a `type` property that is in `ReactMultiChildUpdateTypes`. + * + * @type {array<object>} + * @private + */ +var updateQueue = []; + +/** + * Queue of markup to be rendered. + * + * @type {array<string>} + * @private + */ +var markupQueue = []; + +/** + * Enqueues markup to be rendered and inserted at a supplied index. + * + * @param {string} parentID ID of the parent component. + * @param {string} markup Markup that renders into an element. + * @param {number} toIndex Destination index. + * @private + */ +function enqueueInsertMarkup(parentID, markup, toIndex) { + // NOTE: Null values reduce hidden classes. + updateQueue.push({ + parentID: parentID, + parentNode: null, + type: ReactMultiChildUpdateTypes.INSERT_MARKUP, + markupIndex: markupQueue.push(markup) - 1, + content: null, + fromIndex: null, + toIndex: toIndex + }); +} + +/** + * Enqueues moving an existing element to another index. + * + * @param {string} parentID ID of the parent component. + * @param {number} fromIndex Source index of the existing element. + * @param {number} toIndex Destination index of the element. + * @private + */ +function enqueueMove(parentID, fromIndex, toIndex) { + // NOTE: Null values reduce hidden classes. + updateQueue.push({ + parentID: parentID, + parentNode: null, + type: ReactMultiChildUpdateTypes.MOVE_EXISTING, + markupIndex: null, + content: null, + fromIndex: fromIndex, + toIndex: toIndex + }); +} + +/** + * Enqueues removing an element at an index. + * + * @param {string} parentID ID of the parent component. + * @param {number} fromIndex Index of the element to remove. + * @private + */ +function enqueueRemove(parentID, fromIndex) { + // NOTE: Null values reduce hidden classes. + updateQueue.push({ + parentID: parentID, + parentNode: null, + type: ReactMultiChildUpdateTypes.REMOVE_NODE, + markupIndex: null, + content: null, + fromIndex: fromIndex, + toIndex: null + }); +} + +/** + * Enqueues setting the markup of a node. + * + * @param {string} parentID ID of the parent component. + * @param {string} markup Markup that renders into an element. + * @private + */ +function enqueueSetMarkup(parentID, markup) { + // NOTE: Null values reduce hidden classes. + updateQueue.push({ + parentID: parentID, + parentNode: null, + type: ReactMultiChildUpdateTypes.SET_MARKUP, + markupIndex: null, + content: markup, + fromIndex: null, + toIndex: null + }); +} + +/** + * Enqueues setting the text content. + * + * @param {string} parentID ID of the parent component. + * @param {string} textContent Text content to set. + * @private + */ +function enqueueTextContent(parentID, textContent) { + // NOTE: Null values reduce hidden classes. + updateQueue.push({ + parentID: parentID, + parentNode: null, + type: ReactMultiChildUpdateTypes.TEXT_CONTENT, + markupIndex: null, + content: textContent, + fromIndex: null, + toIndex: null + }); +} + +/** + * Processes any enqueued updates. + * + * @private + */ +function processQueue() { + if (updateQueue.length) { + ReactComponentEnvironment.processChildrenUpdates(updateQueue, markupQueue); + clearQueue(); + } +} + +/** + * Clears any enqueued updates. + * + * @private + */ +function clearQueue() { + updateQueue.length = 0; + markupQueue.length = 0; +} + +/** + * ReactMultiChild are capable of reconciling multiple children. + * + * @class ReactMultiChild + * @internal + */ +var ReactMultiChild = { + + /** + * Provides common functionality for components that must reconcile multiple + * children. This is used by `ReactDOMComponent` to mount, update, and + * unmount child components. + * + * @lends {ReactMultiChild.prototype} + */ + Mixin: { + + _reconcilerInstantiateChildren: function (nestedChildren, transaction, context) { + if ("production" !== 'production') { + if (this._currentElement) { + try { + ReactCurrentOwner.current = this._currentElement._owner; + return ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context); + } finally { + ReactCurrentOwner.current = null; + } + } + } + return ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context); + }, + + _reconcilerUpdateChildren: function (prevChildren, nextNestedChildrenElements, transaction, context) { + var nextChildren; + if ("production" !== 'production') { + if (this._currentElement) { + try { + ReactCurrentOwner.current = this._currentElement._owner; + nextChildren = flattenChildren(nextNestedChildrenElements); + } finally { + ReactCurrentOwner.current = null; + } + return ReactChildReconciler.updateChildren(prevChildren, nextChildren, transaction, context); + } + } + nextChildren = flattenChildren(nextNestedChildrenElements); + return ReactChildReconciler.updateChildren(prevChildren, nextChildren, transaction, context); + }, + + /** + * Generates a "mount image" for each of the supplied children. In the case + * of `ReactDOMComponent`, a mount image is a string of markup. + * + * @param {?object} nestedChildren Nested child maps. + * @return {array} An array of mounted representations. + * @internal + */ + mountChildren: function (nestedChildren, transaction, context) { + var children = this._reconcilerInstantiateChildren(nestedChildren, transaction, context); + this._renderedChildren = children; + var mountImages = []; + var index = 0; + for (var name in children) { + if (children.hasOwnProperty(name)) { + var child = children[name]; + // Inlined for performance, see `ReactInstanceHandles.createReactID`. + var rootID = this._rootNodeID + name; + var mountImage = ReactReconciler.mountComponent(child, rootID, transaction, context); + child._mountIndex = index++; + mountImages.push(mountImage); + } + } + return mountImages; + }, + + /** + * Replaces any rendered children with a text content string. + * + * @param {string} nextContent String of content. + * @internal + */ + updateTextContent: function (nextContent) { + updateDepth++; + var errorThrown = true; + try { + var prevChildren = this._renderedChildren; + // Remove any rendered children. + ReactChildReconciler.unmountChildren(prevChildren); + // TODO: The setTextContent operation should be enough + for (var name in prevChildren) { + if (prevChildren.hasOwnProperty(name)) { + this._unmountChild(prevChildren[name]); + } + } + // Set new text content. + this.setTextContent(nextContent); + errorThrown = false; + } finally { + updateDepth--; + if (!updateDepth) { + if (errorThrown) { + clearQueue(); + } else { + processQueue(); + } + } + } + }, + + /** + * Replaces any rendered children with a markup string. + * + * @param {string} nextMarkup String of markup. + * @internal + */ + updateMarkup: function (nextMarkup) { + updateDepth++; + var errorThrown = true; + try { + var prevChildren = this._renderedChildren; + // Remove any rendered children. + ReactChildReconciler.unmountChildren(prevChildren); + for (var name in prevChildren) { + if (prevChildren.hasOwnProperty(name)) { + this._unmountChildByName(prevChildren[name], name); + } + } + this.setMarkup(nextMarkup); + errorThrown = false; + } finally { + updateDepth--; + if (!updateDepth) { + if (errorThrown) { + clearQueue(); + } else { + processQueue(); + } + } + } + }, + + /** + * Updates the rendered children with new children. + * + * @param {?object} nextNestedChildrenElements Nested child element maps. + * @param {ReactReconcileTransaction} transaction + * @internal + */ + updateChildren: function (nextNestedChildrenElements, transaction, context) { + updateDepth++; + var errorThrown = true; + try { + this._updateChildren(nextNestedChildrenElements, transaction, context); + errorThrown = false; + } finally { + updateDepth--; + if (!updateDepth) { + if (errorThrown) { + clearQueue(); + } else { + processQueue(); + } + } + } + }, + + /** + * Improve performance by isolating this hot code path from the try/catch + * block in `updateChildren`. + * + * @param {?object} nextNestedChildrenElements Nested child element maps. + * @param {ReactReconcileTransaction} transaction + * @final + * @protected + */ + _updateChildren: function (nextNestedChildrenElements, transaction, context) { + var prevChildren = this._renderedChildren; + var nextChildren = this._reconcilerUpdateChildren(prevChildren, nextNestedChildrenElements, transaction, context); + this._renderedChildren = nextChildren; + if (!nextChildren && !prevChildren) { + return; + } + var name; + // `nextIndex` will increment for each child in `nextChildren`, but + // `lastIndex` will be the last index visited in `prevChildren`. + var lastIndex = 0; + var nextIndex = 0; + for (name in nextChildren) { + if (!nextChildren.hasOwnProperty(name)) { + continue; + } + var prevChild = prevChildren && prevChildren[name]; + var nextChild = nextChildren[name]; + if (prevChild === nextChild) { + this.moveChild(prevChild, nextIndex, lastIndex); + lastIndex = Math.max(prevChild._mountIndex, lastIndex); + prevChild._mountIndex = nextIndex; + } else { + if (prevChild) { + // Update `lastIndex` before `_mountIndex` gets unset by unmounting. + lastIndex = Math.max(prevChild._mountIndex, lastIndex); + this._unmountChild(prevChild); + } + // The child must be instantiated before it's mounted. + this._mountChildByNameAtIndex(nextChild, name, nextIndex, transaction, context); + } + nextIndex++; + } + // Remove children that are no longer present. + for (name in prevChildren) { + if (prevChildren.hasOwnProperty(name) && !(nextChildren && nextChildren.hasOwnProperty(name))) { + this._unmountChild(prevChildren[name]); + } + } + }, + + /** + * Unmounts all rendered children. This should be used to clean up children + * when this component is unmounted. + * + * @internal + */ + unmountChildren: function () { + var renderedChildren = this._renderedChildren; + ReactChildReconciler.unmountChildren(renderedChildren); + this._renderedChildren = null; + }, + + /** + * Moves a child component to the supplied index. + * + * @param {ReactComponent} child Component to move. + * @param {number} toIndex Destination index of the element. + * @param {number} lastIndex Last index visited of the siblings of `child`. + * @protected + */ + moveChild: function (child, toIndex, lastIndex) { + // If the index of `child` is less than `lastIndex`, then it needs to + // be moved. Otherwise, we do not need to move it because a child will be + // inserted or moved before `child`. + if (child._mountIndex < lastIndex) { + enqueueMove(this._rootNodeID, child._mountIndex, toIndex); + } + }, + + /** + * Creates a child component. + * + * @param {ReactComponent} child Component to create. + * @param {string} mountImage Markup to insert. + * @protected + */ + createChild: function (child, mountImage) { + enqueueInsertMarkup(this._rootNodeID, mountImage, child._mountIndex); + }, + + /** + * Removes a child component. + * + * @param {ReactComponent} child Child to remove. + * @protected + */ + removeChild: function (child) { + enqueueRemove(this._rootNodeID, child._mountIndex); + }, + + /** + * Sets this text content string. + * + * @param {string} textContent Text content to set. + * @protected + */ + setTextContent: function (textContent) { + enqueueTextContent(this._rootNodeID, textContent); + }, + + /** + * Sets this markup string. + * + * @param {string} markup Markup to set. + * @protected + */ + setMarkup: function (markup) { + enqueueSetMarkup(this._rootNodeID, markup); + }, + + /** + * Mounts a child with the supplied name. + * + * NOTE: This is part of `updateChildren` and is here for readability. + * + * @param {ReactComponent} child Component to mount. + * @param {string} name Name of the child. + * @param {number} index Index at which to insert the child. + * @param {ReactReconcileTransaction} transaction + * @private + */ + _mountChildByNameAtIndex: function (child, name, index, transaction, context) { + // Inlined for performance, see `ReactInstanceHandles.createReactID`. + var rootID = this._rootNodeID + name; + var mountImage = ReactReconciler.mountComponent(child, rootID, transaction, context); + child._mountIndex = index; + this.createChild(child, mountImage); + }, + + /** + * Unmounts a rendered child. + * + * NOTE: This is part of `updateChildren` and is here for readability. + * + * @param {ReactComponent} child Component to unmount. + * @private + */ + _unmountChild: function (child) { + this.removeChild(child); + child._mountIndex = null; + } + + } + +}; + +module.exports = ReactMultiChild; +},{"123":123,"31":31,"36":36,"39":39,"74":74,"84":84}],74:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactMultiChildUpdateTypes + */ + +'use strict'; + +var keyMirror = _dereq_(165); + +/** + * When a component's children are updated, a series of update configuration + * objects are created in order to batch and serialize the required changes. + * + * Enumerates all the possible types of update configurations. + * + * @internal + */ +var ReactMultiChildUpdateTypes = keyMirror({ + INSERT_MARKUP: null, + MOVE_EXISTING: null, + REMOVE_NODE: null, + SET_MARKUP: null, + TEXT_CONTENT: null +}); + +module.exports = ReactMultiChildUpdateTypes; +},{"165":165}],75:[function(_dereq_,module,exports){ +/** + * Copyright 2014-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactNativeComponent + */ + +'use strict'; + +var assign = _dereq_(24); +var invariant = _dereq_(161); + +var autoGenerateWrapperClass = null; +var genericComponentClass = null; +// This registry keeps track of wrapper classes around native tags. +var tagToComponentClass = {}; +var textComponentClass = null; + +var ReactNativeComponentInjection = { + // This accepts a class that receives the tag string. This is a catch all + // that can render any kind of tag. + injectGenericComponentClass: function (componentClass) { + genericComponentClass = componentClass; + }, + // This accepts a text component class that takes the text string to be + // rendered as props. + injectTextComponentClass: function (componentClass) { + textComponentClass = componentClass; + }, + // This accepts a keyed object with classes as values. Each key represents a + // tag. That particular tag will use this class instead of the generic one. + injectComponentClasses: function (componentClasses) { + assign(tagToComponentClass, componentClasses); + } +}; + +/** + * Get a composite component wrapper class for a specific tag. + * + * @param {ReactElement} element The tag for which to get the class. + * @return {function} The React class constructor function. + */ +function getComponentClassForElement(element) { + if (typeof element.type === 'function') { + return element.type; + } + var tag = element.type; + var componentClass = tagToComponentClass[tag]; + if (componentClass == null) { + tagToComponentClass[tag] = componentClass = autoGenerateWrapperClass(tag); + } + return componentClass; +} + +/** + * Get a native internal component class for a specific tag. + * + * @param {ReactElement} element The element to create. + * @return {function} The internal class constructor function. + */ +function createInternalComponent(element) { + !genericComponentClass ? "production" !== 'production' ? invariant(false, 'There is no registered component for the tag %s', element.type) : invariant(false) : undefined; + return new genericComponentClass(element.type, element.props); +} + +/** + * @param {ReactText} text + * @return {ReactComponent} + */ +function createInstanceForText(text) { + return new textComponentClass(text); +} + +/** + * @param {ReactComponent} component + * @return {boolean} + */ +function isTextComponent(component) { + return component instanceof textComponentClass; +} + +var ReactNativeComponent = { + getComponentClassForElement: getComponentClassForElement, + createInternalComponent: createInternalComponent, + createInstanceForText: createInstanceForText, + isTextComponent: isTextComponent, + injection: ReactNativeComponentInjection +}; + +module.exports = ReactNativeComponent; +},{"161":161,"24":24}],76:[function(_dereq_,module,exports){ +/** + * Copyright 2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactNoopUpdateQueue + */ + +'use strict'; + +var warning = _dereq_(173); + +function warnTDZ(publicInstance, callerName) { + if ("production" !== 'production') { + "production" !== 'production' ? warning(false, '%s(...): Can only update a mounted or mounting component. ' + 'This usually means you called %s() on an unmounted component. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, publicInstance.constructor && publicInstance.constructor.displayName || '') : undefined; + } +} + +/** + * This is the abstract API for an update queue. + */ +var ReactNoopUpdateQueue = { + + /** + * Checks whether or not this composite component is mounted. + * @param {ReactClass} publicInstance The instance we want to test. + * @return {boolean} True if mounted, false otherwise. + * @protected + * @final + */ + isMounted: function (publicInstance) { + return false; + }, + + /** + * Enqueue a callback that will be executed after all the pending updates + * have processed. + * + * @param {ReactClass} publicInstance The instance to use as `this` context. + * @param {?function} callback Called after state is updated. + * @internal + */ + enqueueCallback: function (publicInstance, callback) {}, + + /** + * Forces an update. This should only be invoked when it is known with + * certainty that we are **not** in a DOM transaction. + * + * You may want to call this when you know that some deeper aspect of the + * component's state has changed but `setState` was not called. + * + * This will not invoke `shouldComponentUpdate`, but it will invoke + * `componentWillUpdate` and `componentDidUpdate`. + * + * @param {ReactClass} publicInstance The instance that should rerender. + * @internal + */ + enqueueForceUpdate: function (publicInstance) { + warnTDZ(publicInstance, 'forceUpdate'); + }, + + /** + * Replaces all of the state. Always use this or `setState` to mutate state. + * You should treat `this.state` as immutable. + * + * There is no guarantee that `this.state` will be immediately updated, so + * accessing `this.state` after calling this method may return the old value. + * + * @param {ReactClass} publicInstance The instance that should rerender. + * @param {object} completeState Next state. + * @internal + */ + enqueueReplaceState: function (publicInstance, completeState) { + warnTDZ(publicInstance, 'replaceState'); + }, + + /** + * Sets a subset of the state. This only exists because _pendingState is + * internal. This provides a merging strategy that is not available to deep + * properties which is confusing. TODO: Expose pendingState or don't use it + * during the merge. + * + * @param {ReactClass} publicInstance The instance that should rerender. + * @param {object} partialState Next partial state to be merged with state. + * @internal + */ + enqueueSetState: function (publicInstance, partialState) { + warnTDZ(publicInstance, 'setState'); + }, + + /** + * Sets a subset of the props. + * + * @param {ReactClass} publicInstance The instance that should rerender. + * @param {object} partialProps Subset of the next props. + * @internal + */ + enqueueSetProps: function (publicInstance, partialProps) { + warnTDZ(publicInstance, 'setProps'); + }, + + /** + * Replaces all of the props. + * + * @param {ReactClass} publicInstance The instance that should rerender. + * @param {object} props New props. + * @internal + */ + enqueueReplaceProps: function (publicInstance, props) { + warnTDZ(publicInstance, 'replaceProps'); + } + +}; + +module.exports = ReactNoopUpdateQueue; +},{"173":173}],77:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactOwner + */ + +'use strict'; + +var invariant = _dereq_(161); + +/** + * ReactOwners are capable of storing references to owned components. + * + * All components are capable of //being// referenced by owner components, but + * only ReactOwner components are capable of //referencing// owned components. + * The named reference is known as a "ref". + * + * Refs are available when mounted and updated during reconciliation. + * + * var MyComponent = React.createClass({ + * render: function() { + * return ( + * <div onClick={this.handleClick}> + * <CustomComponent ref="custom" /> + * </div> + * ); + * }, + * handleClick: function() { + * this.refs.custom.handleClick(); + * }, + * componentDidMount: function() { + * this.refs.custom.initialize(); + * } + * }); + * + * Refs should rarely be used. When refs are used, they should only be done to + * control data that is not handled by React's data flow. + * + * @class ReactOwner + */ +var ReactOwner = { + + /** + * @param {?object} object + * @return {boolean} True if `object` is a valid owner. + * @final + */ + isValidOwner: function (object) { + return !!(object && typeof object.attachRef === 'function' && typeof object.detachRef === 'function'); + }, + + /** + * Adds a component by ref to an owner component. + * + * @param {ReactComponent} component Component to reference. + * @param {string} ref Name by which to refer to the component. + * @param {ReactOwner} owner Component on which to record the ref. + * @final + * @internal + */ + addComponentAsRefTo: function (component, ref, owner) { + !ReactOwner.isValidOwner(owner) ? "production" !== 'production' ? invariant(false, 'addComponentAsRefTo(...): Only a ReactOwner can have refs. You might ' + 'be adding a ref to a component that was not created inside a component\'s ' + '`render` method, or you have multiple copies of React loaded ' + '(details: https://fb.me/react-refs-must-have-owner).') : invariant(false) : undefined; + owner.attachRef(ref, component); + }, + + /** + * Removes a component by ref from an owner component. + * + * @param {ReactComponent} component Component to dereference. + * @param {string} ref Name of the ref to remove. + * @param {ReactOwner} owner Component on which the ref is recorded. + * @final + * @internal + */ + removeComponentAsRefFrom: function (component, ref, owner) { + !ReactOwner.isValidOwner(owner) ? "production" !== 'production' ? invariant(false, 'removeComponentAsRefFrom(...): Only a ReactOwner can have refs. You might ' + 'be removing a ref to a component that was not created inside a component\'s ' + '`render` method, or you have multiple copies of React loaded ' + '(details: https://fb.me/react-refs-must-have-owner).') : invariant(false) : undefined; + // Check that `component` is still the current ref because we do not want to + // detach the ref if another component stole it. + if (owner.getPublicInstance().refs[ref] === component.getPublicInstance()) { + owner.detachRef(ref); + } + } + +}; + +module.exports = ReactOwner; +},{"161":161}],78:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactPerf + * @typechecks static-only + */ + +'use strict'; + +/** + * ReactPerf is a general AOP system designed to measure performance. This + * module only has the hooks: see ReactDefaultPerf for the analysis tool. + */ +var ReactPerf = { + /** + * Boolean to enable/disable measurement. Set to false by default to prevent + * accidental logging and perf loss. + */ + enableMeasure: false, + + /** + * Holds onto the measure function in use. By default, don't measure + * anything, but we'll override this if we inject a measure function. + */ + storedMeasure: _noMeasure, + + /** + * @param {object} object + * @param {string} objectName + * @param {object<string>} methodNames + */ + measureMethods: function (object, objectName, methodNames) { + if ("production" !== 'production') { + for (var key in methodNames) { + if (!methodNames.hasOwnProperty(key)) { + continue; + } + object[key] = ReactPerf.measure(objectName, methodNames[key], object[key]); + } + } + }, + + /** + * Use this to wrap methods you want to measure. Zero overhead in production. + * + * @param {string} objName + * @param {string} fnName + * @param {function} func + * @return {function} + */ + measure: function (objName, fnName, func) { + if ("production" !== 'production') { + var measuredFunc = null; + var wrapper = function () { + if (ReactPerf.enableMeasure) { + if (!measuredFunc) { + measuredFunc = ReactPerf.storedMeasure(objName, fnName, func); + } + return measuredFunc.apply(this, arguments); + } + return func.apply(this, arguments); + }; + wrapper.displayName = objName + '_' + fnName; + return wrapper; + } + return func; + }, + + injection: { + /** + * @param {function} measure + */ + injectMeasure: function (measure) { + ReactPerf.storedMeasure = measure; + } + } +}; + +/** + * Simply passes through the measured function, without measuring it. + * + * @param {string} objName + * @param {string} fnName + * @param {function} func + * @return {function} + */ +function _noMeasure(objName, fnName, func) { + return func; +} + +module.exports = ReactPerf; +},{}],79:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactPropTransferer + */ + +'use strict'; + +var assign = _dereq_(24); +var emptyFunction = _dereq_(153); +var joinClasses = _dereq_(164); + +/** + * Creates a transfer strategy that will merge prop values using the supplied + * `mergeStrategy`. If a prop was previously unset, this just sets it. + * + * @param {function} mergeStrategy + * @return {function} + */ +function createTransferStrategy(mergeStrategy) { + return function (props, key, value) { + if (!props.hasOwnProperty(key)) { + props[key] = value; + } else { + props[key] = mergeStrategy(props[key], value); + } + }; +} + +var transferStrategyMerge = createTransferStrategy(function (a, b) { + // `merge` overrides the first object's (`props[key]` above) keys using the + // second object's (`value`) keys. An object's style's existing `propA` would + // get overridden. Flip the order here. + return assign({}, b, a); +}); + +/** + * Transfer strategies dictate how props are transferred by `transferPropsTo`. + * NOTE: if you add any more exceptions to this list you should be sure to + * update `cloneWithProps()` accordingly. + */ +var TransferStrategies = { + /** + * Never transfer `children`. + */ + children: emptyFunction, + /** + * Transfer the `className` prop by merging them. + */ + className: createTransferStrategy(joinClasses), + /** + * Transfer the `style` prop (which is an object) by merging them. + */ + style: transferStrategyMerge +}; + +/** + * Mutates the first argument by transferring the properties from the second + * argument. + * + * @param {object} props + * @param {object} newProps + * @return {object} + */ +function transferInto(props, newProps) { + for (var thisKey in newProps) { + if (!newProps.hasOwnProperty(thisKey)) { + continue; + } + + var transferStrategy = TransferStrategies[thisKey]; + + if (transferStrategy && TransferStrategies.hasOwnProperty(thisKey)) { + transferStrategy(props, thisKey, newProps[thisKey]); + } else if (!props.hasOwnProperty(thisKey)) { + props[thisKey] = newProps[thisKey]; + } + } + return props; +} + +/** + * ReactPropTransferer are capable of transferring props to another component + * using a `transferPropsTo` method. + * + * @class ReactPropTransferer + */ +var ReactPropTransferer = { + + /** + * Merge two props objects using TransferStrategies. + * + * @param {object} oldProps original props (they take precedence) + * @param {object} newProps new props to merge in + * @return {object} a new object containing both sets of props merged. + */ + mergeProps: function (oldProps, newProps) { + return transferInto(assign({}, oldProps), newProps); + } + +}; + +module.exports = ReactPropTransferer; +},{"153":153,"164":164,"24":24}],80:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactPropTypeLocationNames + */ + +'use strict'; + +var ReactPropTypeLocationNames = {}; + +if ("production" !== 'production') { + ReactPropTypeLocationNames = { + prop: 'prop', + context: 'context', + childContext: 'child context' + }; +} + +module.exports = ReactPropTypeLocationNames; +},{}],81:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactPropTypeLocations + */ + +'use strict'; + +var keyMirror = _dereq_(165); + +var ReactPropTypeLocations = keyMirror({ + prop: null, + context: null, + childContext: null +}); + +module.exports = ReactPropTypeLocations; +},{"165":165}],82:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactPropTypes + */ + +'use strict'; + +var ReactElement = _dereq_(57); +var ReactPropTypeLocationNames = _dereq_(80); + +var emptyFunction = _dereq_(153); +var getIteratorFn = _dereq_(129); + +/** + * Collection of methods that allow declaration and validation of props that are + * supplied to React components. Example usage: + * + * var Props = require('ReactPropTypes'); + * var MyArticle = React.createClass({ + * propTypes: { + * // An optional string prop named "description". + * description: Props.string, + * + * // A required enum prop named "category". + * category: Props.oneOf(['News','Photos']).isRequired, + * + * // A prop named "dialog" that requires an instance of Dialog. + * dialog: Props.instanceOf(Dialog).isRequired + * }, + * render: function() { ... } + * }); + * + * A more formal specification of how these methods are used: + * + * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) + * decl := ReactPropTypes.{type}(.isRequired)? + * + * Each and every declaration produces a function with the same signature. This + * allows the creation of custom validation functions. For example: + * + * var MyLink = React.createClass({ + * propTypes: { + * // An optional string or URI prop named "href". + * href: function(props, propName, componentName) { + * var propValue = props[propName]; + * if (propValue != null && typeof propValue !== 'string' && + * !(propValue instanceof URI)) { + * return new Error( + * 'Expected a string or an URI for ' + propName + ' in ' + + * componentName + * ); + * } + * } + * }, + * render: function() {...} + * }); + * + * @internal + */ + +var ANONYMOUS = '<<anonymous>>'; + +var ReactPropTypes = { + array: createPrimitiveTypeChecker('array'), + bool: createPrimitiveTypeChecker('boolean'), + func: createPrimitiveTypeChecker('function'), + number: createPrimitiveTypeChecker('number'), + object: createPrimitiveTypeChecker('object'), + string: createPrimitiveTypeChecker('string'), + + any: createAnyTypeChecker(), + arrayOf: createArrayOfTypeChecker, + element: createElementTypeChecker(), + instanceOf: createInstanceTypeChecker, + node: createNodeChecker(), + objectOf: createObjectOfTypeChecker, + oneOf: createEnumTypeChecker, + oneOfType: createUnionTypeChecker, + shape: createShapeTypeChecker +}; + +function createChainableTypeChecker(validate) { + function checkType(isRequired, props, propName, componentName, location, propFullName) { + componentName = componentName || ANONYMOUS; + propFullName = propFullName || propName; + if (props[propName] == null) { + var locationName = ReactPropTypeLocationNames[location]; + if (isRequired) { + return new Error('Required ' + locationName + ' `' + propFullName + '` was not specified in ' + ('`' + componentName + '`.')); + } + return null; + } else { + return validate(props, propName, componentName, location, propFullName); + } + } + + var chainedCheckType = checkType.bind(null, false); + chainedCheckType.isRequired = checkType.bind(null, true); + + return chainedCheckType; +} + +function createPrimitiveTypeChecker(expectedType) { + function validate(props, propName, componentName, location, propFullName) { + var propValue = props[propName]; + var propType = getPropType(propValue); + if (propType !== expectedType) { + var locationName = ReactPropTypeLocationNames[location]; + // `propValue` being instance of, say, date/regexp, pass the 'object' + // check, but we can offer a more precise error message here rather than + // 'of type `object`'. + var preciseType = getPreciseType(propValue); + + return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.')); + } + return null; + } + return createChainableTypeChecker(validate); +} + +function createAnyTypeChecker() { + return createChainableTypeChecker(emptyFunction.thatReturns(null)); +} + +function createArrayOfTypeChecker(typeChecker) { + function validate(props, propName, componentName, location, propFullName) { + var propValue = props[propName]; + if (!Array.isArray(propValue)) { + var locationName = ReactPropTypeLocationNames[location]; + var propType = getPropType(propValue); + return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.')); + } + for (var i = 0; i < propValue.length; i++) { + var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']'); + if (error instanceof Error) { + return error; + } + } + return null; + } + return createChainableTypeChecker(validate); +} + +function createElementTypeChecker() { + function validate(props, propName, componentName, location, propFullName) { + if (!ReactElement.isValidElement(props[propName])) { + var locationName = ReactPropTypeLocationNames[location]; + return new Error('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a single ReactElement.')); + } + return null; + } + return createChainableTypeChecker(validate); +} + +function createInstanceTypeChecker(expectedClass) { + function validate(props, propName, componentName, location, propFullName) { + if (!(props[propName] instanceof expectedClass)) { + var locationName = ReactPropTypeLocationNames[location]; + var expectedClassName = expectedClass.name || ANONYMOUS; + var actualClassName = getClassName(props[propName]); + return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.')); + } + return null; + } + return createChainableTypeChecker(validate); +} + +function createEnumTypeChecker(expectedValues) { + if (!Array.isArray(expectedValues)) { + return createChainableTypeChecker(function () { + return new Error('Invalid argument supplied to oneOf, expected an instance of array.'); + }); + } + + function validate(props, propName, componentName, location, propFullName) { + var propValue = props[propName]; + for (var i = 0; i < expectedValues.length; i++) { + if (propValue === expectedValues[i]) { + return null; + } + } + + var locationName = ReactPropTypeLocationNames[location]; + var valuesString = JSON.stringify(expectedValues); + return new Error('Invalid ' + locationName + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.')); + } + return createChainableTypeChecker(validate); +} + +function createObjectOfTypeChecker(typeChecker) { + function validate(props, propName, componentName, location, propFullName) { + var propValue = props[propName]; + var propType = getPropType(propValue); + if (propType !== 'object') { + var locationName = ReactPropTypeLocationNames[location]; + return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.')); + } + for (var key in propValue) { + if (propValue.hasOwnProperty(key)) { + var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key); + if (error instanceof Error) { + return error; + } + } + } + return null; + } + return createChainableTypeChecker(validate); +} + +function createUnionTypeChecker(arrayOfTypeCheckers) { + if (!Array.isArray(arrayOfTypeCheckers)) { + return createChainableTypeChecker(function () { + return new Error('Invalid argument supplied to oneOfType, expected an instance of array.'); + }); + } + + function validate(props, propName, componentName, location, propFullName) { + for (var i = 0; i < arrayOfTypeCheckers.length; i++) { + var checker = arrayOfTypeCheckers[i]; + if (checker(props, propName, componentName, location, propFullName) == null) { + return null; + } + } + + var locationName = ReactPropTypeLocationNames[location]; + return new Error('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.')); + } + return createChainableTypeChecker(validate); +} + +function createNodeChecker() { + function validate(props, propName, componentName, location, propFullName) { + if (!isNode(props[propName])) { + var locationName = ReactPropTypeLocationNames[location]; + return new Error('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.')); + } + return null; + } + return createChainableTypeChecker(validate); +} + +function createShapeTypeChecker(shapeTypes) { + function validate(props, propName, componentName, location, propFullName) { + var propValue = props[propName]; + var propType = getPropType(propValue); + if (propType !== 'object') { + var locationName = ReactPropTypeLocationNames[location]; + return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); + } + for (var key in shapeTypes) { + var checker = shapeTypes[key]; + if (!checker) { + continue; + } + var error = checker(propValue, key, componentName, location, propFullName + '.' + key); + if (error) { + return error; + } + } + return null; + } + return createChainableTypeChecker(validate); +} + +function isNode(propValue) { + switch (typeof propValue) { + case 'number': + case 'string': + case 'undefined': + return true; + case 'boolean': + return !propValue; + case 'object': + if (Array.isArray(propValue)) { + return propValue.every(isNode); + } + if (propValue === null || ReactElement.isValidElement(propValue)) { + return true; + } + + var iteratorFn = getIteratorFn(propValue); + if (iteratorFn) { + var iterator = iteratorFn.call(propValue); + var step; + if (iteratorFn !== propValue.entries) { + while (!(step = iterator.next()).done) { + if (!isNode(step.value)) { + return false; + } + } + } else { + // Iterator will provide entry [k,v] tuples rather than values. + while (!(step = iterator.next()).done) { + var entry = step.value; + if (entry) { + if (!isNode(entry[1])) { + return false; + } + } + } + } + } else { + return false; + } + + return true; + default: + return false; + } +} + +// Equivalent of `typeof` but with special handling for array and regexp. +function getPropType(propValue) { + var propType = typeof propValue; + if (Array.isArray(propValue)) { + return 'array'; + } + if (propValue instanceof RegExp) { + // Old webkits (at least until Android 4.0) return 'function' rather than + // 'object' for typeof a RegExp. We'll normalize this here so that /bla/ + // passes PropTypes.object. + return 'object'; + } + return propType; +} + +// This handles more types than `getPropType`. Only used for error messages. +// See `createPrimitiveTypeChecker`. +function getPreciseType(propValue) { + var propType = getPropType(propValue); + if (propType === 'object') { + if (propValue instanceof Date) { + return 'date'; + } else if (propValue instanceof RegExp) { + return 'regexp'; + } + } + return propType; +} + +// Returns class name of the object, if any. +function getClassName(propValue) { + if (!propValue.constructor || !propValue.constructor.name) { + return '<<anonymous>>'; + } + return propValue.constructor.name; +} + +module.exports = ReactPropTypes; +},{"129":129,"153":153,"57":57,"80":80}],83:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactReconcileTransaction + * @typechecks static-only + */ + +'use strict'; + +var CallbackQueue = _dereq_(6); +var PooledClass = _dereq_(25); +var ReactBrowserEventEmitter = _dereq_(28); +var ReactDOMFeatureFlags = _dereq_(44); +var ReactInputSelection = _dereq_(66); +var Transaction = _dereq_(113); + +var assign = _dereq_(24); + +/** + * Ensures that, when possible, the selection range (currently selected text + * input) is not disturbed by performing the transaction. + */ +var SELECTION_RESTORATION = { + /** + * @return {Selection} Selection information. + */ + initialize: ReactInputSelection.getSelectionInformation, + /** + * @param {Selection} sel Selection information returned from `initialize`. + */ + close: ReactInputSelection.restoreSelection +}; + +/** + * Suppresses events (blur/focus) that could be inadvertently dispatched due to + * high level DOM manipulations (like temporarily removing a text input from the + * DOM). + */ +var EVENT_SUPPRESSION = { + /** + * @return {boolean} The enabled status of `ReactBrowserEventEmitter` before + * the reconciliation. + */ + initialize: function () { + var currentlyEnabled = ReactBrowserEventEmitter.isEnabled(); + ReactBrowserEventEmitter.setEnabled(false); + return currentlyEnabled; + }, + + /** + * @param {boolean} previouslyEnabled Enabled status of + * `ReactBrowserEventEmitter` before the reconciliation occurred. `close` + * restores the previous value. + */ + close: function (previouslyEnabled) { + ReactBrowserEventEmitter.setEnabled(previouslyEnabled); + } +}; + +/** + * Provides a queue for collecting `componentDidMount` and + * `componentDidUpdate` callbacks during the the transaction. + */ +var ON_DOM_READY_QUEUEING = { + /** + * Initializes the internal `onDOMReady` queue. + */ + initialize: function () { + this.reactMountReady.reset(); + }, + + /** + * After DOM is flushed, invoke all registered `onDOMReady` callbacks. + */ + close: function () { + this.reactMountReady.notifyAll(); + } +}; + +/** + * Executed within the scope of the `Transaction` instance. Consider these as + * being member methods, but with an implied ordering while being isolated from + * each other. + */ +var TRANSACTION_WRAPPERS = [SELECTION_RESTORATION, EVENT_SUPPRESSION, ON_DOM_READY_QUEUEING]; + +/** + * Currently: + * - The order that these are listed in the transaction is critical: + * - Suppresses events. + * - Restores selection range. + * + * Future: + * - Restore document/overflow scroll positions that were unintentionally + * modified via DOM insertions above the top viewport boundary. + * - Implement/integrate with customized constraint based layout system and keep + * track of which dimensions must be remeasured. + * + * @class ReactReconcileTransaction + */ +function ReactReconcileTransaction(forceHTML) { + this.reinitializeTransaction(); + // Only server-side rendering really needs this option (see + // `ReactServerRendering`), but server-side uses + // `ReactServerRenderingTransaction` instead. This option is here so that it's + // accessible and defaults to false when `ReactDOMComponent` and + // `ReactTextComponent` checks it in `mountComponent`.` + this.renderToStaticMarkup = false; + this.reactMountReady = CallbackQueue.getPooled(null); + this.useCreateElement = !forceHTML && ReactDOMFeatureFlags.useCreateElement; +} + +var Mixin = { + /** + * @see Transaction + * @abstract + * @final + * @return {array<object>} List of operation wrap procedures. + * TODO: convert to array<TransactionWrapper> + */ + getTransactionWrappers: function () { + return TRANSACTION_WRAPPERS; + }, + + /** + * @return {object} The queue to collect `onDOMReady` callbacks with. + */ + getReactMountReady: function () { + return this.reactMountReady; + }, + + /** + * `PooledClass` looks for this, and will invoke this before allowing this + * instance to be reused. + */ + destructor: function () { + CallbackQueue.release(this.reactMountReady); + this.reactMountReady = null; + } +}; + +assign(ReactReconcileTransaction.prototype, Transaction.Mixin, Mixin); + +PooledClass.addPoolingTo(ReactReconcileTransaction); + +module.exports = ReactReconcileTransaction; +},{"113":113,"24":24,"25":25,"28":28,"44":44,"6":6,"66":66}],84:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactReconciler + */ + +'use strict'; + +var ReactRef = _dereq_(85); + +/** + * Helper to call ReactRef.attachRefs with this composite component, split out + * to avoid allocations in the transaction mount-ready queue. + */ +function attachRefs() { + ReactRef.attachRefs(this, this._currentElement); +} + +var ReactReconciler = { + + /** + * Initializes the component, renders markup, and registers event listeners. + * + * @param {ReactComponent} internalInstance + * @param {string} rootID DOM ID of the root node. + * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction + * @return {?string} Rendered markup to be inserted into the DOM. + * @final + * @internal + */ + mountComponent: function (internalInstance, rootID, transaction, context) { + var markup = internalInstance.mountComponent(rootID, transaction, context); + if (internalInstance._currentElement && internalInstance._currentElement.ref != null) { + transaction.getReactMountReady().enqueue(attachRefs, internalInstance); + } + return markup; + }, + + /** + * Releases any resources allocated by `mountComponent`. + * + * @final + * @internal + */ + unmountComponent: function (internalInstance) { + ReactRef.detachRefs(internalInstance, internalInstance._currentElement); + internalInstance.unmountComponent(); + }, + + /** + * Update a component using a new element. + * + * @param {ReactComponent} internalInstance + * @param {ReactElement} nextElement + * @param {ReactReconcileTransaction} transaction + * @param {object} context + * @internal + */ + receiveComponent: function (internalInstance, nextElement, transaction, context) { + var prevElement = internalInstance._currentElement; + + if (nextElement === prevElement && context === internalInstance._context) { + // Since elements are immutable after the owner is rendered, + // we can do a cheap identity compare here to determine if this is a + // superfluous reconcile. It's possible for state to be mutable but such + // change should trigger an update of the owner which would recreate + // the element. We explicitly check for the existence of an owner since + // it's possible for an element created outside a composite to be + // deeply mutated and reused. + + // TODO: Bailing out early is just a perf optimization right? + // TODO: Removing the return statement should affect correctness? + return; + } + + var refsChanged = ReactRef.shouldUpdateRefs(prevElement, nextElement); + + if (refsChanged) { + ReactRef.detachRefs(internalInstance, prevElement); + } + + internalInstance.receiveComponent(nextElement, transaction, context); + + if (refsChanged && internalInstance._currentElement && internalInstance._currentElement.ref != null) { + transaction.getReactMountReady().enqueue(attachRefs, internalInstance); + } + }, + + /** + * Flush any dirty changes in a component. + * + * @param {ReactComponent} internalInstance + * @param {ReactReconcileTransaction} transaction + * @internal + */ + performUpdateIfNecessary: function (internalInstance, transaction) { + internalInstance.performUpdateIfNecessary(transaction); + } + +}; + +module.exports = ReactReconciler; +},{"85":85}],85:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactRef + */ + +'use strict'; + +var ReactOwner = _dereq_(77); + +var ReactRef = {}; + +function attachRef(ref, component, owner) { + if (typeof ref === 'function') { + ref(component.getPublicInstance()); + } else { + // Legacy ref + ReactOwner.addComponentAsRefTo(component, ref, owner); + } +} + +function detachRef(ref, component, owner) { + if (typeof ref === 'function') { + ref(null); + } else { + // Legacy ref + ReactOwner.removeComponentAsRefFrom(component, ref, owner); + } +} + +ReactRef.attachRefs = function (instance, element) { + if (element === null || element === false) { + return; + } + var ref = element.ref; + if (ref != null) { + attachRef(ref, instance, element._owner); + } +}; + +ReactRef.shouldUpdateRefs = function (prevElement, nextElement) { + // If either the owner or a `ref` has changed, make sure the newest owner + // has stored a reference to `this`, and the previous owner (if different) + // has forgotten the reference to `this`. We use the element instead + // of the public this.props because the post processing cannot determine + // a ref. The ref conceptually lives on the element. + + // TODO: Should this even be possible? The owner cannot change because + // it's forbidden by shouldUpdateReactComponent. The ref can change + // if you swap the keys of but not the refs. Reconsider where this check + // is made. It probably belongs where the key checking and + // instantiateReactComponent is done. + + var prevEmpty = prevElement === null || prevElement === false; + var nextEmpty = nextElement === null || nextElement === false; + + return( + // This has a few false positives w/r/t empty components. + prevEmpty || nextEmpty || nextElement._owner !== prevElement._owner || nextElement.ref !== prevElement.ref + ); +}; + +ReactRef.detachRefs = function (instance, element) { + if (element === null || element === false) { + return; + } + var ref = element.ref; + if (ref != null) { + detachRef(ref, instance, element._owner); + } +}; + +module.exports = ReactRef; +},{"77":77}],86:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactRootIndex + * @typechecks + */ + +'use strict'; + +var ReactRootIndexInjection = { + /** + * @param {function} _createReactRootIndex + */ + injectCreateReactRootIndex: function (_createReactRootIndex) { + ReactRootIndex.createReactRootIndex = _createReactRootIndex; + } +}; + +var ReactRootIndex = { + createReactRootIndex: null, + injection: ReactRootIndexInjection +}; + +module.exports = ReactRootIndex; +},{}],87:[function(_dereq_,module,exports){ +/** + * Copyright 2014-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactServerBatchingStrategy + * @typechecks + */ + +'use strict'; + +var ReactServerBatchingStrategy = { + isBatchingUpdates: false, + batchedUpdates: function (callback) { + // Don't do anything here. During the server rendering we don't want to + // schedule any updates. We will simply ignore them. + } +}; + +module.exports = ReactServerBatchingStrategy; +},{}],88:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @typechecks static-only + * @providesModule ReactServerRendering + */ +'use strict'; + +var ReactDefaultBatchingStrategy = _dereq_(53); +var ReactElement = _dereq_(57); +var ReactInstanceHandles = _dereq_(67); +var ReactMarkupChecksum = _dereq_(71); +var ReactServerBatchingStrategy = _dereq_(87); +var ReactServerRenderingTransaction = _dereq_(89); +var ReactUpdates = _dereq_(96); + +var emptyObject = _dereq_(154); +var instantiateReactComponent = _dereq_(132); +var invariant = _dereq_(161); + +/** + * @param {ReactElement} element + * @return {string} the HTML markup + */ +function renderToString(element) { + !ReactElement.isValidElement(element) ? "production" !== 'production' ? invariant(false, 'renderToString(): You must pass a valid ReactElement.') : invariant(false) : undefined; + + var transaction; + try { + ReactUpdates.injection.injectBatchingStrategy(ReactServerBatchingStrategy); + + var id = ReactInstanceHandles.createReactRootID(); + transaction = ReactServerRenderingTransaction.getPooled(false); + + return transaction.perform(function () { + var componentInstance = instantiateReactComponent(element, null); + var markup = componentInstance.mountComponent(id, transaction, emptyObject); + return ReactMarkupChecksum.addChecksumToMarkup(markup); + }, null); + } finally { + ReactServerRenderingTransaction.release(transaction); + // Revert to the DOM batching strategy since these two renderers + // currently share these stateful modules. + ReactUpdates.injection.injectBatchingStrategy(ReactDefaultBatchingStrategy); + } +} + +/** + * @param {ReactElement} element + * @return {string} the HTML markup, without the extra React ID and checksum + * (for generating static pages) + */ +function renderToStaticMarkup(element) { + !ReactElement.isValidElement(element) ? "production" !== 'production' ? invariant(false, 'renderToStaticMarkup(): You must pass a valid ReactElement.') : invariant(false) : undefined; + + var transaction; + try { + ReactUpdates.injection.injectBatchingStrategy(ReactServerBatchingStrategy); + + var id = ReactInstanceHandles.createReactRootID(); + transaction = ReactServerRenderingTransaction.getPooled(true); + + return transaction.perform(function () { + var componentInstance = instantiateReactComponent(element, null); + return componentInstance.mountComponent(id, transaction, emptyObject); + }, null); + } finally { + ReactServerRenderingTransaction.release(transaction); + // Revert to the DOM batching strategy since these two renderers + // currently share these stateful modules. + ReactUpdates.injection.injectBatchingStrategy(ReactDefaultBatchingStrategy); + } +} + +module.exports = { + renderToString: renderToString, + renderToStaticMarkup: renderToStaticMarkup +}; +},{"132":132,"154":154,"161":161,"53":53,"57":57,"67":67,"71":71,"87":87,"89":89,"96":96}],89:[function(_dereq_,module,exports){ +/** + * Copyright 2014-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactServerRenderingTransaction + * @typechecks + */ + +'use strict'; + +var PooledClass = _dereq_(25); +var CallbackQueue = _dereq_(6); +var Transaction = _dereq_(113); + +var assign = _dereq_(24); +var emptyFunction = _dereq_(153); + +/** + * Provides a `CallbackQueue` queue for collecting `onDOMReady` callbacks + * during the performing of the transaction. + */ +var ON_DOM_READY_QUEUEING = { + /** + * Initializes the internal `onDOMReady` queue. + */ + initialize: function () { + this.reactMountReady.reset(); + }, + + close: emptyFunction +}; + +/** + * Executed within the scope of the `Transaction` instance. Consider these as + * being member methods, but with an implied ordering while being isolated from + * each other. + */ +var TRANSACTION_WRAPPERS = [ON_DOM_READY_QUEUEING]; + +/** + * @class ReactServerRenderingTransaction + * @param {boolean} renderToStaticMarkup + */ +function ReactServerRenderingTransaction(renderToStaticMarkup) { + this.reinitializeTransaction(); + this.renderToStaticMarkup = renderToStaticMarkup; + this.reactMountReady = CallbackQueue.getPooled(null); + this.useCreateElement = false; +} + +var Mixin = { + /** + * @see Transaction + * @abstract + * @final + * @return {array} Empty list of operation wrap procedures. + */ + getTransactionWrappers: function () { + return TRANSACTION_WRAPPERS; + }, + + /** + * @return {object} The queue to collect `onDOMReady` callbacks with. + */ + getReactMountReady: function () { + return this.reactMountReady; + }, + + /** + * `PooledClass` looks for this, and will invoke this before allowing this + * instance to be reused. + */ + destructor: function () { + CallbackQueue.release(this.reactMountReady); + this.reactMountReady = null; + } +}; + +assign(ReactServerRenderingTransaction.prototype, Transaction.Mixin, Mixin); + +PooledClass.addPoolingTo(ReactServerRenderingTransaction); + +module.exports = ReactServerRenderingTransaction; +},{"113":113,"153":153,"24":24,"25":25,"6":6}],90:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactStateSetters + */ + +'use strict'; + +var ReactStateSetters = { + /** + * Returns a function that calls the provided function, and uses the result + * of that to set the component's state. + * + * @param {ReactCompositeComponent} component + * @param {function} funcReturningState Returned callback uses this to + * determine how to update state. + * @return {function} callback that when invoked uses funcReturningState to + * determined the object literal to setState. + */ + createStateSetter: function (component, funcReturningState) { + return function (a, b, c, d, e, f) { + var partialState = funcReturningState.call(component, a, b, c, d, e, f); + if (partialState) { + component.setState(partialState); + } + }; + }, + + /** + * Returns a single-argument callback that can be used to update a single + * key in the component's state. + * + * Note: this is memoized function, which makes it inexpensive to call. + * + * @param {ReactCompositeComponent} component + * @param {string} key The key in the state that you should update. + * @return {function} callback of 1 argument which calls setState() with + * the provided keyName and callback argument. + */ + createStateKeySetter: function (component, key) { + // Memoize the setters. + var cache = component.__keySetters || (component.__keySetters = {}); + return cache[key] || (cache[key] = createStateKeySetter(component, key)); + } +}; + +function createStateKeySetter(component, key) { + // Partial state is allocated outside of the function closure so it can be + // reused with every call, avoiding memory allocation when this function + // is called. + var partialState = {}; + return function stateKeySetter(value) { + partialState[key] = value; + component.setState(partialState); + }; +} + +ReactStateSetters.Mixin = { + /** + * Returns a function that calls the provided function, and uses the result + * of that to set the component's state. + * + * For example, these statements are equivalent: + * + * this.setState({x: 1}); + * this.createStateSetter(function(xValue) { + * return {x: xValue}; + * })(1); + * + * @param {function} funcReturningState Returned callback uses this to + * determine how to update state. + * @return {function} callback that when invoked uses funcReturningState to + * determined the object literal to setState. + */ + createStateSetter: function (funcReturningState) { + return ReactStateSetters.createStateSetter(this, funcReturningState); + }, + + /** + * Returns a single-argument callback that can be used to update a single + * key in the component's state. + * + * For example, these statements are equivalent: + * + * this.setState({x: 1}); + * this.createStateKeySetter('x')(1); + * + * Note: this is memoized function, which makes it inexpensive to call. + * + * @param {string} key The key in the state that you should update. + * @return {function} callback of 1 argument which calls setState() with + * the provided keyName and callback argument. + */ + createStateKeySetter: function (key) { + return ReactStateSetters.createStateKeySetter(this, key); + } +}; + +module.exports = ReactStateSetters; +},{}],91:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactTestUtils + */ + +'use strict'; + +var EventConstants = _dereq_(15); +var EventPluginHub = _dereq_(16); +var EventPropagators = _dereq_(19); +var React = _dereq_(26); +var ReactDOM = _dereq_(40); +var ReactElement = _dereq_(57); +var ReactBrowserEventEmitter = _dereq_(28); +var ReactCompositeComponent = _dereq_(38); +var ReactInstanceHandles = _dereq_(67); +var ReactInstanceMap = _dereq_(68); +var ReactMount = _dereq_(72); +var ReactUpdates = _dereq_(96); +var SyntheticEvent = _dereq_(105); + +var assign = _dereq_(24); +var emptyObject = _dereq_(154); +var findDOMNode = _dereq_(122); +var invariant = _dereq_(161); + +var topLevelTypes = EventConstants.topLevelTypes; + +function Event(suffix) {} + +/** + * @class ReactTestUtils + */ + +function findAllInRenderedTreeInternal(inst, test) { + if (!inst || !inst.getPublicInstance) { + return []; + } + var publicInst = inst.getPublicInstance(); + var ret = test(publicInst) ? [publicInst] : []; + var currentElement = inst._currentElement; + if (ReactTestUtils.isDOMComponent(publicInst)) { + var renderedChildren = inst._renderedChildren; + var key; + for (key in renderedChildren) { + if (!renderedChildren.hasOwnProperty(key)) { + continue; + } + ret = ret.concat(findAllInRenderedTreeInternal(renderedChildren[key], test)); + } + } else if (ReactElement.isValidElement(currentElement) && typeof currentElement.type === 'function') { + ret = ret.concat(findAllInRenderedTreeInternal(inst._renderedComponent, test)); + } + return ret; +} + +/** + * Todo: Support the entire DOM.scry query syntax. For now, these simple + * utilities will suffice for testing purposes. + * @lends ReactTestUtils + */ +var ReactTestUtils = { + renderIntoDocument: function (instance) { + var div = document.createElementNS('http://www.w3.org/1999/xhtml', 'div'); + // None of our tests actually require attaching the container to the + // DOM, and doing so creates a mess that we rely on test isolation to + // clean up, so we're going to stop honoring the name of this method + // (and probably rename it eventually) if no problems arise. + // document.documentElement.appendChild(div); + return ReactDOM.render(instance, div); + }, + + isElement: function (element) { + return ReactElement.isValidElement(element); + }, + + isElementOfType: function (inst, convenienceConstructor) { + return ReactElement.isValidElement(inst) && inst.type === convenienceConstructor; + }, + + isDOMComponent: function (inst) { + return !!(inst && inst.nodeType === 1 && inst.tagName); + }, + + isDOMComponentElement: function (inst) { + return !!(inst && ReactElement.isValidElement(inst) && !!inst.tagName); + }, + + isCompositeComponent: function (inst) { + if (ReactTestUtils.isDOMComponent(inst)) { + // Accessing inst.setState warns; just return false as that'll be what + // this returns when we have DOM nodes as refs directly + return false; + } + return inst != null && typeof inst.render === 'function' && typeof inst.setState === 'function'; + }, + + isCompositeComponentWithType: function (inst, type) { + if (!ReactTestUtils.isCompositeComponent(inst)) { + return false; + } + var internalInstance = ReactInstanceMap.get(inst); + var constructor = internalInstance._currentElement.type; + + return constructor === type; + }, + + isCompositeComponentElement: function (inst) { + if (!ReactElement.isValidElement(inst)) { + return false; + } + // We check the prototype of the type that will get mounted, not the + // instance itself. This is a future proof way of duck typing. + var prototype = inst.type.prototype; + return typeof prototype.render === 'function' && typeof prototype.setState === 'function'; + }, + + isCompositeComponentElementWithType: function (inst, type) { + var internalInstance = ReactInstanceMap.get(inst); + var constructor = internalInstance._currentElement.type; + + return !!(ReactTestUtils.isCompositeComponentElement(inst) && constructor === type); + }, + + getRenderedChildOfCompositeComponent: function (inst) { + if (!ReactTestUtils.isCompositeComponent(inst)) { + return null; + } + var internalInstance = ReactInstanceMap.get(inst); + return internalInstance._renderedComponent.getPublicInstance(); + }, + + findAllInRenderedTree: function (inst, test) { + if (!inst) { + return []; + } + !ReactTestUtils.isCompositeComponent(inst) ? "production" !== 'production' ? invariant(false, 'findAllInRenderedTree(...): instance must be a composite component') : invariant(false) : undefined; + return findAllInRenderedTreeInternal(ReactInstanceMap.get(inst), test); + }, + + /** + * Finds all instance of components in the rendered tree that are DOM + * components with the class name matching `className`. + * @return {array} an array of all the matches. + */ + scryRenderedDOMComponentsWithClass: function (root, classNames) { + if (!Array.isArray(classNames)) { + classNames = classNames.split(/\s+/); + } + return ReactTestUtils.findAllInRenderedTree(root, function (inst) { + if (ReactTestUtils.isDOMComponent(inst)) { + var className = inst.className; + if (typeof className !== 'string') { + // SVG, probably. + className = inst.getAttribute('class') || ''; + } + var classList = className.split(/\s+/); + return classNames.every(function (name) { + return classList.indexOf(name) !== -1; + }); + } + return false; + }); + }, + + /** + * Like scryRenderedDOMComponentsWithClass but expects there to be one result, + * and returns that one result, or throws exception if there is any other + * number of matches besides one. + * @return {!ReactDOMComponent} The one match. + */ + findRenderedDOMComponentWithClass: function (root, className) { + var all = ReactTestUtils.scryRenderedDOMComponentsWithClass(root, className); + if (all.length !== 1) { + throw new Error('Did not find exactly one match ' + '(found: ' + all.length + ') for class:' + className); + } + return all[0]; + }, + + /** + * Finds all instance of components in the rendered tree that are DOM + * components with the tag name matching `tagName`. + * @return {array} an array of all the matches. + */ + scryRenderedDOMComponentsWithTag: function (root, tagName) { + return ReactTestUtils.findAllInRenderedTree(root, function (inst) { + return ReactTestUtils.isDOMComponent(inst) && inst.tagName.toUpperCase() === tagName.toUpperCase(); + }); + }, + + /** + * Like scryRenderedDOMComponentsWithTag but expects there to be one result, + * and returns that one result, or throws exception if there is any other + * number of matches besides one. + * @return {!ReactDOMComponent} The one match. + */ + findRenderedDOMComponentWithTag: function (root, tagName) { + var all = ReactTestUtils.scryRenderedDOMComponentsWithTag(root, tagName); + if (all.length !== 1) { + throw new Error('Did not find exactly one match for tag:' + tagName); + } + return all[0]; + }, + + /** + * Finds all instances of components with type equal to `componentType`. + * @return {array} an array of all the matches. + */ + scryRenderedComponentsWithType: function (root, componentType) { + return ReactTestUtils.findAllInRenderedTree(root, function (inst) { + return ReactTestUtils.isCompositeComponentWithType(inst, componentType); + }); + }, + + /** + * Same as `scryRenderedComponentsWithType` but expects there to be one result + * and returns that one result, or throws exception if there is any other + * number of matches besides one. + * @return {!ReactComponent} The one match. + */ + findRenderedComponentWithType: function (root, componentType) { + var all = ReactTestUtils.scryRenderedComponentsWithType(root, componentType); + if (all.length !== 1) { + throw new Error('Did not find exactly one match for componentType:' + componentType + ' (found ' + all.length + ')'); + } + return all[0]; + }, + + /** + * Pass a mocked component module to this method to augment it with + * useful methods that allow it to be used as a dummy React component. + * Instead of rendering as usual, the component will become a simple + * <div> containing any provided children. + * + * @param {object} module the mock function object exported from a + * module that defines the component to be mocked + * @param {?string} mockTagName optional dummy root tag name to return + * from render method (overrides + * module.mockTagName if provided) + * @return {object} the ReactTestUtils object (for chaining) + */ + mockComponent: function (module, mockTagName) { + mockTagName = mockTagName || module.mockTagName || 'div'; + + module.prototype.render.mockImplementation(function () { + return React.createElement(mockTagName, null, this.props.children); + }); + + return this; + }, + + /** + * Simulates a top level event being dispatched from a raw event that occurred + * on an `Element` node. + * @param {Object} topLevelType A type from `EventConstants.topLevelTypes` + * @param {!Element} node The dom to simulate an event occurring on. + * @param {?Event} fakeNativeEvent Fake native event to use in SyntheticEvent. + */ + simulateNativeEventOnNode: function (topLevelType, node, fakeNativeEvent) { + fakeNativeEvent.target = node; + ReactBrowserEventEmitter.ReactEventListener.dispatchEvent(topLevelType, fakeNativeEvent); + }, + + /** + * Simulates a top level event being dispatched from a raw event that occurred + * on the `ReactDOMComponent` `comp`. + * @param {Object} topLevelType A type from `EventConstants.topLevelTypes`. + * @param {!ReactDOMComponent} comp + * @param {?Event} fakeNativeEvent Fake native event to use in SyntheticEvent. + */ + simulateNativeEventOnDOMComponent: function (topLevelType, comp, fakeNativeEvent) { + ReactTestUtils.simulateNativeEventOnNode(topLevelType, findDOMNode(comp), fakeNativeEvent); + }, + + nativeTouchData: function (x, y) { + return { + touches: [{ pageX: x, pageY: y }] + }; + }, + + createRenderer: function () { + return new ReactShallowRenderer(); + }, + + Simulate: null, + SimulateNative: {} +}; + +/** + * @class ReactShallowRenderer + */ +var ReactShallowRenderer = function () { + this._instance = null; +}; + +ReactShallowRenderer.prototype.getRenderOutput = function () { + return this._instance && this._instance._renderedComponent && this._instance._renderedComponent._renderedOutput || null; +}; + +var NoopInternalComponent = function (element) { + this._renderedOutput = element; + this._currentElement = element; +}; + +NoopInternalComponent.prototype = { + + mountComponent: function () {}, + + receiveComponent: function (element) { + this._renderedOutput = element; + this._currentElement = element; + }, + + unmountComponent: function () {}, + + getPublicInstance: function () { + return null; + } +}; + +var ShallowComponentWrapper = function () {}; +assign(ShallowComponentWrapper.prototype, ReactCompositeComponent.Mixin, { + _instantiateReactComponent: function (element) { + return new NoopInternalComponent(element); + }, + _replaceNodeWithMarkupByID: function () {}, + _renderValidatedComponent: ReactCompositeComponent.Mixin._renderValidatedComponentWithoutOwnerOrContext +}); + +ReactShallowRenderer.prototype.render = function (element, context) { + !ReactElement.isValidElement(element) ? "production" !== 'production' ? invariant(false, 'ReactShallowRenderer render(): Invalid component element.%s', typeof element === 'function' ? ' Instead of passing a component class, make sure to instantiate ' + 'it by passing it to React.createElement.' : '') : invariant(false) : undefined; + !(typeof element.type !== 'string') ? "production" !== 'production' ? invariant(false, 'ReactShallowRenderer render(): Shallow rendering works only with custom ' + 'components, not primitives (%s). Instead of calling `.render(el)` and ' + 'inspecting the rendered output, look at `el.props` directly instead.', element.type) : invariant(false) : undefined; + + if (!context) { + context = emptyObject; + } + var transaction = ReactUpdates.ReactReconcileTransaction.getPooled(false); + this._render(element, transaction, context); + ReactUpdates.ReactReconcileTransaction.release(transaction); +}; + +ReactShallowRenderer.prototype.unmount = function () { + if (this._instance) { + this._instance.unmountComponent(); + } +}; + +ReactShallowRenderer.prototype._render = function (element, transaction, context) { + if (this._instance) { + this._instance.receiveComponent(element, transaction, context); + } else { + var rootID = ReactInstanceHandles.createReactRootID(); + var instance = new ShallowComponentWrapper(element.type); + instance.construct(element); + + instance.mountComponent(rootID, transaction, context); + + this._instance = instance; + } +}; + +/** + * Exports: + * + * - `ReactTestUtils.Simulate.click(Element/ReactDOMComponent)` + * - `ReactTestUtils.Simulate.mouseMove(Element/ReactDOMComponent)` + * - `ReactTestUtils.Simulate.change(Element/ReactDOMComponent)` + * - ... (All keys from event plugin `eventTypes` objects) + */ +function makeSimulator(eventType) { + return function (domComponentOrNode, eventData) { + var node; + if (ReactTestUtils.isDOMComponent(domComponentOrNode)) { + node = findDOMNode(domComponentOrNode); + } else if (domComponentOrNode.tagName) { + node = domComponentOrNode; + } + + var dispatchConfig = ReactBrowserEventEmitter.eventNameDispatchConfigs[eventType]; + + var fakeNativeEvent = new Event(); + fakeNativeEvent.target = node; + // We don't use SyntheticEvent.getPooled in order to not have to worry about + // properly destroying any properties assigned from `eventData` upon release + var event = new SyntheticEvent(dispatchConfig, ReactMount.getID(node), fakeNativeEvent, node); + assign(event, eventData); + + if (dispatchConfig.phasedRegistrationNames) { + EventPropagators.accumulateTwoPhaseDispatches(event); + } else { + EventPropagators.accumulateDirectDispatches(event); + } + + ReactUpdates.batchedUpdates(function () { + EventPluginHub.enqueueEvents(event); + EventPluginHub.processEventQueue(true); + }); + }; +} + +function buildSimulators() { + ReactTestUtils.Simulate = {}; + + var eventType; + for (eventType in ReactBrowserEventEmitter.eventNameDispatchConfigs) { + /** + * @param {!Element|ReactDOMComponent} domComponentOrNode + * @param {?object} eventData Fake event data to use in SyntheticEvent. + */ + ReactTestUtils.Simulate[eventType] = makeSimulator(eventType); + } +} + +// Rebuild ReactTestUtils.Simulate whenever event plugins are injected +var oldInjectEventPluginOrder = EventPluginHub.injection.injectEventPluginOrder; +EventPluginHub.injection.injectEventPluginOrder = function () { + oldInjectEventPluginOrder.apply(this, arguments); + buildSimulators(); +}; +var oldInjectEventPlugins = EventPluginHub.injection.injectEventPluginsByName; +EventPluginHub.injection.injectEventPluginsByName = function () { + oldInjectEventPlugins.apply(this, arguments); + buildSimulators(); +}; + +buildSimulators(); + +/** + * Exports: + * + * - `ReactTestUtils.SimulateNative.click(Element/ReactDOMComponent)` + * - `ReactTestUtils.SimulateNative.mouseMove(Element/ReactDOMComponent)` + * - `ReactTestUtils.SimulateNative.mouseIn/ReactDOMComponent)` + * - `ReactTestUtils.SimulateNative.mouseOut(Element/ReactDOMComponent)` + * - ... (All keys from `EventConstants.topLevelTypes`) + * + * Note: Top level event types are a subset of the entire set of handler types + * (which include a broader set of "synthetic" events). For example, onDragDone + * is a synthetic event. Except when testing an event plugin or React's event + * handling code specifically, you probably want to use ReactTestUtils.Simulate + * to dispatch synthetic events. + */ + +function makeNativeSimulator(eventType) { + return function (domComponentOrNode, nativeEventData) { + var fakeNativeEvent = new Event(eventType); + assign(fakeNativeEvent, nativeEventData); + if (ReactTestUtils.isDOMComponent(domComponentOrNode)) { + ReactTestUtils.simulateNativeEventOnDOMComponent(eventType, domComponentOrNode, fakeNativeEvent); + } else if (domComponentOrNode.tagName) { + // Will allow on actual dom nodes. + ReactTestUtils.simulateNativeEventOnNode(eventType, domComponentOrNode, fakeNativeEvent); + } + }; +} + +Object.keys(topLevelTypes).forEach(function (eventType) { + // Event type is stored as 'topClick' - we transform that to 'click' + var convenienceName = eventType.indexOf('top') === 0 ? eventType.charAt(3).toLowerCase() + eventType.substr(4) : eventType; + /** + * @param {!Element|ReactDOMComponent} domComponentOrNode + * @param {?Event} nativeEventData Fake native event to use in SyntheticEvent. + */ + ReactTestUtils.SimulateNative[convenienceName] = makeNativeSimulator(eventType); +}); + +module.exports = ReactTestUtils; +},{"105":105,"122":122,"15":15,"154":154,"16":16,"161":161,"19":19,"24":24,"26":26,"28":28,"38":38,"40":40,"57":57,"67":67,"68":68,"72":72,"96":96}],92:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @typechecks static-only + * @providesModule ReactTransitionChildMapping + */ + +'use strict'; + +var flattenChildren = _dereq_(123); + +var ReactTransitionChildMapping = { + /** + * Given `this.props.children`, return an object mapping key to child. Just + * simple syntactic sugar around flattenChildren(). + * + * @param {*} children `this.props.children` + * @return {object} Mapping of key to child + */ + getChildMapping: function (children) { + if (!children) { + return children; + } + return flattenChildren(children); + }, + + /** + * When you're adding or removing children some may be added or removed in the + * same render pass. We want to show *both* since we want to simultaneously + * animate elements in and out. This function takes a previous set of keys + * and a new set of keys and merges them with its best guess of the correct + * ordering. In the future we may expose some of the utilities in + * ReactMultiChild to make this easy, but for now React itself does not + * directly have this concept of the union of prevChildren and nextChildren + * so we implement it here. + * + * @param {object} prev prev children as returned from + * `ReactTransitionChildMapping.getChildMapping()`. + * @param {object} next next children as returned from + * `ReactTransitionChildMapping.getChildMapping()`. + * @return {object} a key set that contains all keys in `prev` and all keys + * in `next` in a reasonable order. + */ + mergeChildMappings: function (prev, next) { + prev = prev || {}; + next = next || {}; + + function getValueForKey(key) { + if (next.hasOwnProperty(key)) { + return next[key]; + } else { + return prev[key]; + } + } + + // For each key of `next`, the list of keys to insert before that key in + // the combined list + var nextKeysPending = {}; + + var pendingKeys = []; + for (var prevKey in prev) { + if (next.hasOwnProperty(prevKey)) { + if (pendingKeys.length) { + nextKeysPending[prevKey] = pendingKeys; + pendingKeys = []; + } + } else { + pendingKeys.push(prevKey); + } + } + + var i; + var childMapping = {}; + for (var nextKey in next) { + if (nextKeysPending.hasOwnProperty(nextKey)) { + for (i = 0; i < nextKeysPending[nextKey].length; i++) { + var pendingNextKey = nextKeysPending[nextKey][i]; + childMapping[nextKeysPending[nextKey][i]] = getValueForKey(pendingNextKey); + } + } + childMapping[nextKey] = getValueForKey(nextKey); + } + + // Finally, add the keys which didn't appear before any key in `next` + for (i = 0; i < pendingKeys.length; i++) { + childMapping[pendingKeys[i]] = getValueForKey(pendingKeys[i]); + } + + return childMapping; + } +}; + +module.exports = ReactTransitionChildMapping; +},{"123":123}],93:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactTransitionEvents + */ + +'use strict'; + +var ExecutionEnvironment = _dereq_(147); + +/** + * EVENT_NAME_MAP is used to determine which event fired when a + * transition/animation ends, based on the style property used to + * define that event. + */ +var EVENT_NAME_MAP = { + transitionend: { + 'transition': 'transitionend', + 'WebkitTransition': 'webkitTransitionEnd', + 'MozTransition': 'mozTransitionEnd', + 'OTransition': 'oTransitionEnd', + 'msTransition': 'MSTransitionEnd' + }, + + animationend: { + 'animation': 'animationend', + 'WebkitAnimation': 'webkitAnimationEnd', + 'MozAnimation': 'mozAnimationEnd', + 'OAnimation': 'oAnimationEnd', + 'msAnimation': 'MSAnimationEnd' + } +}; + +var endEvents = []; + +function detectEvents() { + var testEl = document.createElementNS('http://www.w3.org/1999/xhtml', 'div'); + var style = testEl.style; + + // On some platforms, in particular some releases of Android 4.x, + // the un-prefixed "animation" and "transition" properties are defined on the + // style object but the events that fire will still be prefixed, so we need + // to check if the un-prefixed events are useable, and if not remove them + // from the map + if (!('AnimationEvent' in window)) { + delete EVENT_NAME_MAP.animationend.animation; + } + + if (!('TransitionEvent' in window)) { + delete EVENT_NAME_MAP.transitionend.transition; + } + + for (var baseEventName in EVENT_NAME_MAP) { + var baseEvents = EVENT_NAME_MAP[baseEventName]; + for (var styleName in baseEvents) { + if (styleName in style) { + endEvents.push(baseEvents[styleName]); + break; + } + } + } +} + +if (ExecutionEnvironment.canUseDOM) { + detectEvents(); +} + +// We use the raw {add|remove}EventListener() call because EventListener +// does not know how to remove event listeners and we really should +// clean up. Also, these events are not triggered in older browsers +// so we should be A-OK here. + +function addEventListener(node, eventName, eventListener) { + node.addEventListener(eventName, eventListener, false); +} + +function removeEventListener(node, eventName, eventListener) { + node.removeEventListener(eventName, eventListener, false); +} + +var ReactTransitionEvents = { + addEndEventListener: function (node, eventListener) { + if (endEvents.length === 0) { + // If CSS transitions are not supported, trigger an "end animation" + // event immediately. + window.setTimeout(eventListener, 0); + return; + } + endEvents.forEach(function (endEvent) { + addEventListener(node, endEvent, eventListener); + }); + }, + + removeEndEventListener: function (node, eventListener) { + if (endEvents.length === 0) { + return; + } + endEvents.forEach(function (endEvent) { + removeEventListener(node, endEvent, eventListener); + }); + } +}; + +module.exports = ReactTransitionEvents; +},{"147":147}],94:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactTransitionGroup + */ + +'use strict'; + +var React = _dereq_(26); +var ReactTransitionChildMapping = _dereq_(92); + +var assign = _dereq_(24); +var emptyFunction = _dereq_(153); + +var ReactTransitionGroup = React.createClass({ + displayName: 'ReactTransitionGroup', + + propTypes: { + component: React.PropTypes.any, + childFactory: React.PropTypes.func + }, + + getDefaultProps: function () { + return { + component: 'span', + childFactory: emptyFunction.thatReturnsArgument + }; + }, + + getInitialState: function () { + return { + children: ReactTransitionChildMapping.getChildMapping(this.props.children) + }; + }, + + componentWillMount: function () { + this.currentlyTransitioningKeys = {}; + this.keysToEnter = []; + this.keysToLeave = []; + }, + + componentDidMount: function () { + var initialChildMapping = this.state.children; + for (var key in initialChildMapping) { + if (initialChildMapping[key]) { + this.performAppear(key); + } + } + }, + + componentWillReceiveProps: function (nextProps) { + var nextChildMapping = ReactTransitionChildMapping.getChildMapping(nextProps.children); + var prevChildMapping = this.state.children; + + this.setState({ + children: ReactTransitionChildMapping.mergeChildMappings(prevChildMapping, nextChildMapping) + }); + + var key; + + for (key in nextChildMapping) { + var hasPrev = prevChildMapping && prevChildMapping.hasOwnProperty(key); + if (nextChildMapping[key] && !hasPrev && !this.currentlyTransitioningKeys[key]) { + this.keysToEnter.push(key); + } + } + + for (key in prevChildMapping) { + var hasNext = nextChildMapping && nextChildMapping.hasOwnProperty(key); + if (prevChildMapping[key] && !hasNext && !this.currentlyTransitioningKeys[key]) { + this.keysToLeave.push(key); + } + } + + // If we want to someday check for reordering, we could do it here. + }, + + componentDidUpdate: function () { + var keysToEnter = this.keysToEnter; + this.keysToEnter = []; + keysToEnter.forEach(this.performEnter); + + var keysToLeave = this.keysToLeave; + this.keysToLeave = []; + keysToLeave.forEach(this.performLeave); + }, + + performAppear: function (key) { + this.currentlyTransitioningKeys[key] = true; + + var component = this.refs[key]; + + if (component.componentWillAppear) { + component.componentWillAppear(this._handleDoneAppearing.bind(this, key)); + } else { + this._handleDoneAppearing(key); + } + }, + + _handleDoneAppearing: function (key) { + var component = this.refs[key]; + if (component.componentDidAppear) { + component.componentDidAppear(); + } + + delete this.currentlyTransitioningKeys[key]; + + var currentChildMapping = ReactTransitionChildMapping.getChildMapping(this.props.children); + + if (!currentChildMapping || !currentChildMapping.hasOwnProperty(key)) { + // This was removed before it had fully appeared. Remove it. + this.performLeave(key); + } + }, + + performEnter: function (key) { + this.currentlyTransitioningKeys[key] = true; + + var component = this.refs[key]; + + if (component.componentWillEnter) { + component.componentWillEnter(this._handleDoneEntering.bind(this, key)); + } else { + this._handleDoneEntering(key); + } + }, + + _handleDoneEntering: function (key) { + var component = this.refs[key]; + if (component.componentDidEnter) { + component.componentDidEnter(); + } + + delete this.currentlyTransitioningKeys[key]; + + var currentChildMapping = ReactTransitionChildMapping.getChildMapping(this.props.children); + + if (!currentChildMapping || !currentChildMapping.hasOwnProperty(key)) { + // This was removed before it had fully entered. Remove it. + this.performLeave(key); + } + }, + + performLeave: function (key) { + this.currentlyTransitioningKeys[key] = true; + + var component = this.refs[key]; + if (component.componentWillLeave) { + component.componentWillLeave(this._handleDoneLeaving.bind(this, key)); + } else { + // Note that this is somewhat dangerous b/c it calls setState() + // again, effectively mutating the component before all the work + // is done. + this._handleDoneLeaving(key); + } + }, + + _handleDoneLeaving: function (key) { + var component = this.refs[key]; + + if (component.componentDidLeave) { + component.componentDidLeave(); + } + + delete this.currentlyTransitioningKeys[key]; + + var currentChildMapping = ReactTransitionChildMapping.getChildMapping(this.props.children); + + if (currentChildMapping && currentChildMapping.hasOwnProperty(key)) { + // This entered again before it fully left. Add it again. + this.performEnter(key); + } else { + this.setState(function (state) { + var newChildren = assign({}, state.children); + delete newChildren[key]; + return { children: newChildren }; + }); + } + }, + + render: function () { + // TODO: we could get rid of the need for the wrapper node + // by cloning a single child + var childrenToRender = []; + for (var key in this.state.children) { + var child = this.state.children[key]; + if (child) { + // You may need to apply reactive updates to a child as it is leaving. + // The normal React way to do it won't work since the child will have + // already been removed. In case you need this behavior you can provide + // a childFactory function to wrap every child, even the ones that are + // leaving. + childrenToRender.push(React.cloneElement(this.props.childFactory(child), { ref: key, key: key })); + } + } + return React.createElement(this.props.component, this.props, childrenToRender); + } +}); + +module.exports = ReactTransitionGroup; +},{"153":153,"24":24,"26":26,"92":92}],95:[function(_dereq_,module,exports){ +/** + * Copyright 2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactUpdateQueue + */ + +'use strict'; + +var ReactCurrentOwner = _dereq_(39); +var ReactElement = _dereq_(57); +var ReactInstanceMap = _dereq_(68); +var ReactUpdates = _dereq_(96); + +var assign = _dereq_(24); +var invariant = _dereq_(161); +var warning = _dereq_(173); + +function enqueueUpdate(internalInstance) { + ReactUpdates.enqueueUpdate(internalInstance); +} + +function getInternalInstanceReadyForUpdate(publicInstance, callerName) { + var internalInstance = ReactInstanceMap.get(publicInstance); + if (!internalInstance) { + if ("production" !== 'production') { + // Only warn when we have a callerName. Otherwise we should be silent. + // We're probably calling from enqueueCallback. We don't want to warn + // there because we already warned for the corresponding lifecycle method. + "production" !== 'production' ? warning(!callerName, '%s(...): Can only update a mounted or mounting component. ' + 'This usually means you called %s() on an unmounted component. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, publicInstance.constructor.displayName) : undefined; + } + return null; + } + + if ("production" !== 'production') { + "production" !== 'production' ? warning(ReactCurrentOwner.current == null, '%s(...): Cannot update during an existing state transition ' + '(such as within `render`). Render methods should be a pure function ' + 'of props and state.', callerName) : undefined; + } + + return internalInstance; +} + +/** + * ReactUpdateQueue allows for state updates to be scheduled into a later + * reconciliation step. + */ +var ReactUpdateQueue = { + + /** + * Checks whether or not this composite component is mounted. + * @param {ReactClass} publicInstance The instance we want to test. + * @return {boolean} True if mounted, false otherwise. + * @protected + * @final + */ + isMounted: function (publicInstance) { + if ("production" !== 'production') { + var owner = ReactCurrentOwner.current; + if (owner !== null) { + "production" !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing isMounted inside its render() function. ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component') : undefined; + owner._warnedAboutRefsInRender = true; + } + } + var internalInstance = ReactInstanceMap.get(publicInstance); + if (internalInstance) { + // During componentWillMount and render this will still be null but after + // that will always render to something. At least for now. So we can use + // this hack. + return !!internalInstance._renderedComponent; + } else { + return false; + } + }, + + /** + * Enqueue a callback that will be executed after all the pending updates + * have processed. + * + * @param {ReactClass} publicInstance The instance to use as `this` context. + * @param {?function} callback Called after state is updated. + * @internal + */ + enqueueCallback: function (publicInstance, callback) { + !(typeof callback === 'function') ? "production" !== 'production' ? invariant(false, 'enqueueCallback(...): You called `setProps`, `replaceProps`, ' + '`setState`, `replaceState`, or `forceUpdate` with a callback that ' + 'isn\'t callable.') : invariant(false) : undefined; + var internalInstance = getInternalInstanceReadyForUpdate(publicInstance); + + // Previously we would throw an error if we didn't have an internal + // instance. Since we want to make it a no-op instead, we mirror the same + // behavior we have in other enqueue* methods. + // We also need to ignore callbacks in componentWillMount. See + // enqueueUpdates. + if (!internalInstance) { + return null; + } + + if (internalInstance._pendingCallbacks) { + internalInstance._pendingCallbacks.push(callback); + } else { + internalInstance._pendingCallbacks = [callback]; + } + // TODO: The callback here is ignored when setState is called from + // componentWillMount. Either fix it or disallow doing so completely in + // favor of getInitialState. Alternatively, we can disallow + // componentWillMount during server-side rendering. + enqueueUpdate(internalInstance); + }, + + enqueueCallbackInternal: function (internalInstance, callback) { + !(typeof callback === 'function') ? "production" !== 'production' ? invariant(false, 'enqueueCallback(...): You called `setProps`, `replaceProps`, ' + '`setState`, `replaceState`, or `forceUpdate` with a callback that ' + 'isn\'t callable.') : invariant(false) : undefined; + if (internalInstance._pendingCallbacks) { + internalInstance._pendingCallbacks.push(callback); + } else { + internalInstance._pendingCallbacks = [callback]; + } + enqueueUpdate(internalInstance); + }, + + /** + * Forces an update. This should only be invoked when it is known with + * certainty that we are **not** in a DOM transaction. + * + * You may want to call this when you know that some deeper aspect of the + * component's state has changed but `setState` was not called. + * + * This will not invoke `shouldComponentUpdate`, but it will invoke + * `componentWillUpdate` and `componentDidUpdate`. + * + * @param {ReactClass} publicInstance The instance that should rerender. + * @internal + */ + enqueueForceUpdate: function (publicInstance) { + var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'forceUpdate'); + + if (!internalInstance) { + return; + } + + internalInstance._pendingForceUpdate = true; + + enqueueUpdate(internalInstance); + }, + + /** + * Replaces all of the state. Always use this or `setState` to mutate state. + * You should treat `this.state` as immutable. + * + * There is no guarantee that `this.state` will be immediately updated, so + * accessing `this.state` after calling this method may return the old value. + * + * @param {ReactClass} publicInstance The instance that should rerender. + * @param {object} completeState Next state. + * @internal + */ + enqueueReplaceState: function (publicInstance, completeState) { + var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'replaceState'); + + if (!internalInstance) { + return; + } + + internalInstance._pendingStateQueue = [completeState]; + internalInstance._pendingReplaceState = true; + + enqueueUpdate(internalInstance); + }, + + /** + * Sets a subset of the state. This only exists because _pendingState is + * internal. This provides a merging strategy that is not available to deep + * properties which is confusing. TODO: Expose pendingState or don't use it + * during the merge. + * + * @param {ReactClass} publicInstance The instance that should rerender. + * @param {object} partialState Next partial state to be merged with state. + * @internal + */ + enqueueSetState: function (publicInstance, partialState) { + var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'setState'); + + if (!internalInstance) { + return; + } + + var queue = internalInstance._pendingStateQueue || (internalInstance._pendingStateQueue = []); + queue.push(partialState); + + enqueueUpdate(internalInstance); + }, + + /** + * Sets a subset of the props. + * + * @param {ReactClass} publicInstance The instance that should rerender. + * @param {object} partialProps Subset of the next props. + * @internal + */ + enqueueSetProps: function (publicInstance, partialProps) { + var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'setProps'); + if (!internalInstance) { + return; + } + ReactUpdateQueue.enqueueSetPropsInternal(internalInstance, partialProps); + }, + + enqueueSetPropsInternal: function (internalInstance, partialProps) { + var topLevelWrapper = internalInstance._topLevelWrapper; + !topLevelWrapper ? "production" !== 'production' ? invariant(false, 'setProps(...): You called `setProps` on a ' + 'component with a parent. This is an anti-pattern since props will ' + 'get reactively updated when rendered. Instead, change the owner\'s ' + '`render` method to pass the correct value as props to the component ' + 'where it is created.') : invariant(false) : undefined; + + // Merge with the pending element if it exists, otherwise with existing + // element props. + var wrapElement = topLevelWrapper._pendingElement || topLevelWrapper._currentElement; + var element = wrapElement.props; + var props = assign({}, element.props, partialProps); + topLevelWrapper._pendingElement = ReactElement.cloneAndReplaceProps(wrapElement, ReactElement.cloneAndReplaceProps(element, props)); + + enqueueUpdate(topLevelWrapper); + }, + + /** + * Replaces all of the props. + * + * @param {ReactClass} publicInstance The instance that should rerender. + * @param {object} props New props. + * @internal + */ + enqueueReplaceProps: function (publicInstance, props) { + var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'replaceProps'); + if (!internalInstance) { + return; + } + ReactUpdateQueue.enqueueReplacePropsInternal(internalInstance, props); + }, + + enqueueReplacePropsInternal: function (internalInstance, props) { + var topLevelWrapper = internalInstance._topLevelWrapper; + !topLevelWrapper ? "production" !== 'production' ? invariant(false, 'replaceProps(...): You called `replaceProps` on a ' + 'component with a parent. This is an anti-pattern since props will ' + 'get reactively updated when rendered. Instead, change the owner\'s ' + '`render` method to pass the correct value as props to the component ' + 'where it is created.') : invariant(false) : undefined; + + // Merge with the pending element if it exists, otherwise with existing + // element props. + var wrapElement = topLevelWrapper._pendingElement || topLevelWrapper._currentElement; + var element = wrapElement.props; + topLevelWrapper._pendingElement = ReactElement.cloneAndReplaceProps(wrapElement, ReactElement.cloneAndReplaceProps(element, props)); + + enqueueUpdate(topLevelWrapper); + }, + + enqueueElementInternal: function (internalInstance, newElement) { + internalInstance._pendingElement = newElement; + enqueueUpdate(internalInstance); + } + +}; + +module.exports = ReactUpdateQueue; +},{"161":161,"173":173,"24":24,"39":39,"57":57,"68":68,"96":96}],96:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactUpdates + */ + +'use strict'; + +var CallbackQueue = _dereq_(6); +var PooledClass = _dereq_(25); +var ReactPerf = _dereq_(78); +var ReactReconciler = _dereq_(84); +var Transaction = _dereq_(113); + +var assign = _dereq_(24); +var invariant = _dereq_(161); + +var dirtyComponents = []; +var asapCallbackQueue = CallbackQueue.getPooled(); +var asapEnqueued = false; + +var batchingStrategy = null; + +function ensureInjected() { + !(ReactUpdates.ReactReconcileTransaction && batchingStrategy) ? "production" !== 'production' ? invariant(false, 'ReactUpdates: must inject a reconcile transaction class and batching ' + 'strategy') : invariant(false) : undefined; +} + +var NESTED_UPDATES = { + initialize: function () { + this.dirtyComponentsLength = dirtyComponents.length; + }, + close: function () { + if (this.dirtyComponentsLength !== dirtyComponents.length) { + // Additional updates were enqueued by componentDidUpdate handlers or + // similar; before our own UPDATE_QUEUEING wrapper closes, we want to run + // these new updates so that if A's componentDidUpdate calls setState on + // B, B will update before the callback A's updater provided when calling + // setState. + dirtyComponents.splice(0, this.dirtyComponentsLength); + flushBatchedUpdates(); + } else { + dirtyComponents.length = 0; + } + } +}; + +var UPDATE_QUEUEING = { + initialize: function () { + this.callbackQueue.reset(); + }, + close: function () { + this.callbackQueue.notifyAll(); + } +}; + +var TRANSACTION_WRAPPERS = [NESTED_UPDATES, UPDATE_QUEUEING]; + +function ReactUpdatesFlushTransaction() { + this.reinitializeTransaction(); + this.dirtyComponentsLength = null; + this.callbackQueue = CallbackQueue.getPooled(); + this.reconcileTransaction = ReactUpdates.ReactReconcileTransaction.getPooled( /* forceHTML */false); +} + +assign(ReactUpdatesFlushTransaction.prototype, Transaction.Mixin, { + getTransactionWrappers: function () { + return TRANSACTION_WRAPPERS; + }, + + destructor: function () { + this.dirtyComponentsLength = null; + CallbackQueue.release(this.callbackQueue); + this.callbackQueue = null; + ReactUpdates.ReactReconcileTransaction.release(this.reconcileTransaction); + this.reconcileTransaction = null; + }, + + perform: function (method, scope, a) { + // Essentially calls `this.reconcileTransaction.perform(method, scope, a)` + // with this transaction's wrappers around it. + return Transaction.Mixin.perform.call(this, this.reconcileTransaction.perform, this.reconcileTransaction, method, scope, a); + } +}); + +PooledClass.addPoolingTo(ReactUpdatesFlushTransaction); + +function batchedUpdates(callback, a, b, c, d, e) { + ensureInjected(); + batchingStrategy.batchedUpdates(callback, a, b, c, d, e); +} + +/** + * Array comparator for ReactComponents by mount ordering. + * + * @param {ReactComponent} c1 first component you're comparing + * @param {ReactComponent} c2 second component you're comparing + * @return {number} Return value usable by Array.prototype.sort(). + */ +function mountOrderComparator(c1, c2) { + return c1._mountOrder - c2._mountOrder; +} + +function runBatchedUpdates(transaction) { + var len = transaction.dirtyComponentsLength; + !(len === dirtyComponents.length) ? "production" !== 'production' ? invariant(false, 'Expected flush transaction\'s stored dirty-components length (%s) to ' + 'match dirty-components array length (%s).', len, dirtyComponents.length) : invariant(false) : undefined; + + // Since reconciling a component higher in the owner hierarchy usually (not + // always -- see shouldComponentUpdate()) will reconcile children, reconcile + // them before their children by sorting the array. + dirtyComponents.sort(mountOrderComparator); + + for (var i = 0; i < len; i++) { + // If a component is unmounted before pending changes apply, it will still + // be here, but we assume that it has cleared its _pendingCallbacks and + // that performUpdateIfNecessary is a noop. + var component = dirtyComponents[i]; + + // If performUpdateIfNecessary happens to enqueue any new updates, we + // shouldn't execute the callbacks until the next render happens, so + // stash the callbacks first + var callbacks = component._pendingCallbacks; + component._pendingCallbacks = null; + + ReactReconciler.performUpdateIfNecessary(component, transaction.reconcileTransaction); + + if (callbacks) { + for (var j = 0; j < callbacks.length; j++) { + transaction.callbackQueue.enqueue(callbacks[j], component.getPublicInstance()); + } + } + } +} + +var flushBatchedUpdates = function () { + // ReactUpdatesFlushTransaction's wrappers will clear the dirtyComponents + // array and perform any updates enqueued by mount-ready handlers (i.e., + // componentDidUpdate) but we need to check here too in order to catch + // updates enqueued by setState callbacks and asap calls. + while (dirtyComponents.length || asapEnqueued) { + if (dirtyComponents.length) { + var transaction = ReactUpdatesFlushTransaction.getPooled(); + transaction.perform(runBatchedUpdates, null, transaction); + ReactUpdatesFlushTransaction.release(transaction); + } + + if (asapEnqueued) { + asapEnqueued = false; + var queue = asapCallbackQueue; + asapCallbackQueue = CallbackQueue.getPooled(); + queue.notifyAll(); + CallbackQueue.release(queue); + } + } +}; +flushBatchedUpdates = ReactPerf.measure('ReactUpdates', 'flushBatchedUpdates', flushBatchedUpdates); + +/** + * Mark a component as needing a rerender, adding an optional callback to a + * list of functions which will be executed once the rerender occurs. + */ +function enqueueUpdate(component) { + ensureInjected(); + + // Various parts of our code (such as ReactCompositeComponent's + // _renderValidatedComponent) assume that calls to render aren't nested; + // verify that that's the case. (This is called by each top-level update + // function, like setProps, setState, forceUpdate, etc.; creation and + // destruction of top-level components is guarded in ReactMount.) + + if (!batchingStrategy.isBatchingUpdates) { + batchingStrategy.batchedUpdates(enqueueUpdate, component); + return; + } + + dirtyComponents.push(component); +} + +/** + * Enqueue a callback to be run at the end of the current batching cycle. Throws + * if no updates are currently being performed. + */ +function asap(callback, context) { + !batchingStrategy.isBatchingUpdates ? "production" !== 'production' ? invariant(false, 'ReactUpdates.asap: Can\'t enqueue an asap callback in a context where' + 'updates are not being batched.') : invariant(false) : undefined; + asapCallbackQueue.enqueue(callback, context); + asapEnqueued = true; +} + +var ReactUpdatesInjection = { + injectReconcileTransaction: function (ReconcileTransaction) { + !ReconcileTransaction ? "production" !== 'production' ? invariant(false, 'ReactUpdates: must provide a reconcile transaction class') : invariant(false) : undefined; + ReactUpdates.ReactReconcileTransaction = ReconcileTransaction; + }, + + injectBatchingStrategy: function (_batchingStrategy) { + !_batchingStrategy ? "production" !== 'production' ? invariant(false, 'ReactUpdates: must provide a batching strategy') : invariant(false) : undefined; + !(typeof _batchingStrategy.batchedUpdates === 'function') ? "production" !== 'production' ? invariant(false, 'ReactUpdates: must provide a batchedUpdates() function') : invariant(false) : undefined; + !(typeof _batchingStrategy.isBatchingUpdates === 'boolean') ? "production" !== 'production' ? invariant(false, 'ReactUpdates: must provide an isBatchingUpdates boolean attribute') : invariant(false) : undefined; + batchingStrategy = _batchingStrategy; + } +}; + +var ReactUpdates = { + /** + * React references `ReactReconcileTransaction` using this property in order + * to allow dependency injection. + * + * @internal + */ + ReactReconcileTransaction: null, + + batchedUpdates: batchedUpdates, + enqueueUpdate: enqueueUpdate, + flushBatchedUpdates: flushBatchedUpdates, + injection: ReactUpdatesInjection, + asap: asap +}; + +module.exports = ReactUpdates; +},{"113":113,"161":161,"24":24,"25":25,"6":6,"78":78,"84":84}],97:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactVersion + */ + +'use strict'; + +module.exports = '0.14.6'; +},{}],98:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule SVGDOMPropertyConfig + */ + +'use strict'; + +var DOMProperty = _dereq_(10); + +var MUST_USE_ATTRIBUTE = DOMProperty.injection.MUST_USE_ATTRIBUTE; + +var NS = { + xlink: 'http://www.w3.org/1999/xlink', + xml: 'http://www.w3.org/XML/1998/namespace' +}; + +var SVGDOMPropertyConfig = { + Properties: { + clipPath: MUST_USE_ATTRIBUTE, + cx: MUST_USE_ATTRIBUTE, + cy: MUST_USE_ATTRIBUTE, + d: MUST_USE_ATTRIBUTE, + dx: MUST_USE_ATTRIBUTE, + dy: MUST_USE_ATTRIBUTE, + fill: MUST_USE_ATTRIBUTE, + fillOpacity: MUST_USE_ATTRIBUTE, + fontFamily: MUST_USE_ATTRIBUTE, + fontSize: MUST_USE_ATTRIBUTE, + fx: MUST_USE_ATTRIBUTE, + fy: MUST_USE_ATTRIBUTE, + gradientTransform: MUST_USE_ATTRIBUTE, + gradientUnits: MUST_USE_ATTRIBUTE, + markerEnd: MUST_USE_ATTRIBUTE, + markerMid: MUST_USE_ATTRIBUTE, + markerStart: MUST_USE_ATTRIBUTE, + offset: MUST_USE_ATTRIBUTE, + opacity: MUST_USE_ATTRIBUTE, + patternContentUnits: MUST_USE_ATTRIBUTE, + patternUnits: MUST_USE_ATTRIBUTE, + points: MUST_USE_ATTRIBUTE, + preserveAspectRatio: MUST_USE_ATTRIBUTE, + r: MUST_USE_ATTRIBUTE, + rx: MUST_USE_ATTRIBUTE, + ry: MUST_USE_ATTRIBUTE, + spreadMethod: MUST_USE_ATTRIBUTE, + stopColor: MUST_USE_ATTRIBUTE, + stopOpacity: MUST_USE_ATTRIBUTE, + stroke: MUST_USE_ATTRIBUTE, + strokeDasharray: MUST_USE_ATTRIBUTE, + strokeLinecap: MUST_USE_ATTRIBUTE, + strokeOpacity: MUST_USE_ATTRIBUTE, + strokeWidth: MUST_USE_ATTRIBUTE, + textAnchor: MUST_USE_ATTRIBUTE, + transform: MUST_USE_ATTRIBUTE, + version: MUST_USE_ATTRIBUTE, + viewBox: MUST_USE_ATTRIBUTE, + x1: MUST_USE_ATTRIBUTE, + x2: MUST_USE_ATTRIBUTE, + x: MUST_USE_ATTRIBUTE, + xlinkActuate: MUST_USE_ATTRIBUTE, + xlinkArcrole: MUST_USE_ATTRIBUTE, + xlinkHref: MUST_USE_ATTRIBUTE, + xlinkRole: MUST_USE_ATTRIBUTE, + xlinkShow: MUST_USE_ATTRIBUTE, + xlinkTitle: MUST_USE_ATTRIBUTE, + xlinkType: MUST_USE_ATTRIBUTE, + xmlBase: MUST_USE_ATTRIBUTE, + xmlLang: MUST_USE_ATTRIBUTE, + xmlSpace: MUST_USE_ATTRIBUTE, + y1: MUST_USE_ATTRIBUTE, + y2: MUST_USE_ATTRIBUTE, + y: MUST_USE_ATTRIBUTE + }, + DOMAttributeNamespaces: { + xlinkActuate: NS.xlink, + xlinkArcrole: NS.xlink, + xlinkHref: NS.xlink, + xlinkRole: NS.xlink, + xlinkShow: NS.xlink, + xlinkTitle: NS.xlink, + xlinkType: NS.xlink, + xmlBase: NS.xml, + xmlLang: NS.xml, + xmlSpace: NS.xml + }, + DOMAttributeNames: { + clipPath: 'clip-path', + fillOpacity: 'fill-opacity', + fontFamily: 'font-family', + fontSize: 'font-size', + gradientTransform: 'gradientTransform', + gradientUnits: 'gradientUnits', + markerEnd: 'marker-end', + markerMid: 'marker-mid', + markerStart: 'marker-start', + patternContentUnits: 'patternContentUnits', + patternUnits: 'patternUnits', + preserveAspectRatio: 'preserveAspectRatio', + spreadMethod: 'spreadMethod', + stopColor: 'stop-color', + stopOpacity: 'stop-opacity', + strokeDasharray: 'stroke-dasharray', + strokeLinecap: 'stroke-linecap', + strokeOpacity: 'stroke-opacity', + strokeWidth: 'stroke-width', + textAnchor: 'text-anchor', + viewBox: 'viewBox', + xlinkActuate: 'xlink:actuate', + xlinkArcrole: 'xlink:arcrole', + xlinkHref: 'xlink:href', + xlinkRole: 'xlink:role', + xlinkShow: 'xlink:show', + xlinkTitle: 'xlink:title', + xlinkType: 'xlink:type', + xmlBase: 'xml:base', + xmlLang: 'xml:lang', + xmlSpace: 'xml:space' + } +}; + +module.exports = SVGDOMPropertyConfig; +},{"10":10}],99:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule SelectEventPlugin + */ + +'use strict'; + +var EventConstants = _dereq_(15); +var EventPropagators = _dereq_(19); +var ExecutionEnvironment = _dereq_(147); +var ReactInputSelection = _dereq_(66); +var SyntheticEvent = _dereq_(105); + +var getActiveElement = _dereq_(156); +var isTextInputElement = _dereq_(134); +var keyOf = _dereq_(166); +var shallowEqual = _dereq_(171); + +var topLevelTypes = EventConstants.topLevelTypes; + +var skipSelectionChangeEvent = ExecutionEnvironment.canUseDOM && 'documentMode' in document && document.documentMode <= 11; + +var eventTypes = { + select: { + phasedRegistrationNames: { + bubbled: keyOf({ onSelect: null }), + captured: keyOf({ onSelectCapture: null }) + }, + dependencies: [topLevelTypes.topBlur, topLevelTypes.topContextMenu, topLevelTypes.topFocus, topLevelTypes.topKeyDown, topLevelTypes.topMouseDown, topLevelTypes.topMouseUp, topLevelTypes.topSelectionChange] + } +}; + +var activeElement = null; +var activeElementID = null; +var lastSelection = null; +var mouseDown = false; + +// Track whether a listener exists for this plugin. If none exist, we do +// not extract events. +var hasListener = false; +var ON_SELECT_KEY = keyOf({ onSelect: null }); + +/** + * Get an object which is a unique representation of the current selection. + * + * The return value will not be consistent across nodes or browsers, but + * two identical selections on the same node will return identical objects. + * + * @param {DOMElement} node + * @return {object} + */ +function getSelection(node) { + if ('selectionStart' in node && ReactInputSelection.hasSelectionCapabilities(node)) { + return { + start: node.selectionStart, + end: node.selectionEnd + }; + } else if (window.getSelection) { + var selection = window.getSelection(); + return { + anchorNode: selection.anchorNode, + anchorOffset: selection.anchorOffset, + focusNode: selection.focusNode, + focusOffset: selection.focusOffset + }; + } else if (document.selection) { + var range = document.selection.createRange(); + return { + parentElement: range.parentElement(), + text: range.text, + top: range.boundingTop, + left: range.boundingLeft + }; + } +} + +/** + * Poll selection to see whether it's changed. + * + * @param {object} nativeEvent + * @return {?SyntheticEvent} + */ +function constructSelectEvent(nativeEvent, nativeEventTarget) { + // Ensure we have the right element, and that the user is not dragging a + // selection (this matches native `select` event behavior). In HTML5, select + // fires only on input and textarea thus if there's no focused element we + // won't dispatch. + if (mouseDown || activeElement == null || activeElement !== getActiveElement()) { + return null; + } + + // Only fire when selection has actually changed. + var currentSelection = getSelection(activeElement); + if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) { + lastSelection = currentSelection; + + var syntheticEvent = SyntheticEvent.getPooled(eventTypes.select, activeElementID, nativeEvent, nativeEventTarget); + + syntheticEvent.type = 'select'; + syntheticEvent.target = activeElement; + + EventPropagators.accumulateTwoPhaseDispatches(syntheticEvent); + + return syntheticEvent; + } + + return null; +} + +/** + * This plugin creates an `onSelect` event that normalizes select events + * across form elements. + * + * Supported elements are: + * - input (see `isTextInputElement`) + * - textarea + * - contentEditable + * + * This differs from native browser implementations in the following ways: + * - Fires on contentEditable fields as well as inputs. + * - Fires for collapsed selection. + * - Fires after user input. + */ +var SelectEventPlugin = { + + eventTypes: eventTypes, + + /** + * @param {string} topLevelType Record from `EventConstants`. + * @param {DOMEventTarget} topLevelTarget The listening component root node. + * @param {string} topLevelTargetID ID of `topLevelTarget`. + * @param {object} nativeEvent Native browser event. + * @return {*} An accumulation of synthetic events. + * @see {EventPluginHub.extractEvents} + */ + extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) { + if (!hasListener) { + return null; + } + + switch (topLevelType) { + // Track the input node that has focus. + case topLevelTypes.topFocus: + if (isTextInputElement(topLevelTarget) || topLevelTarget.contentEditable === 'true') { + activeElement = topLevelTarget; + activeElementID = topLevelTargetID; + lastSelection = null; + } + break; + case topLevelTypes.topBlur: + activeElement = null; + activeElementID = null; + lastSelection = null; + break; + + // Don't fire the event while the user is dragging. This matches the + // semantics of the native select event. + case topLevelTypes.topMouseDown: + mouseDown = true; + break; + case topLevelTypes.topContextMenu: + case topLevelTypes.topMouseUp: + mouseDown = false; + return constructSelectEvent(nativeEvent, nativeEventTarget); + + // Chrome and IE fire non-standard event when selection is changed (and + // sometimes when it hasn't). IE's event fires out of order with respect + // to key and input events on deletion, so we discard it. + // + // Firefox doesn't support selectionchange, so check selection status + // after each key entry. The selection changes after keydown and before + // keyup, but we check on keydown as well in the case of holding down a + // key, when multiple keydown events are fired but only one keyup is. + // This is also our approach for IE handling, for the reason above. + case topLevelTypes.topSelectionChange: + if (skipSelectionChangeEvent) { + break; + } + // falls through + case topLevelTypes.topKeyDown: + case topLevelTypes.topKeyUp: + return constructSelectEvent(nativeEvent, nativeEventTarget); + } + + return null; + }, + + didPutListener: function (id, registrationName, listener) { + if (registrationName === ON_SELECT_KEY) { + hasListener = true; + } + } +}; + +module.exports = SelectEventPlugin; +},{"105":105,"134":134,"147":147,"15":15,"156":156,"166":166,"171":171,"19":19,"66":66}],100:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ServerReactRootIndex + * @typechecks + */ + +'use strict'; + +/** + * Size of the reactRoot ID space. We generate random numbers for React root + * IDs and if there's a collision the events and DOM update system will + * get confused. In the future we need a way to generate GUIDs but for + * now this will work on a smaller scale. + */ +var GLOBAL_MOUNT_POINT_MAX = Math.pow(2, 53); + +var ServerReactRootIndex = { + createReactRootIndex: function () { + return Math.ceil(Math.random() * GLOBAL_MOUNT_POINT_MAX); + } +}; + +module.exports = ServerReactRootIndex; +},{}],101:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule SimpleEventPlugin + */ + +'use strict'; + +var EventConstants = _dereq_(15); +var EventListener = _dereq_(146); +var EventPropagators = _dereq_(19); +var ReactMount = _dereq_(72); +var SyntheticClipboardEvent = _dereq_(102); +var SyntheticEvent = _dereq_(105); +var SyntheticFocusEvent = _dereq_(106); +var SyntheticKeyboardEvent = _dereq_(108); +var SyntheticMouseEvent = _dereq_(109); +var SyntheticDragEvent = _dereq_(104); +var SyntheticTouchEvent = _dereq_(110); +var SyntheticUIEvent = _dereq_(111); +var SyntheticWheelEvent = _dereq_(112); + +var emptyFunction = _dereq_(153); +var getEventCharCode = _dereq_(125); +var invariant = _dereq_(161); +var keyOf = _dereq_(166); + +var topLevelTypes = EventConstants.topLevelTypes; + +var eventTypes = { + abort: { + phasedRegistrationNames: { + bubbled: keyOf({ onAbort: true }), + captured: keyOf({ onAbortCapture: true }) + } + }, + blur: { + phasedRegistrationNames: { + bubbled: keyOf({ onBlur: true }), + captured: keyOf({ onBlurCapture: true }) + } + }, + canPlay: { + phasedRegistrationNames: { + bubbled: keyOf({ onCanPlay: true }), + captured: keyOf({ onCanPlayCapture: true }) + } + }, + canPlayThrough: { + phasedRegistrationNames: { + bubbled: keyOf({ onCanPlayThrough: true }), + captured: keyOf({ onCanPlayThroughCapture: true }) + } + }, + click: { + phasedRegistrationNames: { + bubbled: keyOf({ onClick: true }), + captured: keyOf({ onClickCapture: true }) + } + }, + contextMenu: { + phasedRegistrationNames: { + bubbled: keyOf({ onContextMenu: true }), + captured: keyOf({ onContextMenuCapture: true }) + } + }, + copy: { + phasedRegistrationNames: { + bubbled: keyOf({ onCopy: true }), + captured: keyOf({ onCopyCapture: true }) + } + }, + cut: { + phasedRegistrationNames: { + bubbled: keyOf({ onCut: true }), + captured: keyOf({ onCutCapture: true }) + } + }, + doubleClick: { + phasedRegistrationNames: { + bubbled: keyOf({ onDoubleClick: true }), + captured: keyOf({ onDoubleClickCapture: true }) + } + }, + drag: { + phasedRegistrationNames: { + bubbled: keyOf({ onDrag: true }), + captured: keyOf({ onDragCapture: true }) + } + }, + dragEnd: { + phasedRegistrationNames: { + bubbled: keyOf({ onDragEnd: true }), + captured: keyOf({ onDragEndCapture: true }) + } + }, + dragEnter: { + phasedRegistrationNames: { + bubbled: keyOf({ onDragEnter: true }), + captured: keyOf({ onDragEnterCapture: true }) + } + }, + dragExit: { + phasedRegistrationNames: { + bubbled: keyOf({ onDragExit: true }), + captured: keyOf({ onDragExitCapture: true }) + } + }, + dragLeave: { + phasedRegistrationNames: { + bubbled: keyOf({ onDragLeave: true }), + captured: keyOf({ onDragLeaveCapture: true }) + } + }, + dragOver: { + phasedRegistrationNames: { + bubbled: keyOf({ onDragOver: true }), + captured: keyOf({ onDragOverCapture: true }) + } + }, + dragStart: { + phasedRegistrationNames: { + bubbled: keyOf({ onDragStart: true }), + captured: keyOf({ onDragStartCapture: true }) + } + }, + drop: { + phasedRegistrationNames: { + bubbled: keyOf({ onDrop: true }), + captured: keyOf({ onDropCapture: true }) + } + }, + durationChange: { + phasedRegistrationNames: { + bubbled: keyOf({ onDurationChange: true }), + captured: keyOf({ onDurationChangeCapture: true }) + } + }, + emptied: { + phasedRegistrationNames: { + bubbled: keyOf({ onEmptied: true }), + captured: keyOf({ onEmptiedCapture: true }) + } + }, + encrypted: { + phasedRegistrationNames: { + bubbled: keyOf({ onEncrypted: true }), + captured: keyOf({ onEncryptedCapture: true }) + } + }, + ended: { + phasedRegistrationNames: { + bubbled: keyOf({ onEnded: true }), + captured: keyOf({ onEndedCapture: true }) + } + }, + error: { + phasedRegistrationNames: { + bubbled: keyOf({ onError: true }), + captured: keyOf({ onErrorCapture: true }) + } + }, + focus: { + phasedRegistrationNames: { + bubbled: keyOf({ onFocus: true }), + captured: keyOf({ onFocusCapture: true }) + } + }, + input: { + phasedRegistrationNames: { + bubbled: keyOf({ onInput: true }), + captured: keyOf({ onInputCapture: true }) + } + }, + keyDown: { + phasedRegistrationNames: { + bubbled: keyOf({ onKeyDown: true }), + captured: keyOf({ onKeyDownCapture: true }) + } + }, + keyPress: { + phasedRegistrationNames: { + bubbled: keyOf({ onKeyPress: true }), + captured: keyOf({ onKeyPressCapture: true }) + } + }, + keyUp: { + phasedRegistrationNames: { + bubbled: keyOf({ onKeyUp: true }), + captured: keyOf({ onKeyUpCapture: true }) + } + }, + load: { + phasedRegistrationNames: { + bubbled: keyOf({ onLoad: true }), + captured: keyOf({ onLoadCapture: true }) + } + }, + loadedData: { + phasedRegistrationNames: { + bubbled: keyOf({ onLoadedData: true }), + captured: keyOf({ onLoadedDataCapture: true }) + } + }, + loadedMetadata: { + phasedRegistrationNames: { + bubbled: keyOf({ onLoadedMetadata: true }), + captured: keyOf({ onLoadedMetadataCapture: true }) + } + }, + loadStart: { + phasedRegistrationNames: { + bubbled: keyOf({ onLoadStart: true }), + captured: keyOf({ onLoadStartCapture: true }) + } + }, + // Note: We do not allow listening to mouseOver events. Instead, use the + // onMouseEnter/onMouseLeave created by `EnterLeaveEventPlugin`. + mouseDown: { + phasedRegistrationNames: { + bubbled: keyOf({ onMouseDown: true }), + captured: keyOf({ onMouseDownCapture: true }) + } + }, + mouseMove: { + phasedRegistrationNames: { + bubbled: keyOf({ onMouseMove: true }), + captured: keyOf({ onMouseMoveCapture: true }) + } + }, + mouseOut: { + phasedRegistrationNames: { + bubbled: keyOf({ onMouseOut: true }), + captured: keyOf({ onMouseOutCapture: true }) + } + }, + mouseOver: { + phasedRegistrationNames: { + bubbled: keyOf({ onMouseOver: true }), + captured: keyOf({ onMouseOverCapture: true }) + } + }, + mouseUp: { + phasedRegistrationNames: { + bubbled: keyOf({ onMouseUp: true }), + captured: keyOf({ onMouseUpCapture: true }) + } + }, + paste: { + phasedRegistrationNames: { + bubbled: keyOf({ onPaste: true }), + captured: keyOf({ onPasteCapture: true }) + } + }, + pause: { + phasedRegistrationNames: { + bubbled: keyOf({ onPause: true }), + captured: keyOf({ onPauseCapture: true }) + } + }, + play: { + phasedRegistrationNames: { + bubbled: keyOf({ onPlay: true }), + captured: keyOf({ onPlayCapture: true }) + } + }, + playing: { + phasedRegistrationNames: { + bubbled: keyOf({ onPlaying: true }), + captured: keyOf({ onPlayingCapture: true }) + } + }, + progress: { + phasedRegistrationNames: { + bubbled: keyOf({ onProgress: true }), + captured: keyOf({ onProgressCapture: true }) + } + }, + rateChange: { + phasedRegistrationNames: { + bubbled: keyOf({ onRateChange: true }), + captured: keyOf({ onRateChangeCapture: true }) + } + }, + reset: { + phasedRegistrationNames: { + bubbled: keyOf({ onReset: true }), + captured: keyOf({ onResetCapture: true }) + } + }, + scroll: { + phasedRegistrationNames: { + bubbled: keyOf({ onScroll: true }), + captured: keyOf({ onScrollCapture: true }) + } + }, + seeked: { + phasedRegistrationNames: { + bubbled: keyOf({ onSeeked: true }), + captured: keyOf({ onSeekedCapture: true }) + } + }, + seeking: { + phasedRegistrationNames: { + bubbled: keyOf({ onSeeking: true }), + captured: keyOf({ onSeekingCapture: true }) + } + }, + stalled: { + phasedRegistrationNames: { + bubbled: keyOf({ onStalled: true }), + captured: keyOf({ onStalledCapture: true }) + } + }, + submit: { + phasedRegistrationNames: { + bubbled: keyOf({ onSubmit: true }), + captured: keyOf({ onSubmitCapture: true }) + } + }, + suspend: { + phasedRegistrationNames: { + bubbled: keyOf({ onSuspend: true }), + captured: keyOf({ onSuspendCapture: true }) + } + }, + timeUpdate: { + phasedRegistrationNames: { + bubbled: keyOf({ onTimeUpdate: true }), + captured: keyOf({ onTimeUpdateCapture: true }) + } + }, + touchCancel: { + phasedRegistrationNames: { + bubbled: keyOf({ onTouchCancel: true }), + captured: keyOf({ onTouchCancelCapture: true }) + } + }, + touchEnd: { + phasedRegistrationNames: { + bubbled: keyOf({ onTouchEnd: true }), + captured: keyOf({ onTouchEndCapture: true }) + } + }, + touchMove: { + phasedRegistrationNames: { + bubbled: keyOf({ onTouchMove: true }), + captured: keyOf({ onTouchMoveCapture: true }) + } + }, + touchStart: { + phasedRegistrationNames: { + bubbled: keyOf({ onTouchStart: true }), + captured: keyOf({ onTouchStartCapture: true }) + } + }, + volumeChange: { + phasedRegistrationNames: { + bubbled: keyOf({ onVolumeChange: true }), + captured: keyOf({ onVolumeChangeCapture: true }) + } + }, + waiting: { + phasedRegistrationNames: { + bubbled: keyOf({ onWaiting: true }), + captured: keyOf({ onWaitingCapture: true }) + } + }, + wheel: { + phasedRegistrationNames: { + bubbled: keyOf({ onWheel: true }), + captured: keyOf({ onWheelCapture: true }) + } + } +}; + +var topLevelEventsToDispatchConfig = { + topAbort: eventTypes.abort, + topBlur: eventTypes.blur, + topCanPlay: eventTypes.canPlay, + topCanPlayThrough: eventTypes.canPlayThrough, + topClick: eventTypes.click, + topContextMenu: eventTypes.contextMenu, + topCopy: eventTypes.copy, + topCut: eventTypes.cut, + topDoubleClick: eventTypes.doubleClick, + topDrag: eventTypes.drag, + topDragEnd: eventTypes.dragEnd, + topDragEnter: eventTypes.dragEnter, + topDragExit: eventTypes.dragExit, + topDragLeave: eventTypes.dragLeave, + topDragOver: eventTypes.dragOver, + topDragStart: eventTypes.dragStart, + topDrop: eventTypes.drop, + topDurationChange: eventTypes.durationChange, + topEmptied: eventTypes.emptied, + topEncrypted: eventTypes.encrypted, + topEnded: eventTypes.ended, + topError: eventTypes.error, + topFocus: eventTypes.focus, + topInput: eventTypes.input, + topKeyDown: eventTypes.keyDown, + topKeyPress: eventTypes.keyPress, + topKeyUp: eventTypes.keyUp, + topLoad: eventTypes.load, + topLoadedData: eventTypes.loadedData, + topLoadedMetadata: eventTypes.loadedMetadata, + topLoadStart: eventTypes.loadStart, + topMouseDown: eventTypes.mouseDown, + topMouseMove: eventTypes.mouseMove, + topMouseOut: eventTypes.mouseOut, + topMouseOver: eventTypes.mouseOver, + topMouseUp: eventTypes.mouseUp, + topPaste: eventTypes.paste, + topPause: eventTypes.pause, + topPlay: eventTypes.play, + topPlaying: eventTypes.playing, + topProgress: eventTypes.progress, + topRateChange: eventTypes.rateChange, + topReset: eventTypes.reset, + topScroll: eventTypes.scroll, + topSeeked: eventTypes.seeked, + topSeeking: eventTypes.seeking, + topStalled: eventTypes.stalled, + topSubmit: eventTypes.submit, + topSuspend: eventTypes.suspend, + topTimeUpdate: eventTypes.timeUpdate, + topTouchCancel: eventTypes.touchCancel, + topTouchEnd: eventTypes.touchEnd, + topTouchMove: eventTypes.touchMove, + topTouchStart: eventTypes.touchStart, + topVolumeChange: eventTypes.volumeChange, + topWaiting: eventTypes.waiting, + topWheel: eventTypes.wheel +}; + +for (var type in topLevelEventsToDispatchConfig) { + topLevelEventsToDispatchConfig[type].dependencies = [type]; +} + +var ON_CLICK_KEY = keyOf({ onClick: null }); +var onClickListeners = {}; + +var SimpleEventPlugin = { + + eventTypes: eventTypes, + + /** + * @param {string} topLevelType Record from `EventConstants`. + * @param {DOMEventTarget} topLevelTarget The listening component root node. + * @param {string} topLevelTargetID ID of `topLevelTarget`. + * @param {object} nativeEvent Native browser event. + * @return {*} An accumulation of synthetic events. + * @see {EventPluginHub.extractEvents} + */ + extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) { + var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType]; + if (!dispatchConfig) { + return null; + } + var EventConstructor; + switch (topLevelType) { + case topLevelTypes.topAbort: + case topLevelTypes.topCanPlay: + case topLevelTypes.topCanPlayThrough: + case topLevelTypes.topDurationChange: + case topLevelTypes.topEmptied: + case topLevelTypes.topEncrypted: + case topLevelTypes.topEnded: + case topLevelTypes.topError: + case topLevelTypes.topInput: + case topLevelTypes.topLoad: + case topLevelTypes.topLoadedData: + case topLevelTypes.topLoadedMetadata: + case topLevelTypes.topLoadStart: + case topLevelTypes.topPause: + case topLevelTypes.topPlay: + case topLevelTypes.topPlaying: + case topLevelTypes.topProgress: + case topLevelTypes.topRateChange: + case topLevelTypes.topReset: + case topLevelTypes.topSeeked: + case topLevelTypes.topSeeking: + case topLevelTypes.topStalled: + case topLevelTypes.topSubmit: + case topLevelTypes.topSuspend: + case topLevelTypes.topTimeUpdate: + case topLevelTypes.topVolumeChange: + case topLevelTypes.topWaiting: + // HTML Events + // @see http://www.w3.org/TR/html5/index.html#events-0 + EventConstructor = SyntheticEvent; + break; + case topLevelTypes.topKeyPress: + // FireFox creates a keypress event for function keys too. This removes + // the unwanted keypress events. Enter is however both printable and + // non-printable. One would expect Tab to be as well (but it isn't). + if (getEventCharCode(nativeEvent) === 0) { + return null; + } + /* falls through */ + case topLevelTypes.topKeyDown: + case topLevelTypes.topKeyUp: + EventConstructor = SyntheticKeyboardEvent; + break; + case topLevelTypes.topBlur: + case topLevelTypes.topFocus: + EventConstructor = SyntheticFocusEvent; + break; + case topLevelTypes.topClick: + // Firefox creates a click event on right mouse clicks. This removes the + // unwanted click events. + if (nativeEvent.button === 2) { + return null; + } + /* falls through */ + case topLevelTypes.topContextMenu: + case topLevelTypes.topDoubleClick: + case topLevelTypes.topMouseDown: + case topLevelTypes.topMouseMove: + case topLevelTypes.topMouseOut: + case topLevelTypes.topMouseOver: + case topLevelTypes.topMouseUp: + EventConstructor = SyntheticMouseEvent; + break; + case topLevelTypes.topDrag: + case topLevelTypes.topDragEnd: + case topLevelTypes.topDragEnter: + case topLevelTypes.topDragExit: + case topLevelTypes.topDragLeave: + case topLevelTypes.topDragOver: + case topLevelTypes.topDragStart: + case topLevelTypes.topDrop: + EventConstructor = SyntheticDragEvent; + break; + case topLevelTypes.topTouchCancel: + case topLevelTypes.topTouchEnd: + case topLevelTypes.topTouchMove: + case topLevelTypes.topTouchStart: + EventConstructor = SyntheticTouchEvent; + break; + case topLevelTypes.topScroll: + EventConstructor = SyntheticUIEvent; + break; + case topLevelTypes.topWheel: + EventConstructor = SyntheticWheelEvent; + break; + case topLevelTypes.topCopy: + case topLevelTypes.topCut: + case topLevelTypes.topPaste: + EventConstructor = SyntheticClipboardEvent; + break; + } + !EventConstructor ? "production" !== 'production' ? invariant(false, 'SimpleEventPlugin: Unhandled event type, `%s`.', topLevelType) : invariant(false) : undefined; + var event = EventConstructor.getPooled(dispatchConfig, topLevelTargetID, nativeEvent, nativeEventTarget); + EventPropagators.accumulateTwoPhaseDispatches(event); + return event; + }, + + didPutListener: function (id, registrationName, listener) { + // Mobile Safari does not fire properly bubble click events on + // non-interactive elements, which means delegated click listeners do not + // fire. The workaround for this bug involves attaching an empty click + // listener on the target node. + if (registrationName === ON_CLICK_KEY) { + var node = ReactMount.getNode(id); + if (!onClickListeners[id]) { + onClickListeners[id] = EventListener.listen(node, 'click', emptyFunction); + } + } + }, + + willDeleteListener: function (id, registrationName) { + if (registrationName === ON_CLICK_KEY) { + onClickListeners[id].remove(); + delete onClickListeners[id]; + } + } + +}; + +module.exports = SimpleEventPlugin; +},{"102":102,"104":104,"105":105,"106":106,"108":108,"109":109,"110":110,"111":111,"112":112,"125":125,"146":146,"15":15,"153":153,"161":161,"166":166,"19":19,"72":72}],102:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule SyntheticClipboardEvent + * @typechecks static-only + */ + +'use strict'; + +var SyntheticEvent = _dereq_(105); + +/** + * @interface Event + * @see http://www.w3.org/TR/clipboard-apis/ + */ +var ClipboardEventInterface = { + clipboardData: function (event) { + return 'clipboardData' in event ? event.clipboardData : window.clipboardData; + } +}; + +/** + * @param {object} dispatchConfig Configuration used to dispatch this event. + * @param {string} dispatchMarker Marker identifying the event target. + * @param {object} nativeEvent Native browser event. + * @extends {SyntheticUIEvent} + */ +function SyntheticClipboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { + SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); +} + +SyntheticEvent.augmentClass(SyntheticClipboardEvent, ClipboardEventInterface); + +module.exports = SyntheticClipboardEvent; +},{"105":105}],103:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule SyntheticCompositionEvent + * @typechecks static-only + */ + +'use strict'; + +var SyntheticEvent = _dereq_(105); + +/** + * @interface Event + * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents + */ +var CompositionEventInterface = { + data: null +}; + +/** + * @param {object} dispatchConfig Configuration used to dispatch this event. + * @param {string} dispatchMarker Marker identifying the event target. + * @param {object} nativeEvent Native browser event. + * @extends {SyntheticUIEvent} + */ +function SyntheticCompositionEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { + SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); +} + +SyntheticEvent.augmentClass(SyntheticCompositionEvent, CompositionEventInterface); + +module.exports = SyntheticCompositionEvent; +},{"105":105}],104:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule SyntheticDragEvent + * @typechecks static-only + */ + +'use strict'; + +var SyntheticMouseEvent = _dereq_(109); + +/** + * @interface DragEvent + * @see http://www.w3.org/TR/DOM-Level-3-Events/ + */ +var DragEventInterface = { + dataTransfer: null +}; + +/** + * @param {object} dispatchConfig Configuration used to dispatch this event. + * @param {string} dispatchMarker Marker identifying the event target. + * @param {object} nativeEvent Native browser event. + * @extends {SyntheticUIEvent} + */ +function SyntheticDragEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { + SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); +} + +SyntheticMouseEvent.augmentClass(SyntheticDragEvent, DragEventInterface); + +module.exports = SyntheticDragEvent; +},{"109":109}],105:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule SyntheticEvent + * @typechecks static-only + */ + +'use strict'; + +var PooledClass = _dereq_(25); + +var assign = _dereq_(24); +var emptyFunction = _dereq_(153); +var warning = _dereq_(173); + +/** + * @interface Event + * @see http://www.w3.org/TR/DOM-Level-3-Events/ + */ +var EventInterface = { + type: null, + // currentTarget is set when dispatching; no use in copying it here + currentTarget: emptyFunction.thatReturnsNull, + eventPhase: null, + bubbles: null, + cancelable: null, + timeStamp: function (event) { + return event.timeStamp || Date.now(); + }, + defaultPrevented: null, + isTrusted: null +}; + +/** + * Synthetic events are dispatched by event plugins, typically in response to a + * top-level event delegation handler. + * + * These systems should generally use pooling to reduce the frequency of garbage + * collection. The system should check `isPersistent` to determine whether the + * event should be released into the pool after being dispatched. Users that + * need a persisted event should invoke `persist`. + * + * Synthetic events (and subclasses) implement the DOM Level 3 Events API by + * normalizing browser quirks. Subclasses do not necessarily have to implement a + * DOM interface; custom application-specific events can also subclass this. + * + * @param {object} dispatchConfig Configuration used to dispatch this event. + * @param {string} dispatchMarker Marker identifying the event target. + * @param {object} nativeEvent Native browser event. + */ +function SyntheticEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { + this.dispatchConfig = dispatchConfig; + this.dispatchMarker = dispatchMarker; + this.nativeEvent = nativeEvent; + this.target = nativeEventTarget; + this.currentTarget = nativeEventTarget; + + var Interface = this.constructor.Interface; + for (var propName in Interface) { + if (!Interface.hasOwnProperty(propName)) { + continue; + } + var normalize = Interface[propName]; + if (normalize) { + this[propName] = normalize(nativeEvent); + } else { + this[propName] = nativeEvent[propName]; + } + } + + var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false; + if (defaultPrevented) { + this.isDefaultPrevented = emptyFunction.thatReturnsTrue; + } else { + this.isDefaultPrevented = emptyFunction.thatReturnsFalse; + } + this.isPropagationStopped = emptyFunction.thatReturnsFalse; +} + +assign(SyntheticEvent.prototype, { + + preventDefault: function () { + this.defaultPrevented = true; + var event = this.nativeEvent; + if ("production" !== 'production') { + "production" !== 'production' ? warning(event, 'This synthetic event is reused for performance reasons. If you\'re ' + 'seeing this, you\'re calling `preventDefault` on a ' + 'released/nullified synthetic event. This is a no-op. See ' + 'https://fb.me/react-event-pooling for more information.') : undefined; + } + if (!event) { + return; + } + + if (event.preventDefault) { + event.preventDefault(); + } else { + event.returnValue = false; + } + this.isDefaultPrevented = emptyFunction.thatReturnsTrue; + }, + + stopPropagation: function () { + var event = this.nativeEvent; + if ("production" !== 'production') { + "production" !== 'production' ? warning(event, 'This synthetic event is reused for performance reasons. If you\'re ' + 'seeing this, you\'re calling `stopPropagation` on a ' + 'released/nullified synthetic event. This is a no-op. See ' + 'https://fb.me/react-event-pooling for more information.') : undefined; + } + if (!event) { + return; + } + + if (event.stopPropagation) { + event.stopPropagation(); + } else { + event.cancelBubble = true; + } + this.isPropagationStopped = emptyFunction.thatReturnsTrue; + }, + + /** + * We release all dispatched `SyntheticEvent`s after each event loop, adding + * them back into the pool. This allows a way to hold onto a reference that + * won't be added back into the pool. + */ + persist: function () { + this.isPersistent = emptyFunction.thatReturnsTrue; + }, + + /** + * Checks if this event should be released back into the pool. + * + * @return {boolean} True if this should not be released, false otherwise. + */ + isPersistent: emptyFunction.thatReturnsFalse, + + /** + * `PooledClass` looks for `destructor` on each instance it releases. + */ + destructor: function () { + var Interface = this.constructor.Interface; + for (var propName in Interface) { + this[propName] = null; + } + this.dispatchConfig = null; + this.dispatchMarker = null; + this.nativeEvent = null; + } + +}); + +SyntheticEvent.Interface = EventInterface; + +/** + * Helper to reduce boilerplate when creating subclasses. + * + * @param {function} Class + * @param {?object} Interface + */ +SyntheticEvent.augmentClass = function (Class, Interface) { + var Super = this; + + var prototype = Object.create(Super.prototype); + assign(prototype, Class.prototype); + Class.prototype = prototype; + Class.prototype.constructor = Class; + + Class.Interface = assign({}, Super.Interface, Interface); + Class.augmentClass = Super.augmentClass; + + PooledClass.addPoolingTo(Class, PooledClass.fourArgumentPooler); +}; + +PooledClass.addPoolingTo(SyntheticEvent, PooledClass.fourArgumentPooler); + +module.exports = SyntheticEvent; +},{"153":153,"173":173,"24":24,"25":25}],106:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule SyntheticFocusEvent + * @typechecks static-only + */ + +'use strict'; + +var SyntheticUIEvent = _dereq_(111); + +/** + * @interface FocusEvent + * @see http://www.w3.org/TR/DOM-Level-3-Events/ + */ +var FocusEventInterface = { + relatedTarget: null +}; + +/** + * @param {object} dispatchConfig Configuration used to dispatch this event. + * @param {string} dispatchMarker Marker identifying the event target. + * @param {object} nativeEvent Native browser event. + * @extends {SyntheticUIEvent} + */ +function SyntheticFocusEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { + SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); +} + +SyntheticUIEvent.augmentClass(SyntheticFocusEvent, FocusEventInterface); + +module.exports = SyntheticFocusEvent; +},{"111":111}],107:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule SyntheticInputEvent + * @typechecks static-only + */ + +'use strict'; + +var SyntheticEvent = _dereq_(105); + +/** + * @interface Event + * @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105 + * /#events-inputevents + */ +var InputEventInterface = { + data: null +}; + +/** + * @param {object} dispatchConfig Configuration used to dispatch this event. + * @param {string} dispatchMarker Marker identifying the event target. + * @param {object} nativeEvent Native browser event. + * @extends {SyntheticUIEvent} + */ +function SyntheticInputEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { + SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); +} + +SyntheticEvent.augmentClass(SyntheticInputEvent, InputEventInterface); + +module.exports = SyntheticInputEvent; +},{"105":105}],108:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule SyntheticKeyboardEvent + * @typechecks static-only + */ + +'use strict'; + +var SyntheticUIEvent = _dereq_(111); + +var getEventCharCode = _dereq_(125); +var getEventKey = _dereq_(126); +var getEventModifierState = _dereq_(127); + +/** + * @interface KeyboardEvent + * @see http://www.w3.org/TR/DOM-Level-3-Events/ + */ +var KeyboardEventInterface = { + key: getEventKey, + location: null, + ctrlKey: null, + shiftKey: null, + altKey: null, + metaKey: null, + repeat: null, + locale: null, + getModifierState: getEventModifierState, + // Legacy Interface + charCode: function (event) { + // `charCode` is the result of a KeyPress event and represents the value of + // the actual printable character. + + // KeyPress is deprecated, but its replacement is not yet final and not + // implemented in any major browser. Only KeyPress has charCode. + if (event.type === 'keypress') { + return getEventCharCode(event); + } + return 0; + }, + keyCode: function (event) { + // `keyCode` is the result of a KeyDown/Up event and represents the value of + // physical keyboard key. + + // The actual meaning of the value depends on the users' keyboard layout + // which cannot be detected. Assuming that it is a US keyboard layout + // provides a surprisingly accurate mapping for US and European users. + // Due to this, it is left to the user to implement at this time. + if (event.type === 'keydown' || event.type === 'keyup') { + return event.keyCode; + } + return 0; + }, + which: function (event) { + // `which` is an alias for either `keyCode` or `charCode` depending on the + // type of the event. + if (event.type === 'keypress') { + return getEventCharCode(event); + } + if (event.type === 'keydown' || event.type === 'keyup') { + return event.keyCode; + } + return 0; + } +}; + +/** + * @param {object} dispatchConfig Configuration used to dispatch this event. + * @param {string} dispatchMarker Marker identifying the event target. + * @param {object} nativeEvent Native browser event. + * @extends {SyntheticUIEvent} + */ +function SyntheticKeyboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { + SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); +} + +SyntheticUIEvent.augmentClass(SyntheticKeyboardEvent, KeyboardEventInterface); + +module.exports = SyntheticKeyboardEvent; +},{"111":111,"125":125,"126":126,"127":127}],109:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule SyntheticMouseEvent + * @typechecks static-only + */ + +'use strict'; + +var SyntheticUIEvent = _dereq_(111); +var ViewportMetrics = _dereq_(114); + +var getEventModifierState = _dereq_(127); + +/** + * @interface MouseEvent + * @see http://www.w3.org/TR/DOM-Level-3-Events/ + */ +var MouseEventInterface = { + screenX: null, + screenY: null, + clientX: null, + clientY: null, + ctrlKey: null, + shiftKey: null, + altKey: null, + metaKey: null, + getModifierState: getEventModifierState, + button: function (event) { + // Webkit, Firefox, IE9+ + // which: 1 2 3 + // button: 0 1 2 (standard) + var button = event.button; + if ('which' in event) { + return button; + } + // IE<9 + // which: undefined + // button: 0 0 0 + // button: 1 4 2 (onmouseup) + return button === 2 ? 2 : button === 4 ? 1 : 0; + }, + buttons: null, + relatedTarget: function (event) { + return event.relatedTarget || (event.fromElement === event.srcElement ? event.toElement : event.fromElement); + }, + // "Proprietary" Interface. + pageX: function (event) { + return 'pageX' in event ? event.pageX : event.clientX + ViewportMetrics.currentScrollLeft; + }, + pageY: function (event) { + return 'pageY' in event ? event.pageY : event.clientY + ViewportMetrics.currentScrollTop; + } +}; + +/** + * @param {object} dispatchConfig Configuration used to dispatch this event. + * @param {string} dispatchMarker Marker identifying the event target. + * @param {object} nativeEvent Native browser event. + * @extends {SyntheticUIEvent} + */ +function SyntheticMouseEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { + SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); +} + +SyntheticUIEvent.augmentClass(SyntheticMouseEvent, MouseEventInterface); + +module.exports = SyntheticMouseEvent; +},{"111":111,"114":114,"127":127}],110:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule SyntheticTouchEvent + * @typechecks static-only + */ + +'use strict'; + +var SyntheticUIEvent = _dereq_(111); + +var getEventModifierState = _dereq_(127); + +/** + * @interface TouchEvent + * @see http://www.w3.org/TR/touch-events/ + */ +var TouchEventInterface = { + touches: null, + targetTouches: null, + changedTouches: null, + altKey: null, + metaKey: null, + ctrlKey: null, + shiftKey: null, + getModifierState: getEventModifierState +}; + +/** + * @param {object} dispatchConfig Configuration used to dispatch this event. + * @param {string} dispatchMarker Marker identifying the event target. + * @param {object} nativeEvent Native browser event. + * @extends {SyntheticUIEvent} + */ +function SyntheticTouchEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { + SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); +} + +SyntheticUIEvent.augmentClass(SyntheticTouchEvent, TouchEventInterface); + +module.exports = SyntheticTouchEvent; +},{"111":111,"127":127}],111:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule SyntheticUIEvent + * @typechecks static-only + */ + +'use strict'; + +var SyntheticEvent = _dereq_(105); + +var getEventTarget = _dereq_(128); + +/** + * @interface UIEvent + * @see http://www.w3.org/TR/DOM-Level-3-Events/ + */ +var UIEventInterface = { + view: function (event) { + if (event.view) { + return event.view; + } + + var target = getEventTarget(event); + if (target != null && target.window === target) { + // target is a window object + return target; + } + + var doc = target.ownerDocument; + // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. + if (doc) { + return doc.defaultView || doc.parentWindow; + } else { + return window; + } + }, + detail: function (event) { + return event.detail || 0; + } +}; + +/** + * @param {object} dispatchConfig Configuration used to dispatch this event. + * @param {string} dispatchMarker Marker identifying the event target. + * @param {object} nativeEvent Native browser event. + * @extends {SyntheticEvent} + */ +function SyntheticUIEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { + SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); +} + +SyntheticEvent.augmentClass(SyntheticUIEvent, UIEventInterface); + +module.exports = SyntheticUIEvent; +},{"105":105,"128":128}],112:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule SyntheticWheelEvent + * @typechecks static-only + */ + +'use strict'; + +var SyntheticMouseEvent = _dereq_(109); + +/** + * @interface WheelEvent + * @see http://www.w3.org/TR/DOM-Level-3-Events/ + */ +var WheelEventInterface = { + deltaX: function (event) { + return 'deltaX' in event ? event.deltaX : + // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive). + 'wheelDeltaX' in event ? -event.wheelDeltaX : 0; + }, + deltaY: function (event) { + return 'deltaY' in event ? event.deltaY : + // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive). + 'wheelDeltaY' in event ? -event.wheelDeltaY : + // Fallback to `wheelDelta` for IE<9 and normalize (down is positive). + 'wheelDelta' in event ? -event.wheelDelta : 0; + }, + deltaZ: null, + + // Browsers without "deltaMode" is reporting in raw wheel delta where one + // notch on the scroll is always +/- 120, roughly equivalent to pixels. + // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or + // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size. + deltaMode: null +}; + +/** + * @param {object} dispatchConfig Configuration used to dispatch this event. + * @param {string} dispatchMarker Marker identifying the event target. + * @param {object} nativeEvent Native browser event. + * @extends {SyntheticMouseEvent} + */ +function SyntheticWheelEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { + SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); +} + +SyntheticMouseEvent.augmentClass(SyntheticWheelEvent, WheelEventInterface); + +module.exports = SyntheticWheelEvent; +},{"109":109}],113:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule Transaction + */ + +'use strict'; + +var invariant = _dereq_(161); + +/** + * `Transaction` creates a black box that is able to wrap any method such that + * certain invariants are maintained before and after the method is invoked + * (Even if an exception is thrown while invoking the wrapped method). Whoever + * instantiates a transaction can provide enforcers of the invariants at + * creation time. The `Transaction` class itself will supply one additional + * automatic invariant for you - the invariant that any transaction instance + * should not be run while it is already being run. You would typically create a + * single instance of a `Transaction` for reuse multiple times, that potentially + * is used to wrap several different methods. Wrappers are extremely simple - + * they only require implementing two methods. + * + * <pre> + * wrappers (injected at creation time) + * + + + * | | + * +-----------------|--------|--------------+ + * | v | | + * | +---------------+ | | + * | +--| wrapper1 |---|----+ | + * | | +---------------+ v | | + * | | +-------------+ | | + * | | +----| wrapper2 |--------+ | + * | | | +-------------+ | | | + * | | | | | | + * | v v v v | wrapper + * | +---+ +---+ +---------+ +---+ +---+ | invariants + * perform(anyMethod) | | | | | | | | | | | | maintained + * +----------------->|-|---|-|---|-->|anyMethod|---|---|-|---|-|--------> + * | | | | | | | | | | | | + * | | | | | | | | | | | | + * | | | | | | | | | | | | + * | +---+ +---+ +---------+ +---+ +---+ | + * | initialize close | + * +-----------------------------------------+ + * </pre> + * + * Use cases: + * - Preserving the input selection ranges before/after reconciliation. + * Restoring selection even in the event of an unexpected error. + * - Deactivating events while rearranging the DOM, preventing blurs/focuses, + * while guaranteeing that afterwards, the event system is reactivated. + * - Flushing a queue of collected DOM mutations to the main UI thread after a + * reconciliation takes place in a worker thread. + * - Invoking any collected `componentDidUpdate` callbacks after rendering new + * content. + * - (Future use case): Wrapping particular flushes of the `ReactWorker` queue + * to preserve the `scrollTop` (an automatic scroll aware DOM). + * - (Future use case): Layout calculations before and after DOM updates. + * + * Transactional plugin API: + * - A module that has an `initialize` method that returns any precomputation. + * - and a `close` method that accepts the precomputation. `close` is invoked + * when the wrapped process is completed, or has failed. + * + * @param {Array<TransactionalWrapper>} transactionWrapper Wrapper modules + * that implement `initialize` and `close`. + * @return {Transaction} Single transaction for reuse in thread. + * + * @class Transaction + */ +var Mixin = { + /** + * Sets up this instance so that it is prepared for collecting metrics. Does + * so such that this setup method may be used on an instance that is already + * initialized, in a way that does not consume additional memory upon reuse. + * That can be useful if you decide to make your subclass of this mixin a + * "PooledClass". + */ + reinitializeTransaction: function () { + this.transactionWrappers = this.getTransactionWrappers(); + if (this.wrapperInitData) { + this.wrapperInitData.length = 0; + } else { + this.wrapperInitData = []; + } + this._isInTransaction = false; + }, + + _isInTransaction: false, + + /** + * @abstract + * @return {Array<TransactionWrapper>} Array of transaction wrappers. + */ + getTransactionWrappers: null, + + isInTransaction: function () { + return !!this._isInTransaction; + }, + + /** + * Executes the function within a safety window. Use this for the top level + * methods that result in large amounts of computation/mutations that would + * need to be safety checked. The optional arguments helps prevent the need + * to bind in many cases. + * + * @param {function} method Member of scope to call. + * @param {Object} scope Scope to invoke from. + * @param {Object?=} a Argument to pass to the method. + * @param {Object?=} b Argument to pass to the method. + * @param {Object?=} c Argument to pass to the method. + * @param {Object?=} d Argument to pass to the method. + * @param {Object?=} e Argument to pass to the method. + * @param {Object?=} f Argument to pass to the method. + * + * @return {*} Return value from `method`. + */ + perform: function (method, scope, a, b, c, d, e, f) { + !!this.isInTransaction() ? "production" !== 'production' ? invariant(false, 'Transaction.perform(...): Cannot initialize a transaction when there ' + 'is already an outstanding transaction.') : invariant(false) : undefined; + var errorThrown; + var ret; + try { + this._isInTransaction = true; + // Catching errors makes debugging more difficult, so we start with + // errorThrown set to true before setting it to false after calling + // close -- if it's still set to true in the finally block, it means + // one of these calls threw. + errorThrown = true; + this.initializeAll(0); + ret = method.call(scope, a, b, c, d, e, f); + errorThrown = false; + } finally { + try { + if (errorThrown) { + // If `method` throws, prefer to show that stack trace over any thrown + // by invoking `closeAll`. + try { + this.closeAll(0); + } catch (err) {} + } else { + // Since `method` didn't throw, we don't want to silence the exception + // here. + this.closeAll(0); + } + } finally { + this._isInTransaction = false; + } + } + return ret; + }, + + initializeAll: function (startIndex) { + var transactionWrappers = this.transactionWrappers; + for (var i = startIndex; i < transactionWrappers.length; i++) { + var wrapper = transactionWrappers[i]; + try { + // Catching errors makes debugging more difficult, so we start with the + // OBSERVED_ERROR state before overwriting it with the real return value + // of initialize -- if it's still set to OBSERVED_ERROR in the finally + // block, it means wrapper.initialize threw. + this.wrapperInitData[i] = Transaction.OBSERVED_ERROR; + this.wrapperInitData[i] = wrapper.initialize ? wrapper.initialize.call(this) : null; + } finally { + if (this.wrapperInitData[i] === Transaction.OBSERVED_ERROR) { + // The initializer for wrapper i threw an error; initialize the + // remaining wrappers but silence any exceptions from them to ensure + // that the first error is the one to bubble up. + try { + this.initializeAll(i + 1); + } catch (err) {} + } + } + } + }, + + /** + * Invokes each of `this.transactionWrappers.close[i]` functions, passing into + * them the respective return values of `this.transactionWrappers.init[i]` + * (`close`rs that correspond to initializers that failed will not be + * invoked). + */ + closeAll: function (startIndex) { + !this.isInTransaction() ? "production" !== 'production' ? invariant(false, 'Transaction.closeAll(): Cannot close transaction when none are open.') : invariant(false) : undefined; + var transactionWrappers = this.transactionWrappers; + for (var i = startIndex; i < transactionWrappers.length; i++) { + var wrapper = transactionWrappers[i]; + var initData = this.wrapperInitData[i]; + var errorThrown; + try { + // Catching errors makes debugging more difficult, so we start with + // errorThrown set to true before setting it to false after calling + // close -- if it's still set to true in the finally block, it means + // wrapper.close threw. + errorThrown = true; + if (initData !== Transaction.OBSERVED_ERROR && wrapper.close) { + wrapper.close.call(this, initData); + } + errorThrown = false; + } finally { + if (errorThrown) { + // The closer for wrapper i threw an error; close the remaining + // wrappers but silence any exceptions from them to ensure that the + // first error is the one to bubble up. + try { + this.closeAll(i + 1); + } catch (e) {} + } + } + } + this.wrapperInitData.length = 0; + } +}; + +var Transaction = { + + Mixin: Mixin, + + /** + * Token to look for to determine if an error occurred. + */ + OBSERVED_ERROR: {} + +}; + +module.exports = Transaction; +},{"161":161}],114:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ViewportMetrics + */ + +'use strict'; + +var ViewportMetrics = { + + currentScrollLeft: 0, + + currentScrollTop: 0, + + refreshScrollValues: function (scrollPosition) { + ViewportMetrics.currentScrollLeft = scrollPosition.x; + ViewportMetrics.currentScrollTop = scrollPosition.y; + } + +}; + +module.exports = ViewportMetrics; +},{}],115:[function(_dereq_,module,exports){ +/** + * Copyright 2014-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule accumulateInto + */ + +'use strict'; + +var invariant = _dereq_(161); + +/** + * + * Accumulates items that must not be null or undefined into the first one. This + * is used to conserve memory by avoiding array allocations, and thus sacrifices + * API cleanness. Since `current` can be null before being passed in and not + * null after this function, make sure to assign it back to `current`: + * + * `a = accumulateInto(a, b);` + * + * This API should be sparingly used. Try `accumulate` for something cleaner. + * + * @return {*|array<*>} An accumulation of items. + */ + +function accumulateInto(current, next) { + !(next != null) ? "production" !== 'production' ? invariant(false, 'accumulateInto(...): Accumulated items must not be null or undefined.') : invariant(false) : undefined; + if (current == null) { + return next; + } + + // Both are not empty. Warning: Never call x.concat(y) when you are not + // certain that x is an Array (x could be a string with concat method). + var currentIsArray = Array.isArray(current); + var nextIsArray = Array.isArray(next); + + if (currentIsArray && nextIsArray) { + current.push.apply(current, next); + return current; + } + + if (currentIsArray) { + current.push(next); + return current; + } + + if (nextIsArray) { + // A bit too dangerous to mutate `next`. + return [current].concat(next); + } + + return [current, next]; +} + +module.exports = accumulateInto; +},{"161":161}],116:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule adler32 + */ + +'use strict'; + +var MOD = 65521; + +// adler32 is not cryptographically strong, and is only used to sanity check that +// markup generated on the server matches the markup generated on the client. +// This implementation (a modified version of the SheetJS version) has been optimized +// for our use case, at the expense of conforming to the adler32 specification +// for non-ascii inputs. +function adler32(data) { + var a = 1; + var b = 0; + var i = 0; + var l = data.length; + var m = l & ~0x3; + while (i < m) { + for (; i < Math.min(i + 4096, m); i += 4) { + b += (a += data.charCodeAt(i)) + (a += data.charCodeAt(i + 1)) + (a += data.charCodeAt(i + 2)) + (a += data.charCodeAt(i + 3)); + } + a %= MOD; + b %= MOD; + } + for (; i < l; i++) { + b += a += data.charCodeAt(i); + } + a %= MOD; + b %= MOD; + return a | b << 16; +} + +module.exports = adler32; +},{}],117:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule canDefineProperty + */ + +'use strict'; + +var canDefineProperty = false; +if ("production" !== 'production') { + try { + Object.defineProperty({}, 'x', { get: function () {} }); + canDefineProperty = true; + } catch (x) { + // IE will fail on defineProperty + } +} + +module.exports = canDefineProperty; +},{}],118:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @typechecks static-only + * @providesModule cloneWithProps + */ + +'use strict'; + +var ReactElement = _dereq_(57); +var ReactPropTransferer = _dereq_(79); + +var keyOf = _dereq_(166); +var warning = _dereq_(173); + +var CHILDREN_PROP = keyOf({ children: null }); + +var didDeprecatedWarn = false; + +/** + * Sometimes you want to change the props of a child passed to you. Usually + * this is to add a CSS class. + * + * @param {ReactElement} child child element you'd like to clone + * @param {object} props props you'd like to modify. className and style will be + * merged automatically. + * @return {ReactElement} a clone of child with props merged in. + * @deprecated + */ +function cloneWithProps(child, props) { + if ("production" !== 'production') { + "production" !== 'production' ? warning(didDeprecatedWarn, 'cloneWithProps(...) is deprecated. ' + 'Please use React.cloneElement instead.') : undefined; + didDeprecatedWarn = true; + "production" !== 'production' ? warning(!child.ref, 'You are calling cloneWithProps() on a child with a ref. This is ' + 'dangerous because you\'re creating a new child which will not be ' + 'added as a ref to its parent.') : undefined; + } + + var newProps = ReactPropTransferer.mergeProps(props, child.props); + + // Use `child.props.children` if it is provided. + if (!newProps.hasOwnProperty(CHILDREN_PROP) && child.props.hasOwnProperty(CHILDREN_PROP)) { + newProps.children = child.props.children; + } + + // The current API doesn't retain _owner, which is why this + // doesn't use ReactElement.cloneAndReplaceProps. + return ReactElement.createElement(child.type, newProps); +} + +module.exports = cloneWithProps; +},{"166":166,"173":173,"57":57,"79":79}],119:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule dangerousStyleValue + * @typechecks static-only + */ + +'use strict'; + +var CSSProperty = _dereq_(4); + +var isUnitlessNumber = CSSProperty.isUnitlessNumber; + +/** + * Convert a value into the proper css writable value. The style name `name` + * should be logical (no hyphens), as specified + * in `CSSProperty.isUnitlessNumber`. + * + * @param {string} name CSS property name such as `topMargin`. + * @param {*} value CSS property value such as `10px`. + * @return {string} Normalized style value with dimensions applied. + */ +function dangerousStyleValue(name, value) { + // Note that we've removed escapeTextForBrowser() calls here since the + // whole string will be escaped when the attribute is injected into + // the markup. If you provide unsafe user data here they can inject + // arbitrary CSS which may be problematic (I couldn't repro this): + // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet + // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/ + // This is not an XSS hole but instead a potential CSS injection issue + // which has lead to a greater discussion about how we're going to + // trust URLs moving forward. See #2115901 + + var isEmpty = value == null || typeof value === 'boolean' || value === ''; + if (isEmpty) { + return ''; + } + + var isNonNumeric = isNaN(value); + if (isNonNumeric || value === 0 || isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name]) { + return '' + value; // cast to string + } + + if (typeof value === 'string') { + value = value.trim(); + } + return value + 'px'; +} + +module.exports = dangerousStyleValue; +},{"4":4}],120:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule deprecated + */ + +'use strict'; + +var assign = _dereq_(24); +var warning = _dereq_(173); + +/** + * This will log a single deprecation notice per function and forward the call + * on to the new API. + * + * @param {string} fnName The name of the function + * @param {string} newModule The module that fn will exist in + * @param {string} newPackage The module that fn will exist in + * @param {*} ctx The context this forwarded call should run in + * @param {function} fn The function to forward on to + * @return {function} The function that will warn once and then call fn + */ +function deprecated(fnName, newModule, newPackage, ctx, fn) { + var warned = false; + if ("production" !== 'production') { + var newFn = function () { + "production" !== 'production' ? warning(warned, + // Require examples in this string must be split to prevent React's + // build tools from mistaking them for real requires. + // Otherwise the build tools will attempt to build a '%s' module. + 'React.%s is deprecated. Please use %s.%s from require' + '(\'%s\') ' + 'instead.', fnName, newModule, fnName, newPackage) : undefined; + warned = true; + return fn.apply(ctx, arguments); + }; + // We need to make sure all properties of the original fn are copied over. + // In particular, this is needed to support PropTypes + return assign(newFn, fn); + } + + return fn; +} + +module.exports = deprecated; +},{"173":173,"24":24}],121:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule escapeTextContentForBrowser + */ + +'use strict'; + +var ESCAPE_LOOKUP = { + '&': '&', + '>': '>', + '<': '<', + '"': '"', + '\'': ''' +}; + +var ESCAPE_REGEX = /[&><"']/g; + +function escaper(match) { + return ESCAPE_LOOKUP[match]; +} + +/** + * Escapes text to prevent scripting attacks. + * + * @param {*} text Text value to escape. + * @return {string} An escaped string. + */ +function escapeTextContentForBrowser(text) { + return ('' + text).replace(ESCAPE_REGEX, escaper); +} + +module.exports = escapeTextContentForBrowser; +},{}],122:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule findDOMNode + * @typechecks static-only + */ + +'use strict'; + +var ReactCurrentOwner = _dereq_(39); +var ReactInstanceMap = _dereq_(68); +var ReactMount = _dereq_(72); + +var invariant = _dereq_(161); +var warning = _dereq_(173); + +/** + * Returns the DOM node rendered by this element. + * + * @param {ReactComponent|DOMElement} componentOrElement + * @return {?DOMElement} The root node of this element. + */ +function findDOMNode(componentOrElement) { + if ("production" !== 'production') { + var owner = ReactCurrentOwner.current; + if (owner !== null) { + "production" !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing getDOMNode or findDOMNode inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component') : undefined; + owner._warnedAboutRefsInRender = true; + } + } + if (componentOrElement == null) { + return null; + } + if (componentOrElement.nodeType === 1) { + return componentOrElement; + } + if (ReactInstanceMap.has(componentOrElement)) { + return ReactMount.getNodeFromInstance(componentOrElement); + } + !(componentOrElement.render == null || typeof componentOrElement.render !== 'function') ? "production" !== 'production' ? invariant(false, 'findDOMNode was called on an unmounted component.') : invariant(false) : undefined; + !false ? "production" !== 'production' ? invariant(false, 'Element appears to be neither ReactComponent nor DOMNode (keys: %s)', Object.keys(componentOrElement)) : invariant(false) : undefined; +} + +module.exports = findDOMNode; +},{"161":161,"173":173,"39":39,"68":68,"72":72}],123:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule flattenChildren + */ + +'use strict'; + +var traverseAllChildren = _dereq_(142); +var warning = _dereq_(173); + +/** + * @param {function} traverseContext Context passed through traversal. + * @param {?ReactComponent} child React child component. + * @param {!string} name String name of key path to child. + */ +function flattenSingleChildIntoContext(traverseContext, child, name) { + // We found a component instance. + var result = traverseContext; + var keyUnique = result[name] === undefined; + if ("production" !== 'production') { + "production" !== 'production' ? warning(keyUnique, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.', name) : undefined; + } + if (keyUnique && child != null) { + result[name] = child; + } +} + +/** + * Flattens children that are typically specified as `props.children`. Any null + * children will not be included in the resulting object. + * @return {!object} flattened children keyed by name. + */ +function flattenChildren(children) { + if (children == null) { + return children; + } + var result = {}; + traverseAllChildren(children, flattenSingleChildIntoContext, result); + return result; +} + +module.exports = flattenChildren; +},{"142":142,"173":173}],124:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule forEachAccumulated + */ + +'use strict'; + +/** + * @param {array} arr an "accumulation" of items which is either an Array or + * a single item. Useful when paired with the `accumulate` module. This is a + * simple utility that allows us to reason about a collection of items, but + * handling the case when there is exactly one item (and we do not need to + * allocate an array). + */ +var forEachAccumulated = function (arr, cb, scope) { + if (Array.isArray(arr)) { + arr.forEach(cb, scope); + } else if (arr) { + cb.call(scope, arr); + } +}; + +module.exports = forEachAccumulated; +},{}],125:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule getEventCharCode + * @typechecks static-only + */ + +'use strict'; + +/** + * `charCode` represents the actual "character code" and is safe to use with + * `String.fromCharCode`. As such, only keys that correspond to printable + * characters produce a valid `charCode`, the only exception to this is Enter. + * The Tab-key is considered non-printable and does not have a `charCode`, + * presumably because it does not produce a tab-character in browsers. + * + * @param {object} nativeEvent Native browser event. + * @return {number} Normalized `charCode` property. + */ +function getEventCharCode(nativeEvent) { + var charCode; + var keyCode = nativeEvent.keyCode; + + if ('charCode' in nativeEvent) { + charCode = nativeEvent.charCode; + + // FF does not set `charCode` for the Enter-key, check against `keyCode`. + if (charCode === 0 && keyCode === 13) { + charCode = 13; + } + } else { + // IE8 does not implement `charCode`, but `keyCode` has the correct value. + charCode = keyCode; + } + + // Some non-printable keys are reported in `charCode`/`keyCode`, discard them. + // Must not discard the (non-)printable Enter-key. + if (charCode >= 32 || charCode === 13) { + return charCode; + } + + return 0; +} + +module.exports = getEventCharCode; +},{}],126:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule getEventKey + * @typechecks static-only + */ + +'use strict'; + +var getEventCharCode = _dereq_(125); + +/** + * Normalization of deprecated HTML5 `key` values + * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names + */ +var normalizeKey = { + 'Esc': 'Escape', + 'Spacebar': ' ', + 'Left': 'ArrowLeft', + 'Up': 'ArrowUp', + 'Right': 'ArrowRight', + 'Down': 'ArrowDown', + 'Del': 'Delete', + 'Win': 'OS', + 'Menu': 'ContextMenu', + 'Apps': 'ContextMenu', + 'Scroll': 'ScrollLock', + 'MozPrintableKey': 'Unidentified' +}; + +/** + * Translation from legacy `keyCode` to HTML5 `key` + * Only special keys supported, all others depend on keyboard layout or browser + * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names + */ +var translateToKey = { + 8: 'Backspace', + 9: 'Tab', + 12: 'Clear', + 13: 'Enter', + 16: 'Shift', + 17: 'Control', + 18: 'Alt', + 19: 'Pause', + 20: 'CapsLock', + 27: 'Escape', + 32: ' ', + 33: 'PageUp', + 34: 'PageDown', + 35: 'End', + 36: 'Home', + 37: 'ArrowLeft', + 38: 'ArrowUp', + 39: 'ArrowRight', + 40: 'ArrowDown', + 45: 'Insert', + 46: 'Delete', + 112: 'F1', 113: 'F2', 114: 'F3', 115: 'F4', 116: 'F5', 117: 'F6', + 118: 'F7', 119: 'F8', 120: 'F9', 121: 'F10', 122: 'F11', 123: 'F12', + 144: 'NumLock', + 145: 'ScrollLock', + 224: 'Meta' +}; + +/** + * @param {object} nativeEvent Native browser event. + * @return {string} Normalized `key` property. + */ +function getEventKey(nativeEvent) { + if (nativeEvent.key) { + // Normalize inconsistent values reported by browsers due to + // implementations of a working draft specification. + + // FireFox implements `key` but returns `MozPrintableKey` for all + // printable characters (normalized to `Unidentified`), ignore it. + var key = normalizeKey[nativeEvent.key] || nativeEvent.key; + if (key !== 'Unidentified') { + return key; + } + } + + // Browser does not implement `key`, polyfill as much of it as we can. + if (nativeEvent.type === 'keypress') { + var charCode = getEventCharCode(nativeEvent); + + // The enter-key is technically both printable and non-printable and can + // thus be captured by `keypress`, no other non-printable key should. + return charCode === 13 ? 'Enter' : String.fromCharCode(charCode); + } + if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') { + // While user keyboard layout determines the actual meaning of each + // `keyCode` value, almost all function keys have a universal value. + return translateToKey[nativeEvent.keyCode] || 'Unidentified'; + } + return ''; +} + +module.exports = getEventKey; +},{"125":125}],127:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule getEventModifierState + * @typechecks static-only + */ + +'use strict'; + +/** + * Translation from modifier key to the associated property in the event. + * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers + */ + +var modifierKeyToProp = { + 'Alt': 'altKey', + 'Control': 'ctrlKey', + 'Meta': 'metaKey', + 'Shift': 'shiftKey' +}; + +// IE8 does not implement getModifierState so we simply map it to the only +// modifier keys exposed by the event itself, does not support Lock-keys. +// Currently, all major browsers except Chrome seems to support Lock-keys. +function modifierStateGetter(keyArg) { + var syntheticEvent = this; + var nativeEvent = syntheticEvent.nativeEvent; + if (nativeEvent.getModifierState) { + return nativeEvent.getModifierState(keyArg); + } + var keyProp = modifierKeyToProp[keyArg]; + return keyProp ? !!nativeEvent[keyProp] : false; +} + +function getEventModifierState(nativeEvent) { + return modifierStateGetter; +} + +module.exports = getEventModifierState; +},{}],128:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule getEventTarget + * @typechecks static-only + */ + +'use strict'; + +/** + * Gets the target node from a native browser event by accounting for + * inconsistencies in browser DOM APIs. + * + * @param {object} nativeEvent Native browser event. + * @return {DOMEventTarget} Target node. + */ +function getEventTarget(nativeEvent) { + var target = nativeEvent.target || nativeEvent.srcElement || window; + // Safari may fire events on text nodes (Node.TEXT_NODE is 3). + // @see http://www.quirksmode.org/js/events_properties.html + return target.nodeType === 3 ? target.parentNode : target; +} + +module.exports = getEventTarget; +},{}],129:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule getIteratorFn + * @typechecks static-only + */ + +'use strict'; + +/* global Symbol */ +var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; +var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec. + +/** + * Returns the iterator method function contained on the iterable object. + * + * Be sure to invoke the function with the iterable as context: + * + * var iteratorFn = getIteratorFn(myIterable); + * if (iteratorFn) { + * var iterator = iteratorFn.call(myIterable); + * ... + * } + * + * @param {?object} maybeIterable + * @return {?function} + */ +function getIteratorFn(maybeIterable) { + var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); + if (typeof iteratorFn === 'function') { + return iteratorFn; + } +} + +module.exports = getIteratorFn; +},{}],130:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule getNodeForCharacterOffset + */ + +'use strict'; + +/** + * Given any node return the first leaf node without children. + * + * @param {DOMElement|DOMTextNode} node + * @return {DOMElement|DOMTextNode} + */ +function getLeafNode(node) { + while (node && node.firstChild) { + node = node.firstChild; + } + return node; +} + +/** + * Get the next sibling within a container. This will walk up the + * DOM if a node's siblings have been exhausted. + * + * @param {DOMElement|DOMTextNode} node + * @return {?DOMElement|DOMTextNode} + */ +function getSiblingNode(node) { + while (node) { + if (node.nextSibling) { + return node.nextSibling; + } + node = node.parentNode; + } +} + +/** + * Get object describing the nodes which contain characters at offset. + * + * @param {DOMElement|DOMTextNode} root + * @param {number} offset + * @return {?object} + */ +function getNodeForCharacterOffset(root, offset) { + var node = getLeafNode(root); + var nodeStart = 0; + var nodeEnd = 0; + + while (node) { + if (node.nodeType === 3) { + nodeEnd = nodeStart + node.textContent.length; + + if (nodeStart <= offset && nodeEnd >= offset) { + return { + node: node, + offset: offset - nodeStart + }; + } + + nodeStart = nodeEnd; + } + + node = getLeafNode(getSiblingNode(node)); + } +} + +module.exports = getNodeForCharacterOffset; +},{}],131:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule getTextContentAccessor + */ + +'use strict'; + +var ExecutionEnvironment = _dereq_(147); + +var contentKey = null; + +/** + * Gets the key used to access text content on a DOM node. + * + * @return {?string} Key used to access text content. + * @internal + */ +function getTextContentAccessor() { + if (!contentKey && ExecutionEnvironment.canUseDOM) { + // Prefer textContent to innerText because many browsers support both but + // SVG <text> elements don't support innerText even when <div> does. + contentKey = 'textContent' in document.documentElement ? 'textContent' : 'innerText'; + } + return contentKey; +} + +module.exports = getTextContentAccessor; +},{"147":147}],132:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule instantiateReactComponent + * @typechecks static-only + */ + +'use strict'; + +var ReactCompositeComponent = _dereq_(38); +var ReactEmptyComponent = _dereq_(59); +var ReactNativeComponent = _dereq_(75); + +var assign = _dereq_(24); +var invariant = _dereq_(161); +var warning = _dereq_(173); + +// To avoid a cyclic dependency, we create the final class in this module +var ReactCompositeComponentWrapper = function () {}; +assign(ReactCompositeComponentWrapper.prototype, ReactCompositeComponent.Mixin, { + _instantiateReactComponent: instantiateReactComponent +}); + +function getDeclarationErrorAddendum(owner) { + if (owner) { + var name = owner.getName(); + if (name) { + return ' Check the render method of `' + name + '`.'; + } + } + return ''; +} + +/** + * Check if the type reference is a known internal type. I.e. not a user + * provided composite type. + * + * @param {function} type + * @return {boolean} Returns true if this is a valid internal type. + */ +function isInternalComponentType(type) { + return typeof type === 'function' && typeof type.prototype !== 'undefined' && typeof type.prototype.mountComponent === 'function' && typeof type.prototype.receiveComponent === 'function'; +} + +/** + * Given a ReactNode, create an instance that will actually be mounted. + * + * @param {ReactNode} node + * @return {object} A new instance of the element's constructor. + * @protected + */ +function instantiateReactComponent(node) { + var instance; + + if (node === null || node === false) { + instance = new ReactEmptyComponent(instantiateReactComponent); + } else if (typeof node === 'object') { + var element = node; + !(element && (typeof element.type === 'function' || typeof element.type === 'string')) ? "production" !== 'production' ? invariant(false, 'Element type is invalid: expected a string (for built-in components) ' + 'or a class/function (for composite components) but got: %s.%s', element.type == null ? element.type : typeof element.type, getDeclarationErrorAddendum(element._owner)) : invariant(false) : undefined; + + // Special case string values + if (typeof element.type === 'string') { + instance = ReactNativeComponent.createInternalComponent(element); + } else if (isInternalComponentType(element.type)) { + // This is temporarily available for custom components that are not string + // representations. I.e. ART. Once those are updated to use the string + // representation, we can drop this code path. + instance = new element.type(element); + } else { + instance = new ReactCompositeComponentWrapper(); + } + } else if (typeof node === 'string' || typeof node === 'number') { + instance = ReactNativeComponent.createInstanceForText(node); + } else { + !false ? "production" !== 'production' ? invariant(false, 'Encountered invalid React node of type %s', typeof node) : invariant(false) : undefined; + } + + if ("production" !== 'production') { + "production" !== 'production' ? warning(typeof instance.construct === 'function' && typeof instance.mountComponent === 'function' && typeof instance.receiveComponent === 'function' && typeof instance.unmountComponent === 'function', 'Only React Components can be mounted.') : undefined; + } + + // Sets up the instance. This can probably just move into the constructor now. + instance.construct(node); + + // These two fields are used by the DOM and ART diffing algorithms + // respectively. Instead of using expandos on components, we should be + // storing the state needed by the diffing algorithms elsewhere. + instance._mountIndex = 0; + instance._mountImage = null; + + if ("production" !== 'production') { + instance._isOwnerNecessary = false; + instance._warnedAboutRefsInRender = false; + } + + // Internal instances should fully constructed at this point, so they should + // not get any new fields added to them at this point. + if ("production" !== 'production') { + if (Object.preventExtensions) { + Object.preventExtensions(instance); + } + } + + return instance; +} + +module.exports = instantiateReactComponent; +},{"161":161,"173":173,"24":24,"38":38,"59":59,"75":75}],133:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule isEventSupported + */ + +'use strict'; + +var ExecutionEnvironment = _dereq_(147); + +var useHasFeature; +if (ExecutionEnvironment.canUseDOM) { + useHasFeature = document.implementation && document.implementation.hasFeature && + // always returns true in newer browsers as per the standard. + // @see http://dom.spec.whatwg.org/#dom-domimplementation-hasfeature + document.implementation.hasFeature('', '') !== true; +} + +/** + * Checks if an event is supported in the current execution environment. + * + * NOTE: This will not work correctly for non-generic events such as `change`, + * `reset`, `load`, `error`, and `select`. + * + * Borrows from Modernizr. + * + * @param {string} eventNameSuffix Event name, e.g. "click". + * @param {?boolean} capture Check if the capture phase is supported. + * @return {boolean} True if the event is supported. + * @internal + * @license Modernizr 3.0.0pre (Custom Build) | MIT + */ +function isEventSupported(eventNameSuffix, capture) { + if (!ExecutionEnvironment.canUseDOM || capture && !('addEventListener' in document)) { + return false; + } + + var eventName = 'on' + eventNameSuffix; + var isSupported = (eventName in document); + + if (!isSupported) { + var element = document.createElementNS('http://www.w3.org/1999/xhtml', 'div'); + element.setAttribute(eventName, 'return;'); + isSupported = typeof element[eventName] === 'function'; + } + + if (!isSupported && useHasFeature && eventNameSuffix === 'wheel') { + // This is the only way to test support for the `wheel` event in IE9+. + isSupported = document.implementation.hasFeature('Events.wheel', '3.0'); + } + + return isSupported; +} + +module.exports = isEventSupported; +},{"147":147}],134:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule isTextInputElement + */ + +'use strict'; + +/** + * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary + */ +var supportedInputTypes = { + 'color': true, + 'date': true, + 'datetime': true, + 'datetime-local': true, + 'email': true, + 'month': true, + 'number': true, + 'password': true, + 'range': true, + 'search': true, + 'tel': true, + 'text': true, + 'time': true, + 'url': true, + 'week': true +}; + +function isTextInputElement(elem) { + var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); + return nodeName && (nodeName === 'input' && supportedInputTypes[elem.type] || nodeName === 'textarea'); +} + +module.exports = isTextInputElement; +},{}],135:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule onlyChild + */ +'use strict'; + +var ReactElement = _dereq_(57); + +var invariant = _dereq_(161); + +/** + * Returns the first child in a collection of children and verifies that there + * is only one child in the collection. The current implementation of this + * function assumes that a single child gets passed without a wrapper, but the + * purpose of this helper function is to abstract away the particular structure + * of children. + * + * @param {?object} children Child collection structure. + * @return {ReactComponent} The first and only `ReactComponent` contained in the + * structure. + */ +function onlyChild(children) { + !ReactElement.isValidElement(children) ? "production" !== 'production' ? invariant(false, 'onlyChild must be passed a children with exactly one child.') : invariant(false) : undefined; + return children; +} + +module.exports = onlyChild; +},{"161":161,"57":57}],136:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule quoteAttributeValueForBrowser + */ + +'use strict'; + +var escapeTextContentForBrowser = _dereq_(121); + +/** + * Escapes attribute value to prevent scripting attacks. + * + * @param {*} value Value to escape. + * @return {string} An escaped string. + */ +function quoteAttributeValueForBrowser(value) { + return '"' + escapeTextContentForBrowser(value) + '"'; +} + +module.exports = quoteAttributeValueForBrowser; +},{"121":121}],137:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * +* @providesModule renderSubtreeIntoContainer +*/ + +'use strict'; + +var ReactMount = _dereq_(72); + +module.exports = ReactMount.renderSubtreeIntoContainer; +},{"72":72}],138:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule setInnerHTML + */ + +/* globals MSApp */ + +'use strict'; + +var ExecutionEnvironment = _dereq_(147); + +var WHITESPACE_TEST = /^[ \r\n\t\f]/; +var NONVISIBLE_TEST = /<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/; + +/** + * Set the innerHTML property of a node, ensuring that whitespace is preserved + * even in IE8. + * + * @param {DOMElement} node + * @param {string} html + * @internal + */ +var setInnerHTML = function (node, html) { + node.innerHTML = html; +}; + +// Win8 apps: Allow all html to be inserted +if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) { + setInnerHTML = function (node, html) { + MSApp.execUnsafeLocalFunction(function () { + node.innerHTML = html; + }); + }; +} + +if (ExecutionEnvironment.canUseDOM) { + // IE8: When updating a just created node with innerHTML only leading + // whitespace is removed. When updating an existing node with innerHTML + // whitespace in root TextNodes is also collapsed. + // @see quirksmode.org/bugreports/archives/2004/11/innerhtml_and_t.html + + // Feature detection; only IE8 is known to behave improperly like this. + var testElement = document.createElementNS('http://www.w3.org/1999/xhtml', 'div'); + testElement.innerHTML = ' '; + if (testElement.innerHTML === '') { + setInnerHTML = function (node, html) { + // Magic theory: IE8 supposedly differentiates between added and updated + // nodes when processing innerHTML, innerHTML on updated nodes suffers + // from worse whitespace behavior. Re-adding a node like this triggers + // the initial and more favorable whitespace behavior. + // TODO: What to do on a detached node? + if (node.parentNode) { + node.parentNode.replaceChild(node, node); + } + + // We also implement a workaround for non-visible tags disappearing into + // thin air on IE8, this only happens if there is no visible text + // in-front of the non-visible tags. Piggyback on the whitespace fix + // and simply check if any non-visible tags appear in the source. + if (WHITESPACE_TEST.test(html) || html[0] === '<' && NONVISIBLE_TEST.test(html)) { + // Recover leading whitespace by temporarily prepending any character. + // \uFEFF has the potential advantage of being zero-width/invisible. + // UglifyJS drops U+FEFF chars when parsing, so use String.fromCharCode + // in hopes that this is preserved even if "\uFEFF" is transformed to + // the actual Unicode character (by Babel, for example). + // https://github.com/mishoo/UglifyJS2/blob/v2.4.20/lib/parse.js#L216 + node.innerHTML = String.fromCharCode(0xFEFF) + html; + + // deleteData leaves an empty `TextNode` which offsets the index of all + // children. Definitely want to avoid this. + var textNode = node.firstChild; + if (textNode.data.length === 1) { + node.removeChild(textNode); + } else { + textNode.deleteData(0, 1); + } + } else { + node.innerHTML = html; + } + }; + } +} + +module.exports = setInnerHTML; +},{"147":147}],139:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule setTextContent + */ + +'use strict'; + +var ExecutionEnvironment = _dereq_(147); +var escapeTextContentForBrowser = _dereq_(121); +var setInnerHTML = _dereq_(138); + +/** + * Set the textContent property of a node, ensuring that whitespace is preserved + * even in IE8. innerText is a poor substitute for textContent and, among many + * issues, inserts <br> instead of the literal newline chars. innerHTML behaves + * as it should. + * + * @param {DOMElement} node + * @param {string} text + * @internal + */ +var setTextContent = function (node, text) { + node.textContent = text; +}; + +if (ExecutionEnvironment.canUseDOM) { + if (!('textContent' in document.documentElement)) { + setTextContent = function (node, text) { + setInnerHTML(node, escapeTextContentForBrowser(text)); + }; + } +} + +module.exports = setTextContent; +},{"121":121,"138":138,"147":147}],140:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * +* @providesModule shallowCompare +*/ + +'use strict'; + +var shallowEqual = _dereq_(171); + +/** + * Does a shallow comparison for props and state. + * See ReactComponentWithPureRenderMixin + */ +function shallowCompare(instance, nextProps, nextState) { + return !shallowEqual(instance.props, nextProps) || !shallowEqual(instance.state, nextState); +} + +module.exports = shallowCompare; +},{"171":171}],141:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule shouldUpdateReactComponent + * @typechecks static-only + */ + +'use strict'; + +/** + * Given a `prevElement` and `nextElement`, determines if the existing + * instance should be updated as opposed to being destroyed or replaced by a new + * instance. Both arguments are elements. This ensures that this logic can + * operate on stateless trees without any backing instance. + * + * @param {?object} prevElement + * @param {?object} nextElement + * @return {boolean} True if the existing instance should be updated. + * @protected + */ +function shouldUpdateReactComponent(prevElement, nextElement) { + var prevEmpty = prevElement === null || prevElement === false; + var nextEmpty = nextElement === null || nextElement === false; + if (prevEmpty || nextEmpty) { + return prevEmpty === nextEmpty; + } + + var prevType = typeof prevElement; + var nextType = typeof nextElement; + if (prevType === 'string' || prevType === 'number') { + return nextType === 'string' || nextType === 'number'; + } else { + return nextType === 'object' && prevElement.type === nextElement.type && prevElement.key === nextElement.key; + } + return false; +} + +module.exports = shouldUpdateReactComponent; +},{}],142:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule traverseAllChildren + */ + +'use strict'; + +var ReactCurrentOwner = _dereq_(39); +var ReactElement = _dereq_(57); +var ReactInstanceHandles = _dereq_(67); + +var getIteratorFn = _dereq_(129); +var invariant = _dereq_(161); +var warning = _dereq_(173); + +var SEPARATOR = ReactInstanceHandles.SEPARATOR; +var SUBSEPARATOR = ':'; + +/** + * TODO: Test that a single child and an array with one item have the same key + * pattern. + */ + +var userProvidedKeyEscaperLookup = { + '=': '=0', + '.': '=1', + ':': '=2' +}; + +var userProvidedKeyEscapeRegex = /[=.:]/g; + +var didWarnAboutMaps = false; + +function userProvidedKeyEscaper(match) { + return userProvidedKeyEscaperLookup[match]; +} + +/** + * Generate a key string that identifies a component within a set. + * + * @param {*} component A component that could contain a manual key. + * @param {number} index Index that is used if a manual key is not provided. + * @return {string} + */ +function getComponentKey(component, index) { + if (component && component.key != null) { + // Explicit key + return wrapUserProvidedKey(component.key); + } + // Implicit key determined by the index in the set + return index.toString(36); +} + +/** + * Escape a component key so that it is safe to use in a reactid. + * + * @param {*} text Component key to be escaped. + * @return {string} An escaped string. + */ +function escapeUserProvidedKey(text) { + return ('' + text).replace(userProvidedKeyEscapeRegex, userProvidedKeyEscaper); +} + +/** + * Wrap a `key` value explicitly provided by the user to distinguish it from + * implicitly-generated keys generated by a component's index in its parent. + * + * @param {string} key Value of a user-provided `key` attribute + * @return {string} + */ +function wrapUserProvidedKey(key) { + return '$' + escapeUserProvidedKey(key); +} + +/** + * @param {?*} children Children tree container. + * @param {!string} nameSoFar Name of the key path so far. + * @param {!function} callback Callback to invoke with each child found. + * @param {?*} traverseContext Used to pass information throughout the traversal + * process. + * @return {!number} The number of children in this subtree. + */ +function traverseAllChildrenImpl(children, nameSoFar, callback, traverseContext) { + var type = typeof children; + + if (type === 'undefined' || type === 'boolean') { + // All of the above are perceived as null. + children = null; + } + + if (children === null || type === 'string' || type === 'number' || ReactElement.isValidElement(children)) { + callback(traverseContext, children, + // If it's the only child, treat the name as if it was wrapped in an array + // so that it's consistent if the number of children grows. + nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar); + return 1; + } + + var child; + var nextName; + var subtreeCount = 0; // Count of children found in the current subtree. + var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR; + + if (Array.isArray(children)) { + for (var i = 0; i < children.length; i++) { + child = children[i]; + nextName = nextNamePrefix + getComponentKey(child, i); + subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); + } + } else { + var iteratorFn = getIteratorFn(children); + if (iteratorFn) { + var iterator = iteratorFn.call(children); + var step; + if (iteratorFn !== children.entries) { + var ii = 0; + while (!(step = iterator.next()).done) { + child = step.value; + nextName = nextNamePrefix + getComponentKey(child, ii++); + subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); + } + } else { + if ("production" !== 'production') { + "production" !== 'production' ? warning(didWarnAboutMaps, 'Using Maps as children is not yet fully supported. It is an ' + 'experimental feature that might be removed. Convert it to a ' + 'sequence / iterable of keyed ReactElements instead.') : undefined; + didWarnAboutMaps = true; + } + // Iterator will provide entry [k,v] tuples rather than values. + while (!(step = iterator.next()).done) { + var entry = step.value; + if (entry) { + child = entry[1]; + nextName = nextNamePrefix + wrapUserProvidedKey(entry[0]) + SUBSEPARATOR + getComponentKey(child, 0); + subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); + } + } + } + } else if (type === 'object') { + var addendum = ''; + if ("production" !== 'production') { + addendum = ' If you meant to render a collection of children, use an array ' + 'instead or wrap the object using createFragment(object) from the ' + 'React add-ons.'; + if (children._isReactElement) { + addendum = ' It looks like you\'re using an element created by a different ' + 'version of React. Make sure to use only one copy of React.'; + } + if (ReactCurrentOwner.current) { + var name = ReactCurrentOwner.current.getName(); + if (name) { + addendum += ' Check the render method of `' + name + '`.'; + } + } + } + var childrenString = String(children); + !false ? "production" !== 'production' ? invariant(false, 'Objects are not valid as a React child (found: %s).%s', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : invariant(false) : undefined; + } + } + + return subtreeCount; +} + +/** + * Traverses children that are typically specified as `props.children`, but + * might also be specified through attributes: + * + * - `traverseAllChildren(this.props.children, ...)` + * - `traverseAllChildren(this.props.leftPanelChildren, ...)` + * + * The `traverseContext` is an optional argument that is passed through the + * entire traversal. It can be used to store accumulations or anything else that + * the callback might find relevant. + * + * @param {?*} children Children tree object. + * @param {!function} callback To invoke upon traversing each child. + * @param {?*} traverseContext Context for traversal. + * @return {!number} The number of children in this subtree. + */ +function traverseAllChildren(children, callback, traverseContext) { + if (children == null) { + return 0; + } + + return traverseAllChildrenImpl(children, '', callback, traverseContext); +} + +module.exports = traverseAllChildren; +},{"129":129,"161":161,"173":173,"39":39,"57":57,"67":67}],143:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule update + */ + +/* global hasOwnProperty:true */ + +'use strict'; + +var assign = _dereq_(24); +var keyOf = _dereq_(166); +var invariant = _dereq_(161); +var hasOwnProperty = ({}).hasOwnProperty; + +function shallowCopy(x) { + if (Array.isArray(x)) { + return x.concat(); + } else if (x && typeof x === 'object') { + return assign(new x.constructor(), x); + } else { + return x; + } +} + +var COMMAND_PUSH = keyOf({ $push: null }); +var COMMAND_UNSHIFT = keyOf({ $unshift: null }); +var COMMAND_SPLICE = keyOf({ $splice: null }); +var COMMAND_SET = keyOf({ $set: null }); +var COMMAND_MERGE = keyOf({ $merge: null }); +var COMMAND_APPLY = keyOf({ $apply: null }); + +var ALL_COMMANDS_LIST = [COMMAND_PUSH, COMMAND_UNSHIFT, COMMAND_SPLICE, COMMAND_SET, COMMAND_MERGE, COMMAND_APPLY]; + +var ALL_COMMANDS_SET = {}; + +ALL_COMMANDS_LIST.forEach(function (command) { + ALL_COMMANDS_SET[command] = true; +}); + +function invariantArrayCase(value, spec, command) { + !Array.isArray(value) ? "production" !== 'production' ? invariant(false, 'update(): expected target of %s to be an array; got %s.', command, value) : invariant(false) : undefined; + var specValue = spec[command]; + !Array.isArray(specValue) ? "production" !== 'production' ? invariant(false, 'update(): expected spec of %s to be an array; got %s. ' + 'Did you forget to wrap your parameter in an array?', command, specValue) : invariant(false) : undefined; +} + +function update(value, spec) { + !(typeof spec === 'object') ? "production" !== 'production' ? invariant(false, 'update(): You provided a key path to update() that did not contain one ' + 'of %s. Did you forget to include {%s: ...}?', ALL_COMMANDS_LIST.join(', '), COMMAND_SET) : invariant(false) : undefined; + + if (hasOwnProperty.call(spec, COMMAND_SET)) { + !(Object.keys(spec).length === 1) ? "production" !== 'production' ? invariant(false, 'Cannot have more than one key in an object with %s', COMMAND_SET) : invariant(false) : undefined; + + return spec[COMMAND_SET]; + } + + var nextValue = shallowCopy(value); + + if (hasOwnProperty.call(spec, COMMAND_MERGE)) { + var mergeObj = spec[COMMAND_MERGE]; + !(mergeObj && typeof mergeObj === 'object') ? "production" !== 'production' ? invariant(false, 'update(): %s expects a spec of type \'object\'; got %s', COMMAND_MERGE, mergeObj) : invariant(false) : undefined; + !(nextValue && typeof nextValue === 'object') ? "production" !== 'production' ? invariant(false, 'update(): %s expects a target of type \'object\'; got %s', COMMAND_MERGE, nextValue) : invariant(false) : undefined; + assign(nextValue, spec[COMMAND_MERGE]); + } + + if (hasOwnProperty.call(spec, COMMAND_PUSH)) { + invariantArrayCase(value, spec, COMMAND_PUSH); + spec[COMMAND_PUSH].forEach(function (item) { + nextValue.push(item); + }); + } + + if (hasOwnProperty.call(spec, COMMAND_UNSHIFT)) { + invariantArrayCase(value, spec, COMMAND_UNSHIFT); + spec[COMMAND_UNSHIFT].forEach(function (item) { + nextValue.unshift(item); + }); + } + + if (hasOwnProperty.call(spec, COMMAND_SPLICE)) { + !Array.isArray(value) ? "production" !== 'production' ? invariant(false, 'Expected %s target to be an array; got %s', COMMAND_SPLICE, value) : invariant(false) : undefined; + !Array.isArray(spec[COMMAND_SPLICE]) ? "production" !== 'production' ? invariant(false, 'update(): expected spec of %s to be an array of arrays; got %s. ' + 'Did you forget to wrap your parameters in an array?', COMMAND_SPLICE, spec[COMMAND_SPLICE]) : invariant(false) : undefined; + spec[COMMAND_SPLICE].forEach(function (args) { + !Array.isArray(args) ? "production" !== 'production' ? invariant(false, 'update(): expected spec of %s to be an array of arrays; got %s. ' + 'Did you forget to wrap your parameters in an array?', COMMAND_SPLICE, spec[COMMAND_SPLICE]) : invariant(false) : undefined; + nextValue.splice.apply(nextValue, args); + }); + } + + if (hasOwnProperty.call(spec, COMMAND_APPLY)) { + !(typeof spec[COMMAND_APPLY] === 'function') ? "production" !== 'production' ? invariant(false, 'update(): expected spec of %s to be a function; got %s.', COMMAND_APPLY, spec[COMMAND_APPLY]) : invariant(false) : undefined; + nextValue = spec[COMMAND_APPLY](nextValue); + } + + for (var k in spec) { + if (!(ALL_COMMANDS_SET.hasOwnProperty(k) && ALL_COMMANDS_SET[k])) { + nextValue[k] = update(value[k], spec[k]); + } + } + + return nextValue; +} + +module.exports = update; +},{"161":161,"166":166,"24":24}],144:[function(_dereq_,module,exports){ +/** + * Copyright 2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule validateDOMNesting + */ + +'use strict'; + +var assign = _dereq_(24); +var emptyFunction = _dereq_(153); +var warning = _dereq_(173); + +var validateDOMNesting = emptyFunction; + +if ("production" !== 'production') { + // This validation code was written based on the HTML5 parsing spec: + // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope + // + // Note: this does not catch all invalid nesting, nor does it try to (as it's + // not clear what practical benefit doing so provides); instead, we warn only + // for cases where the parser will give a parse tree differing from what React + // intended. For example, <b><div></div></b> is invalid but we don't warn + // because it still parses correctly; we do warn for other cases like nested + // <p> tags where the beginning of the second element implicitly closes the + // first, causing a confusing mess. + + // https://html.spec.whatwg.org/multipage/syntax.html#special + var specialTags = ['address', 'applet', 'area', 'article', 'aside', 'base', 'basefont', 'bgsound', 'blockquote', 'body', 'br', 'button', 'caption', 'center', 'col', 'colgroup', 'dd', 'details', 'dir', 'div', 'dl', 'dt', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'iframe', 'img', 'input', 'isindex', 'li', 'link', 'listing', 'main', 'marquee', 'menu', 'menuitem', 'meta', 'nav', 'noembed', 'noframes', 'noscript', 'object', 'ol', 'p', 'param', 'plaintext', 'pre', 'script', 'section', 'select', 'source', 'style', 'summary', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul', 'wbr', 'xmp']; + + // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope + var inScopeTags = ['applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', 'template', + + // https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point + // TODO: Distinguish by namespace here -- for <title>, including it here + // errs on the side of fewer warnings + 'foreignObject', 'desc', 'title']; + + // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope + var buttonScopeTags = inScopeTags.concat(['button']); + + // https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags + var impliedEndTags = ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt']; + + var emptyAncestorInfo = { + parentTag: null, + + formTag: null, + aTagInScope: null, + buttonTagInScope: null, + nobrTagInScope: null, + pTagInButtonScope: null, + + listItemTagAutoclosing: null, + dlItemTagAutoclosing: null + }; + + var updatedAncestorInfo = function (oldInfo, tag, instance) { + var ancestorInfo = assign({}, oldInfo || emptyAncestorInfo); + var info = { tag: tag, instance: instance }; + + if (inScopeTags.indexOf(tag) !== -1) { + ancestorInfo.aTagInScope = null; + ancestorInfo.buttonTagInScope = null; + ancestorInfo.nobrTagInScope = null; + } + if (buttonScopeTags.indexOf(tag) !== -1) { + ancestorInfo.pTagInButtonScope = null; + } + + // See rules for 'li', 'dd', 'dt' start tags in + // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody + if (specialTags.indexOf(tag) !== -1 && tag !== 'address' && tag !== 'div' && tag !== 'p') { + ancestorInfo.listItemTagAutoclosing = null; + ancestorInfo.dlItemTagAutoclosing = null; + } + + ancestorInfo.parentTag = info; + + if (tag === 'form') { + ancestorInfo.formTag = info; + } + if (tag === 'a') { + ancestorInfo.aTagInScope = info; + } + if (tag === 'button') { + ancestorInfo.buttonTagInScope = info; + } + if (tag === 'nobr') { + ancestorInfo.nobrTagInScope = info; + } + if (tag === 'p') { + ancestorInfo.pTagInButtonScope = info; + } + if (tag === 'li') { + ancestorInfo.listItemTagAutoclosing = info; + } + if (tag === 'dd' || tag === 'dt') { + ancestorInfo.dlItemTagAutoclosing = info; + } + + return ancestorInfo; + }; + + /** + * Returns whether + */ + var isTagValidWithParent = function (tag, parentTag) { + // First, let's check if we're in an unusual parsing mode... + switch (parentTag) { + // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect + case 'select': + return tag === 'option' || tag === 'optgroup' || tag === '#text'; + case 'optgroup': + return tag === 'option' || tag === '#text'; + // Strictly speaking, seeing an <option> doesn't mean we're in a <select> + // but + case 'option': + return tag === '#text'; + + // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd + // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption + // No special behavior since these rules fall back to "in body" mode for + // all except special table nodes which cause bad parsing behavior anyway. + + // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr + case 'tr': + return tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' || tag === 'template'; + + // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody + case 'tbody': + case 'thead': + case 'tfoot': + return tag === 'tr' || tag === 'style' || tag === 'script' || tag === 'template'; + + // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup + case 'colgroup': + return tag === 'col' || tag === 'template'; + + // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable + case 'table': + return tag === 'caption' || tag === 'colgroup' || tag === 'tbody' || tag === 'tfoot' || tag === 'thead' || tag === 'style' || tag === 'script' || tag === 'template'; + + // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead + case 'head': + return tag === 'base' || tag === 'basefont' || tag === 'bgsound' || tag === 'link' || tag === 'meta' || tag === 'title' || tag === 'noscript' || tag === 'noframes' || tag === 'style' || tag === 'script' || tag === 'template'; + + // https://html.spec.whatwg.org/multipage/semantics.html#the-html-element + case 'html': + return tag === 'head' || tag === 'body'; + } + + // Probably in the "in body" parsing mode, so we outlaw only tag combos + // where the parsing rules cause implicit opens or closes to be added. + // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody + switch (tag) { + case 'h1': + case 'h2': + case 'h3': + case 'h4': + case 'h5': + case 'h6': + return parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' && parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6'; + + case 'rp': + case 'rt': + return impliedEndTags.indexOf(parentTag) === -1; + + case 'caption': + case 'col': + case 'colgroup': + case 'frame': + case 'head': + case 'tbody': + case 'td': + case 'tfoot': + case 'th': + case 'thead': + case 'tr': + // These tags are only valid with a few parents that have special child + // parsing rules -- if we're down here, then none of those matched and + // so we allow it only if we don't know what the parent is, as all other + // cases are invalid. + return parentTag == null; + } + + return true; + }; + + /** + * Returns whether + */ + var findInvalidAncestorForTag = function (tag, ancestorInfo) { + switch (tag) { + case 'address': + case 'article': + case 'aside': + case 'blockquote': + case 'center': + case 'details': + case 'dialog': + case 'dir': + case 'div': + case 'dl': + case 'fieldset': + case 'figcaption': + case 'figure': + case 'footer': + case 'header': + case 'hgroup': + case 'main': + case 'menu': + case 'nav': + case 'ol': + case 'p': + case 'section': + case 'summary': + case 'ul': + + case 'pre': + case 'listing': + + case 'table': + + case 'hr': + + case 'xmp': + + case 'h1': + case 'h2': + case 'h3': + case 'h4': + case 'h5': + case 'h6': + return ancestorInfo.pTagInButtonScope; + + case 'form': + return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope; + + case 'li': + return ancestorInfo.listItemTagAutoclosing; + + case 'dd': + case 'dt': + return ancestorInfo.dlItemTagAutoclosing; + + case 'button': + return ancestorInfo.buttonTagInScope; + + case 'a': + // Spec says something about storing a list of markers, but it sounds + // equivalent to this check. + return ancestorInfo.aTagInScope; + + case 'nobr': + return ancestorInfo.nobrTagInScope; + } + + return null; + }; + + /** + * Given a ReactCompositeComponent instance, return a list of its recursive + * owners, starting at the root and ending with the instance itself. + */ + var findOwnerStack = function (instance) { + if (!instance) { + return []; + } + + var stack = []; + /*eslint-disable space-after-keywords */ + do { + /*eslint-enable space-after-keywords */ + stack.push(instance); + } while (instance = instance._currentElement._owner); + stack.reverse(); + return stack; + }; + + var didWarn = {}; + + validateDOMNesting = function (childTag, childInstance, ancestorInfo) { + ancestorInfo = ancestorInfo || emptyAncestorInfo; + var parentInfo = ancestorInfo.parentTag; + var parentTag = parentInfo && parentInfo.tag; + + var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo; + var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo); + var problematic = invalidParent || invalidAncestor; + + if (problematic) { + var ancestorTag = problematic.tag; + var ancestorInstance = problematic.instance; + + var childOwner = childInstance && childInstance._currentElement._owner; + var ancestorOwner = ancestorInstance && ancestorInstance._currentElement._owner; + + var childOwners = findOwnerStack(childOwner); + var ancestorOwners = findOwnerStack(ancestorOwner); + + var minStackLen = Math.min(childOwners.length, ancestorOwners.length); + var i; + + var deepestCommon = -1; + for (i = 0; i < minStackLen; i++) { + if (childOwners[i] === ancestorOwners[i]) { + deepestCommon = i; + } else { + break; + } + } + + var UNKNOWN = '(unknown)'; + var childOwnerNames = childOwners.slice(deepestCommon + 1).map(function (inst) { + return inst.getName() || UNKNOWN; + }); + var ancestorOwnerNames = ancestorOwners.slice(deepestCommon + 1).map(function (inst) { + return inst.getName() || UNKNOWN; + }); + var ownerInfo = [].concat( + // If the parent and child instances have a common owner ancestor, start + // with that -- otherwise we just start with the parent's owners. + deepestCommon !== -1 ? childOwners[deepestCommon].getName() || UNKNOWN : [], ancestorOwnerNames, ancestorTag, + // If we're warning about an invalid (non-parent) ancestry, add '...' + invalidAncestor ? ['...'] : [], childOwnerNames, childTag).join(' > '); + + var warnKey = !!invalidParent + '|' + childTag + '|' + ancestorTag + '|' + ownerInfo; + if (didWarn[warnKey]) { + return; + } + didWarn[warnKey] = true; + + if (invalidParent) { + var info = ''; + if (ancestorTag === 'table' && childTag === 'tr') { + info += ' Add a <tbody> to your code to match the DOM tree generated by ' + 'the browser.'; + } + "production" !== 'production' ? warning(false, 'validateDOMNesting(...): <%s> cannot appear as a child of <%s>. ' + 'See %s.%s', childTag, ancestorTag, ownerInfo, info) : undefined; + } else { + "production" !== 'production' ? warning(false, 'validateDOMNesting(...): <%s> cannot appear as a descendant of ' + '<%s>. See %s.', childTag, ancestorTag, ownerInfo) : undefined; + } + } + }; + + validateDOMNesting.ancestorInfoContextKey = '__validateDOMNesting_ancestorInfo$' + Math.random().toString(36).slice(2); + + validateDOMNesting.updatedAncestorInfo = updatedAncestorInfo; + + // For testing + validateDOMNesting.isTagValidInContext = function (tag, ancestorInfo) { + ancestorInfo = ancestorInfo || emptyAncestorInfo; + var parentInfo = ancestorInfo.parentTag; + var parentTag = parentInfo && parentInfo.tag; + return isTagValidWithParent(tag, parentTag) && !findInvalidAncestorForTag(tag, ancestorInfo); + }; +} + +module.exports = validateDOMNesting; +},{"153":153,"173":173,"24":24}],145:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule CSSCore + * @typechecks + */ + +'use strict'; + +var invariant = _dereq_(161); + +/** + * The CSSCore module specifies the API (and implements most of the methods) + * that should be used when dealing with the display of elements (via their + * CSS classes and visibility on screen. It is an API focused on mutating the + * display and not reading it as no logical state should be encoded in the + * display of elements. + */ + +var CSSCore = { + + /** + * Adds the class passed in to the element if it doesn't already have it. + * + * @param {DOMElement} element the element to set the class on + * @param {string} className the CSS className + * @return {DOMElement} the element passed in + */ + addClass: function (element, className) { + !!/\s/.test(className) ? "production" !== 'production' ? invariant(false, 'CSSCore.addClass takes only a single class name. "%s" contains ' + 'multiple classes.', className) : invariant(false) : undefined; + + if (className) { + if (element.classList) { + element.classList.add(className); + } else if (!CSSCore.hasClass(element, className)) { + element.className = element.className + ' ' + className; + } + } + return element; + }, + + /** + * Removes the class passed in from the element + * + * @param {DOMElement} element the element to set the class on + * @param {string} className the CSS className + * @return {DOMElement} the element passed in + */ + removeClass: function (element, className) { + !!/\s/.test(className) ? "production" !== 'production' ? invariant(false, 'CSSCore.removeClass takes only a single class name. "%s" contains ' + 'multiple classes.', className) : invariant(false) : undefined; + + if (className) { + if (element.classList) { + element.classList.remove(className); + } else if (CSSCore.hasClass(element, className)) { + element.className = element.className.replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)', 'g'), '$1').replace(/\s+/g, ' ') // multiple spaces to one + .replace(/^\s*|\s*$/g, ''); // trim the ends + } + } + return element; + }, + + /** + * Helper to add or remove a class from an element based on a condition. + * + * @param {DOMElement} element the element to set the class on + * @param {string} className the CSS className + * @param {*} bool condition to whether to add or remove the class + * @return {DOMElement} the element passed in + */ + conditionClass: function (element, className, bool) { + return (bool ? CSSCore.addClass : CSSCore.removeClass)(element, className); + }, + + /** + * Tests whether the element has the class specified. + * + * @param {DOMNode|DOMWindow} element the element to set the class on + * @param {string} className the CSS className + * @return {boolean} true if the element has the class, false if not + */ + hasClass: function (element, className) { + !!/\s/.test(className) ? "production" !== 'production' ? invariant(false, 'CSS.hasClass takes only a single class name.') : invariant(false) : undefined; + if (element.classList) { + return !!className && element.classList.contains(className); + } + return (' ' + element.className + ' ').indexOf(' ' + className + ' ') > -1; + } + +}; + +module.exports = CSSCore; +},{"161":161}],146:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * @providesModule EventListener + * @typechecks + */ + +'use strict'; + +var emptyFunction = _dereq_(153); + +/** + * Upstream version of event listener. Does not take into account specific + * nature of platform. + */ +var EventListener = { + /** + * Listen to DOM events during the bubble phase. + * + * @param {DOMEventTarget} target DOM element to register listener on. + * @param {string} eventType Event type, e.g. 'click' or 'mouseover'. + * @param {function} callback Callback function. + * @return {object} Object with a `remove` method. + */ + listen: function (target, eventType, callback) { + if (target.addEventListener) { + target.addEventListener(eventType, callback, false); + return { + remove: function () { + target.removeEventListener(eventType, callback, false); + } + }; + } else if (target.attachEvent) { + target.attachEvent('on' + eventType, callback); + return { + remove: function () { + target.detachEvent('on' + eventType, callback); + } + }; + } + }, + + /** + * Listen to DOM events during the capture phase. + * + * @param {DOMEventTarget} target DOM element to register listener on. + * @param {string} eventType Event type, e.g. 'click' or 'mouseover'. + * @param {function} callback Callback function. + * @return {object} Object with a `remove` method. + */ + capture: function (target, eventType, callback) { + if (target.addEventListener) { + target.addEventListener(eventType, callback, true); + return { + remove: function () { + target.removeEventListener(eventType, callback, true); + } + }; + } else { + if ("production" !== 'production') { + console.error('Attempted to listen to events during the capture phase on a ' + 'browser that does not support the capture phase. Your application ' + 'will not receive some events.'); + } + return { + remove: emptyFunction + }; + } + }, + + registerDefault: function () {} +}; + +module.exports = EventListener; +},{"153":153}],147:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ExecutionEnvironment + */ + +'use strict'; + +var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement); + +/** + * Simple, lightweight module assisting with the detection and context of + * Worker. Helps avoid circular dependencies and allows code to reason about + * whether or not they are in a Worker, even if they never include the main + * `ReactWorker` dependency. + */ +var ExecutionEnvironment = { + + canUseDOM: canUseDOM, + + canUseWorkers: typeof Worker !== 'undefined', + + canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent), + + canUseViewport: canUseDOM && !!window.screen, + + isInWorker: !canUseDOM // For now, this is true - might change in the future. + +}; + +module.exports = ExecutionEnvironment; +},{}],148:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule camelize + * @typechecks + */ + +"use strict"; + +var _hyphenPattern = /-(.)/g; + +/** + * Camelcases a hyphenated string, for example: + * + * > camelize('background-color') + * < "backgroundColor" + * + * @param {string} string + * @return {string} + */ +function camelize(string) { + return string.replace(_hyphenPattern, function (_, character) { + return character.toUpperCase(); + }); +} + +module.exports = camelize; +},{}],149:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule camelizeStyleName + * @typechecks + */ + +'use strict'; + +var camelize = _dereq_(148); + +var msPattern = /^-ms-/; + +/** + * Camelcases a hyphenated CSS property name, for example: + * + * > camelizeStyleName('background-color') + * < "backgroundColor" + * > camelizeStyleName('-moz-transition') + * < "MozTransition" + * > camelizeStyleName('-ms-transition') + * < "msTransition" + * + * As Andi Smith suggests + * (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix + * is converted to lowercase `ms`. + * + * @param {string} string + * @return {string} + */ +function camelizeStyleName(string) { + return camelize(string.replace(msPattern, 'ms-')); +} + +module.exports = camelizeStyleName; +},{"148":148}],150:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule containsNode + * @typechecks + */ + +'use strict'; + +var isTextNode = _dereq_(163); + +/*eslint-disable no-bitwise */ + +/** + * Checks if a given DOM node contains or is another DOM node. + * + * @param {?DOMNode} outerNode Outer DOM node. + * @param {?DOMNode} innerNode Inner DOM node. + * @return {boolean} True if `outerNode` contains or is `innerNode`. + */ +function containsNode(_x, _x2) { + var _again = true; + + _function: while (_again) { + var outerNode = _x, + innerNode = _x2; + _again = false; + + if (!outerNode || !innerNode) { + return false; + } else if (outerNode === innerNode) { + return true; + } else if (isTextNode(outerNode)) { + return false; + } else if (isTextNode(innerNode)) { + _x = outerNode; + _x2 = innerNode.parentNode; + _again = true; + continue _function; + } else if (outerNode.contains) { + return outerNode.contains(innerNode); + } else if (outerNode.compareDocumentPosition) { + return !!(outerNode.compareDocumentPosition(innerNode) & 16); + } else { + return false; + } + } +} + +module.exports = containsNode; +},{"163":163}],151:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule createArrayFromMixed + * @typechecks + */ + +'use strict'; + +var toArray = _dereq_(172); + +/** + * Perform a heuristic test to determine if an object is "array-like". + * + * A monk asked Joshu, a Zen master, "Has a dog Buddha nature?" + * Joshu replied: "Mu." + * + * This function determines if its argument has "array nature": it returns + * true if the argument is an actual array, an `arguments' object, or an + * HTMLCollection (e.g. node.childNodes or node.getElementsByTagName()). + * + * It will return false for other array-like objects like Filelist. + * + * @param {*} obj + * @return {boolean} + */ +function hasArrayNature(obj) { + return( + // not null/false + !!obj && ( + // arrays are objects, NodeLists are functions in Safari + typeof obj == 'object' || typeof obj == 'function') && + // quacks like an array + 'length' in obj && + // not window + !('setInterval' in obj) && + // no DOM node should be considered an array-like + // a 'select' element has 'length' and 'item' properties on IE8 + typeof obj.nodeType != 'number' && ( + // a real array + Array.isArray(obj) || + // arguments + 'callee' in obj || + // HTMLCollection/NodeList + 'item' in obj) + ); +} + +/** + * Ensure that the argument is an array by wrapping it in an array if it is not. + * Creates a copy of the argument if it is already an array. + * + * This is mostly useful idiomatically: + * + * var createArrayFromMixed = require('createArrayFromMixed'); + * + * function takesOneOrMoreThings(things) { + * things = createArrayFromMixed(things); + * ... + * } + * + * This allows you to treat `things' as an array, but accept scalars in the API. + * + * If you need to convert an array-like object, like `arguments`, into an array + * use toArray instead. + * + * @param {*} obj + * @return {array} + */ +function createArrayFromMixed(obj) { + if (!hasArrayNature(obj)) { + return [obj]; + } else if (Array.isArray(obj)) { + return obj.slice(); + } else { + return toArray(obj); + } +} + +module.exports = createArrayFromMixed; +},{"172":172}],152:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule createNodesFromMarkup + * @typechecks + */ + +/*eslint-disable fb-www/unsafe-html*/ + +'use strict'; + +var ExecutionEnvironment = _dereq_(147); + +var createArrayFromMixed = _dereq_(151); +var getMarkupWrap = _dereq_(157); +var invariant = _dereq_(161); + +/** + * Dummy container used to render all markup. + */ +var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElementNS('http://www.w3.org/1999/xhtml', 'div') : null; + +/** + * Pattern used by `getNodeName`. + */ +var nodeNamePattern = /^\s*<(\w+)/; + +/** + * Extracts the `nodeName` of the first element in a string of markup. + * + * @param {string} markup String of markup. + * @return {?string} Node name of the supplied markup. + */ +function getNodeName(markup) { + var nodeNameMatch = markup.match(nodeNamePattern); + return nodeNameMatch && nodeNameMatch[1].toLowerCase(); +} + +/** + * Creates an array containing the nodes rendered from the supplied markup. The + * optionally supplied `handleScript` function will be invoked once for each + * <script> element that is rendered. If no `handleScript` function is supplied, + * an exception is thrown if any <script> elements are rendered. + * + * @param {string} markup A string of valid HTML markup. + * @param {?function} handleScript Invoked once for each rendered <script>. + * @return {array<DOMElement|DOMTextNode>} An array of rendered nodes. + */ +function createNodesFromMarkup(markup, handleScript) { + var node = dummyNode; + !!!dummyNode ? "production" !== 'production' ? invariant(false, 'createNodesFromMarkup dummy not initialized') : invariant(false) : undefined; + var nodeName = getNodeName(markup); + + var wrap = nodeName && getMarkupWrap(nodeName); + if (wrap) { + node.innerHTML = wrap[1] + markup + wrap[2]; + + var wrapDepth = wrap[0]; + while (wrapDepth--) { + node = node.lastChild; + } + } else { + node.innerHTML = markup; + } + + var scripts = node.getElementsByTagName('script'); + if (scripts.length) { + !handleScript ? "production" !== 'production' ? invariant(false, 'createNodesFromMarkup(...): Unexpected <script> element rendered.') : invariant(false) : undefined; + createArrayFromMixed(scripts).forEach(handleScript); + } + + var nodes = createArrayFromMixed(node.childNodes); + while (node.lastChild) { + node.removeChild(node.lastChild); + } + return nodes; +} + +module.exports = createNodesFromMarkup; + +},{"147":147,"151":151,"157":157,"161":161}],153:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule emptyFunction + */ + +"use strict"; + +function makeEmptyFunction(arg) { + return function () { + return arg; + }; +} + +/** + * This function accepts and discards inputs; it has no side effects. This is + * primarily useful idiomatically for overridable function endpoints which + * always need to be callable, since JS lacks a null-call idiom ala Cocoa. + */ +function emptyFunction() {} + +emptyFunction.thatReturns = makeEmptyFunction; +emptyFunction.thatReturnsFalse = makeEmptyFunction(false); +emptyFunction.thatReturnsTrue = makeEmptyFunction(true); +emptyFunction.thatReturnsNull = makeEmptyFunction(null); +emptyFunction.thatReturnsThis = function () { + return this; +}; +emptyFunction.thatReturnsArgument = function (arg) { + return arg; +}; + +module.exports = emptyFunction; +},{}],154:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule emptyObject + */ + +'use strict'; + +var emptyObject = {}; + +if ("production" !== 'production') { + Object.freeze(emptyObject); +} + +module.exports = emptyObject; +},{}],155:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule focusNode + */ + +'use strict'; + +/** + * @param {DOMElement} node input/textarea to focus + */ +function focusNode(node) { + // IE8 can throw "Can't move focus to the control because it is invisible, + // not enabled, or of a type that does not accept the focus." for all kinds of + // reasons that are too expensive and fragile to test. + try { + node.focus(); + } catch (e) {} +} + +module.exports = focusNode; +},{}],156:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule getActiveElement + * @typechecks + */ + +/* eslint-disable fb-www/typeof-undefined */ + +/** + * Same as document.activeElement but wraps in a try-catch block. In IE it is + * not safe to call document.activeElement if there is nothing focused. + * + * The activeElement will be null only if the document or document body is not + * yet defined. + */ +'use strict'; + +function getActiveElement() /*?DOMElement*/{ + if (typeof document === 'undefined') { + return null; + } + try { + return document.activeElement || document.body; + } catch (e) { + return document.body; + } +} + +module.exports = getActiveElement; +},{}],157:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule getMarkupWrap + */ + +/*eslint-disable fb-www/unsafe-html */ + +'use strict'; + +var ExecutionEnvironment = _dereq_(147); + +var invariant = _dereq_(161); + +/** + * Dummy container used to detect which wraps are necessary. + */ +var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElementNS('http://www.w3.org/1999/xhtml', 'div') : null; + +/** + * Some browsers cannot use `innerHTML` to render certain elements standalone, + * so we wrap them, render the wrapped nodes, then extract the desired node. + * + * In IE8, certain elements cannot render alone, so wrap all elements ('*'). + */ + +var shouldWrap = {}; + +var selectWrap = [1, '<select multiple="true">', '</select>']; +var tableWrap = [1, '<table>', '</table>']; +var trWrap = [3, '<table><tbody><tr>', '</tr></tbody></table>']; + +var svgWrap = [1, '<svg xmlns="http://www.w3.org/2000/svg">', '</svg>']; + +var markupWrap = { + '*': [1, '?<div>', '</div>'], + + 'area': [1, '<map>', '</map>'], + 'col': [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'], + 'legend': [1, '<fieldset>', '</fieldset>'], + 'param': [1, '<object>', '</object>'], + 'tr': [2, '<table><tbody>', '</tbody></table>'], + + 'optgroup': selectWrap, + 'option': selectWrap, + + 'caption': tableWrap, + 'colgroup': tableWrap, + 'tbody': tableWrap, + 'tfoot': tableWrap, + 'thead': tableWrap, + + 'td': trWrap, + 'th': trWrap +}; + +// Initialize the SVG elements since we know they'll always need to be wrapped +// consistently. If they are created inside a <div> they will be initialized in +// the wrong namespace (and will not display). +var svgElements = ['circle', 'clipPath', 'defs', 'ellipse', 'g', 'image', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'text', 'tspan']; +svgElements.forEach(function (nodeName) { + markupWrap[nodeName] = svgWrap; + shouldWrap[nodeName] = true; +}); + +/** + * Gets the markup wrap configuration for the supplied `nodeName`. + * + * NOTE: This lazily detects which wraps are necessary for the current browser. + * + * @param {string} nodeName Lowercase `nodeName`. + * @return {?array} Markup wrap configuration, if applicable. + */ +function getMarkupWrap(nodeName) { + !!!dummyNode ? "production" !== 'production' ? invariant(false, 'Markup wrapping node not initialized') : invariant(false) : undefined; + if (!markupWrap.hasOwnProperty(nodeName)) { + nodeName = '*'; + } + if (!shouldWrap.hasOwnProperty(nodeName)) { + if (nodeName === '*') { + dummyNode.innerHTML = '<link />'; + } else { + dummyNode.innerHTML = '<' + nodeName + '></' + nodeName + '>'; + } + shouldWrap[nodeName] = !dummyNode.firstChild; + } + return shouldWrap[nodeName] ? markupWrap[nodeName] : null; +} + +module.exports = getMarkupWrap; +},{"147":147,"161":161}],158:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule getUnboundedScrollPosition + * @typechecks + */ + +'use strict'; + +/** + * Gets the scroll position of the supplied element or window. + * + * The return values are unbounded, unlike `getScrollPosition`. This means they + * may be negative or exceed the element boundaries (which is possible using + * inertial scrolling). + * + * @param {DOMWindow|DOMElement} scrollable + * @return {object} Map with `x` and `y` keys. + */ +function getUnboundedScrollPosition(scrollable) { + if (scrollable === window) { + return { + x: window.pageXOffset || document.documentElement.scrollLeft, + y: window.pageYOffset || document.documentElement.scrollTop + }; + } + return { + x: scrollable.scrollLeft, + y: scrollable.scrollTop + }; +} + +module.exports = getUnboundedScrollPosition; +},{}],159:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule hyphenate + * @typechecks + */ + +'use strict'; + +var _uppercasePattern = /([A-Z])/g; + +/** + * Hyphenates a camelcased string, for example: + * + * > hyphenate('backgroundColor') + * < "background-color" + * + * For CSS style names, use `hyphenateStyleName` instead which works properly + * with all vendor prefixes, including `ms`. + * + * @param {string} string + * @return {string} + */ +function hyphenate(string) { + return string.replace(_uppercasePattern, '-$1').toLowerCase(); +} + +module.exports = hyphenate; +},{}],160:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule hyphenateStyleName + * @typechecks + */ + +'use strict'; + +var hyphenate = _dereq_(159); + +var msPattern = /^ms-/; + +/** + * Hyphenates a camelcased CSS property name, for example: + * + * > hyphenateStyleName('backgroundColor') + * < "background-color" + * > hyphenateStyleName('MozTransition') + * < "-moz-transition" + * > hyphenateStyleName('msTransition') + * < "-ms-transition" + * + * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix + * is converted to `-ms-`. + * + * @param {string} string + * @return {string} + */ +function hyphenateStyleName(string) { + return hyphenate(string).replace(msPattern, '-ms-'); +} + +module.exports = hyphenateStyleName; +},{"159":159}],161:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule invariant + */ + +'use strict'; + +/** + * Use invariant() to assert state which your program assumes to be true. + * + * Provide sprintf-style format (only %s is supported) and arguments + * to provide information about what broke and what you were + * expecting. + * + * The invariant message will be stripped in production, but the invariant + * will remain to ensure logic does not differ in production. + */ + +function invariant(condition, format, a, b, c, d, e, f) { + if ("production" !== 'production') { + if (format === undefined) { + throw new Error('invariant requires an error message argument'); + } + } + + if (!condition) { + var error; + if (format === undefined) { + error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); + } else { + var args = [a, b, c, d, e, f]; + var argIndex = 0; + error = new Error(format.replace(/%s/g, function () { + return args[argIndex++]; + })); + error.name = 'Invariant Violation'; + } + + error.framesToPop = 1; // we don't care about invariant's own frame + throw error; + } +} + +module.exports = invariant; +},{}],162:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule isNode + * @typechecks + */ + +/** + * @param {*} object The object to check. + * @return {boolean} Whether or not the object is a DOM node. + */ +'use strict'; + +function isNode(object) { + return !!(object && (typeof Node === 'function' ? object instanceof Node : typeof object === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string')); +} + +module.exports = isNode; +},{}],163:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule isTextNode + * @typechecks + */ + +'use strict'; + +var isNode = _dereq_(162); + +/** + * @param {*} object The object to check. + * @return {boolean} Whether or not the object is a DOM text node. + */ +function isTextNode(object) { + return isNode(object) && object.nodeType == 3; +} + +module.exports = isTextNode; +},{"162":162}],164:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule joinClasses + * @typechecks static-only + */ + +'use strict'; + +/** + * Combines multiple className strings into one. + * http://jsperf.com/joinclasses-args-vs-array + * + * @param {...?string} className + * @return {string} + */ +function joinClasses(className /*, ... */) { + if (!className) { + className = ''; + } + var nextClass; + var argLength = arguments.length; + if (argLength > 1) { + for (var ii = 1; ii < argLength; ii++) { + nextClass = arguments[ii]; + if (nextClass) { + className = (className ? className + ' ' : '') + nextClass; + } + } + } + return className; +} + +module.exports = joinClasses; +},{}],165:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule keyMirror + * @typechecks static-only + */ + +'use strict'; + +var invariant = _dereq_(161); + +/** + * Constructs an enumeration with keys equal to their value. + * + * For example: + * + * var COLORS = keyMirror({blue: null, red: null}); + * var myColor = COLORS.blue; + * var isColorValid = !!COLORS[myColor]; + * + * The last line could not be performed if the values of the generated enum were + * not equal to their keys. + * + * Input: {key1: val1, key2: val2} + * Output: {key1: key1, key2: key2} + * + * @param {object} obj + * @return {object} + */ +var keyMirror = function (obj) { + var ret = {}; + var key; + !(obj instanceof Object && !Array.isArray(obj)) ? "production" !== 'production' ? invariant(false, 'keyMirror(...): Argument must be an object.') : invariant(false) : undefined; + for (key in obj) { + if (!obj.hasOwnProperty(key)) { + continue; + } + ret[key] = key; + } + return ret; +}; + +module.exports = keyMirror; +},{"161":161}],166:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule keyOf + */ + +/** + * Allows extraction of a minified key. Let's the build system minify keys + * without losing the ability to dynamically use key strings as values + * themselves. Pass in an object with a single key/val pair and it will return + * you the string key of that single record. Suppose you want to grab the + * value for a key 'className' inside of an object. Key/val minification may + * have aliased that key to be 'xa12'. keyOf({className: null}) will return + * 'xa12' in that case. Resolve keys you want to use once at startup time, then + * reuse those resolutions. + */ +"use strict"; + +var keyOf = function (oneKeyObj) { + var key; + for (key in oneKeyObj) { + if (!oneKeyObj.hasOwnProperty(key)) { + continue; + } + return key; + } + return null; +}; + +module.exports = keyOf; +},{}],167:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule mapObject + */ + +'use strict'; + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +/** + * Executes the provided `callback` once for each enumerable own property in the + * object and constructs a new object from the results. The `callback` is + * invoked with three arguments: + * + * - the property value + * - the property name + * - the object being traversed + * + * Properties that are added after the call to `mapObject` will not be visited + * by `callback`. If the values of existing properties are changed, the value + * passed to `callback` will be the value at the time `mapObject` visits them. + * Properties that are deleted before being visited are not visited. + * + * @grep function objectMap() + * @grep function objMap() + * + * @param {?object} object + * @param {function} callback + * @param {*} context + * @return {?object} + */ +function mapObject(object, callback, context) { + if (!object) { + return null; + } + var result = {}; + for (var name in object) { + if (hasOwnProperty.call(object, name)) { + result[name] = callback.call(context, object[name], name, object); + } + } + return result; +} + +module.exports = mapObject; +},{}],168:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule memoizeStringOnly + * @typechecks static-only + */ + +'use strict'; + +/** + * Memoizes the return value of a function that accepts one string argument. + * + * @param {function} callback + * @return {function} + */ +function memoizeStringOnly(callback) { + var cache = {}; + return function (string) { + if (!cache.hasOwnProperty(string)) { + cache[string] = callback.call(this, string); + } + return cache[string]; + }; +} + +module.exports = memoizeStringOnly; +},{}],169:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule performance + * @typechecks + */ + +'use strict'; + +var ExecutionEnvironment = _dereq_(147); + +var performance; + +if (ExecutionEnvironment.canUseDOM) { + performance = window.performance || window.msPerformance || window.webkitPerformance; +} + +module.exports = performance || {}; +},{"147":147}],170:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule performanceNow + * @typechecks + */ + +'use strict'; + +var performance = _dereq_(169); + +var performanceNow; + +/** + * Detect if we can use `window.performance.now()` and gracefully fallback to + * `Date.now()` if it doesn't exist. We need to support Firefox < 15 for now + * because of Facebook's testing infrastructure. + */ +if (performance.now) { + performanceNow = function () { + return performance.now(); + }; +} else { + performanceNow = function () { + return Date.now(); + }; +} + +module.exports = performanceNow; +},{"169":169}],171:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule shallowEqual + * @typechecks + * + */ + +'use strict'; + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +/** + * Performs equality by iterating through keys on an object and returning false + * when any key has values which are not strictly equal between the arguments. + * Returns true when the values of all keys are strictly equal. + */ +function shallowEqual(objA, objB) { + if (objA === objB) { + return true; + } + + if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) { + return false; + } + + var keysA = Object.keys(objA); + var keysB = Object.keys(objB); + + if (keysA.length !== keysB.length) { + return false; + } + + // Test for A's keys different from B. + var bHasOwnProperty = hasOwnProperty.bind(objB); + for (var i = 0; i < keysA.length; i++) { + if (!bHasOwnProperty(keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) { + return false; + } + } + + return true; +} + +module.exports = shallowEqual; +},{}],172:[function(_dereq_,module,exports){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule toArray + * @typechecks + */ + +'use strict'; + +var invariant = _dereq_(161); + +/** + * Convert array-like objects to arrays. + * + * This API assumes the caller knows the contents of the data type. For less + * well defined inputs use createArrayFromMixed. + * + * @param {object|function|filelist} obj + * @return {array} + */ +function toArray(obj) { + var length = obj.length; + + // Some browse builtin objects can report typeof 'function' (e.g. NodeList in + // old versions of Safari). + !(!Array.isArray(obj) && (typeof obj === 'object' || typeof obj === 'function')) ? "production" !== 'production' ? invariant(false, 'toArray: Array-like object expected') : invariant(false) : undefined; + + !(typeof length === 'number') ? "production" !== 'production' ? invariant(false, 'toArray: Object needs a length property') : invariant(false) : undefined; + + !(length === 0 || length - 1 in obj) ? "production" !== 'production' ? invariant(false, 'toArray: Object should have keys for indices') : invariant(false) : undefined; + + // Old IE doesn't give collections access to hasOwnProperty. Assume inputs + // without method will throw during the slice call and skip straight to the + // fallback. + if (obj.hasOwnProperty) { + try { + return Array.prototype.slice.call(obj); + } catch (e) { + // IE < 9 does not support Array#slice on collections objects + } + } + + // Fall back to copying key by key. This assumes all keys have a value, + // so will not preserve sparsely populated inputs. + var ret = Array(length); + for (var ii = 0; ii < length; ii++) { + ret[ii] = obj[ii]; + } + return ret; +} + +module.exports = toArray; +},{"161":161}],173:[function(_dereq_,module,exports){ +/** + * Copyright 2014-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule warning + */ + +'use strict'; + +var emptyFunction = _dereq_(153); + +/** + * Similar to invariant but only logs a warning if the condition is not met. + * This can be used to log issues in development environments in critical + * paths. Removing the logging code for production environments will keep the + * same logic and follow the same code paths. + */ + +var warning = emptyFunction; + +if ("production" !== 'production') { + warning = function (condition, format) { + for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { + args[_key - 2] = arguments[_key]; + } + + if (format === undefined) { + throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument'); + } + + if (format.indexOf('Failed Composite propType: ') === 0) { + return; // Ignore CompositeComponent proptype check. + } + + if (!condition) { + var argIndex = 0; + var message = 'Warning: ' + format.replace(/%s/g, function () { + return args[argIndex++]; + }); + if (typeof console !== 'undefined') { + console.error(message); + } + try { + // --- Welcome to debugging React --- + // This error was thrown as a convenience so that you can use this stack + // to find the callsite that caused this warning to fire. + throw new Error(message); + } catch (x) {} + } + }; +} + +module.exports = warning; +},{"153":153}]},{},[1])(1) +}); diff --git a/devtools/client/shared/vendor/redux.js b/devtools/client/shared/vendor/redux.js new file mode 100644 index 000000000..fe12ae878 --- /dev/null +++ b/devtools/client/shared/vendor/redux.js @@ -0,0 +1,775 @@ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define([], factory); + else if(typeof exports === 'object') + exports["Redux"] = factory(); + else + root["Redux"] = factory(); +})(this, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; + +/******/ // The require function +/******/ function __webpack_require__(moduleId) { + +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; + +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ exports: {}, +/******/ id: moduleId, +/******/ loaded: false +/******/ }; + +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + +/******/ // Flag the module as loaded +/******/ module.loaded = true; + +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } + + +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; + +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; + +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; + +/******/ // Load entry module and return exports +/******/ return __webpack_require__(0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + exports.__esModule = true; + exports.compose = exports.applyMiddleware = exports.bindActionCreators = exports.combineReducers = exports.createStore = undefined; + + var _createStore = __webpack_require__(2); + + var _createStore2 = _interopRequireDefault(_createStore); + + var _combineReducers = __webpack_require__(7); + + var _combineReducers2 = _interopRequireDefault(_combineReducers); + + var _bindActionCreators = __webpack_require__(6); + + var _bindActionCreators2 = _interopRequireDefault(_bindActionCreators); + + var _applyMiddleware = __webpack_require__(5); + + var _applyMiddleware2 = _interopRequireDefault(_applyMiddleware); + + var _compose = __webpack_require__(1); + + var _compose2 = _interopRequireDefault(_compose); + + var _warning = __webpack_require__(3); + + var _warning2 = _interopRequireDefault(_warning); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + + /* + * This is a dummy function to check if the function name has been altered by minification. + * If the function has been minified and NODE_ENV !== 'production', warn the user. + */ + function isCrushed() {} + + if (("development") !== 'production' && typeof isCrushed.name === 'string' && isCrushed.name !== 'isCrushed') { + (0, _warning2["default"])('You are currently using minified code outside of NODE_ENV === \'production\'. ' + 'This means that you are running a slower development build of Redux. ' + 'You can use loose-envify (https://github.com/zertosh/loose-envify) for browserify ' + 'or DefinePlugin for webpack (http://stackoverflow.com/questions/30030031) ' + 'to ensure you have the correct code for your production build.'); + } + + exports.createStore = _createStore2["default"]; + exports.combineReducers = _combineReducers2["default"]; + exports.bindActionCreators = _bindActionCreators2["default"]; + exports.applyMiddleware = _applyMiddleware2["default"]; + exports.compose = _compose2["default"]; + +/***/ }, +/* 1 */ +/***/ function(module, exports) { + + "use strict"; + + exports.__esModule = true; + exports["default"] = compose; + /** + * Composes single-argument functions from right to left. + * + * @param {...Function} funcs The functions to compose. + * @returns {Function} A function obtained by composing functions from right to + * left. For example, compose(f, g, h) is identical to arg => f(g(h(arg))). + */ + function compose() { + for (var _len = arguments.length, funcs = Array(_len), _key = 0; _key < _len; _key++) { + funcs[_key] = arguments[_key]; + } + + return function () { + if (funcs.length === 0) { + return arguments.length <= 0 ? undefined : arguments[0]; + } + + var last = funcs[funcs.length - 1]; + var rest = funcs.slice(0, -1); + + return rest.reduceRight(function (composed, f) { + return f(composed); + }, last.apply(undefined, arguments)); + }; + } + +/***/ }, +/* 2 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + exports.__esModule = true; + exports.ActionTypes = undefined; + exports["default"] = createStore; + + var _isPlainObject = __webpack_require__(4); + + var _isPlainObject2 = _interopRequireDefault(_isPlainObject); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + + /** + * These are private action types reserved by Redux. + * For any unknown actions, you must return the current state. + * If the current state is undefined, you must return the initial state. + * Do not reference these action types directly in your code. + */ + var ActionTypes = exports.ActionTypes = { + INIT: '@@redux/INIT' + }; + + /** + * Creates a Redux store that holds the state tree. + * The only way to change the data in the store is to call `dispatch()` on it. + * + * There should only be a single store in your app. To specify how different + * parts of the state tree respond to actions, you may combine several reducers + * into a single reducer function by using `combineReducers`. + * + * @param {Function} reducer A function that returns the next state tree, given + * the current state tree and the action to handle. + * + * @param {any} [initialState] The initial state. You may optionally specify it + * to hydrate the state from the server in universal apps, or to restore a + * previously serialized user session. + * If you use `combineReducers` to produce the root reducer function, this must be + * an object with the same shape as `combineReducers` keys. + * + * @param {Function} enhancer The store enhancer. You may optionally specify it + * to enhance the store with third-party capabilities such as middleware, + * time travel, persistence, etc. The only store enhancer that ships with Redux + * is `applyMiddleware()`. + * + * @returns {Store} A Redux store that lets you read the state, dispatch actions + * and subscribe to changes. + */ + function createStore(reducer, initialState, enhancer) { + if (typeof initialState === 'function' && typeof enhancer === 'undefined') { + enhancer = initialState; + initialState = undefined; + } + + if (typeof enhancer !== 'undefined') { + if (typeof enhancer !== 'function') { + throw new Error('Expected the enhancer to be a function.'); + } + + return enhancer(createStore)(reducer, initialState); + } + + if (typeof reducer !== 'function') { + throw new Error('Expected the reducer to be a function.'); + } + + var currentReducer = reducer; + var currentState = initialState; + var currentListeners = []; + var nextListeners = currentListeners; + var isDispatching = false; + + function ensureCanMutateNextListeners() { + if (nextListeners === currentListeners) { + nextListeners = currentListeners.slice(); + } + } + + /** + * Reads the state tree managed by the store. + * + * @returns {any} The current state tree of your application. + */ + function getState() { + return currentState; + } + + /** + * Adds a change listener. It will be called any time an action is dispatched, + * and some part of the state tree may potentially have changed. You may then + * call `getState()` to read the current state tree inside the callback. + * + * You may call `dispatch()` from a change listener, with the following + * caveats: + * + * 1. The subscriptions are snapshotted just before every `dispatch()` call. + * If you subscribe or unsubscribe while the listeners are being invoked, this + * will not have any effect on the `dispatch()` that is currently in progress. + * However, the next `dispatch()` call, whether nested or not, will use a more + * recent snapshot of the subscription list. + * + * 2. The listener should not expect to see all states changes, as the state + * might have been updated multiple times during a nested `dispatch()` before + * the listener is called. It is, however, guaranteed that all subscribers + * registered before the `dispatch()` started will be called with the latest + * state by the time it exits. + * + * @param {Function} listener A callback to be invoked on every dispatch. + * @returns {Function} A function to remove this change listener. + */ + function subscribe(listener) { + if (typeof listener !== 'function') { + throw new Error('Expected listener to be a function.'); + } + + var isSubscribed = true; + + ensureCanMutateNextListeners(); + nextListeners.push(listener); + + return function unsubscribe() { + if (!isSubscribed) { + return; + } + + isSubscribed = false; + + ensureCanMutateNextListeners(); + var index = nextListeners.indexOf(listener); + nextListeners.splice(index, 1); + }; + } + + /** + * Dispatches an action. It is the only way to trigger a state change. + * + * The `reducer` function, used to create the store, will be called with the + * current state tree and the given `action`. Its return value will + * be considered the **next** state of the tree, and the change listeners + * will be notified. + * + * The base implementation only supports plain object actions. If you want to + * dispatch a Promise, an Observable, a thunk, or something else, you need to + * wrap your store creating function into the corresponding middleware. For + * example, see the documentation for the `redux-thunk` package. Even the + * middleware will eventually dispatch plain object actions using this method. + * + * @param {Object} action A plain object representing “what changed”. It is + * a good idea to keep actions serializable so you can record and replay user + * sessions, or use the time travelling `redux-devtools`. An action must have + * a `type` property which may not be `undefined`. It is a good idea to use + * string constants for action types. + * + * @returns {Object} For convenience, the same action object you dispatched. + * + * Note that, if you use a custom middleware, it may wrap `dispatch()` to + * return something else (for example, a Promise you can await). + */ + function dispatch(action) { + if (!(0, _isPlainObject2["default"])(action)) { + throw new Error('Actions must be plain objects. ' + 'Use custom middleware for async actions.'); + } + + if (typeof action.type === 'undefined') { + throw new Error('Actions may not have an undefined "type" property. ' + 'Have you misspelled a constant?'); + } + + if (isDispatching) { + throw new Error('Reducers may not dispatch actions.'); + } + + try { + isDispatching = true; + currentState = currentReducer(currentState, action); + } finally { + isDispatching = false; + } + + var listeners = currentListeners = nextListeners; + for (var i = 0; i < listeners.length; i++) { + listeners[i](); + } + + return action; + } + + /** + * Replaces the reducer currently used by the store to calculate the state. + * + * You might need this if your app implements code splitting and you want to + * load some of the reducers dynamically. You might also need this if you + * implement a hot reloading mechanism for Redux. + * + * @param {Function} nextReducer The reducer for the store to use instead. + * @returns {void} + */ + function replaceReducer(nextReducer) { + if (typeof nextReducer !== 'function') { + throw new Error('Expected the nextReducer to be a function.'); + } + + currentReducer = nextReducer; + dispatch({ type: ActionTypes.INIT }); + } + + // When a store is created, an "INIT" action is dispatched so that every + // reducer returns their initial state. This effectively populates + // the initial state tree. + dispatch({ type: ActionTypes.INIT }); + + return { + dispatch: dispatch, + subscribe: subscribe, + getState: getState, + replaceReducer: replaceReducer + }; + } + +/***/ }, +/* 3 */ +/***/ function(module, exports) { + + 'use strict'; + + exports.__esModule = true; + exports["default"] = warning; + /** + * Prints a warning in the console if it exists. + * + * @param {String} message The warning message. + * @returns {void} + */ + function warning(message) { + /* eslint-disable no-console */ + if (typeof console !== 'undefined' && typeof console.error === 'function') { + console.error(message); + } + /* eslint-enable no-console */ + try { + // This error was thrown as a convenience so that you can use this stack + // to find the callsite that caused this warning to fire. + throw new Error(message); + /* eslint-disable no-empty */ + } catch (e) {} + /* eslint-enable no-empty */ + } + +/***/ }, +/* 4 */ +/***/ function(module, exports, __webpack_require__) { + + var isHostObject = __webpack_require__(8), + isObjectLike = __webpack_require__(9); + + /** `Object#toString` result references. */ + var objectTag = '[object Object]'; + + /** Used for built-in method references. */ + var objectProto = Object.prototype; + + /** Used to resolve the decompiled source of functions. */ + var funcToString = Function.prototype.toString; + + /** Used to infer the `Object` constructor. */ + var objectCtorString = funcToString.call(Object); + + /** + * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) + * of values. + */ + var objectToString = objectProto.toString; + + /** Built-in value references. */ + var getPrototypeOf = Object.getPrototypeOf; + + /** + * Checks if `value` is a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true + */ + function isPlainObject(value) { + if (!isObjectLike(value) || objectToString.call(value) != objectTag || isHostObject(value)) { + return false; + } + var proto = objectProto; + if (typeof value.constructor == 'function') { + proto = getPrototypeOf(value); + } + if (proto === null) { + return true; + } + var Ctor = proto.constructor; + return (typeof Ctor == 'function' && + Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString); + } + + module.exports = isPlainObject; + + +/***/ }, +/* 5 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; + + exports.__esModule = true; + exports["default"] = applyMiddleware; + + var _compose = __webpack_require__(1); + + var _compose2 = _interopRequireDefault(_compose); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + + /** + * Creates a store enhancer that applies middleware to the dispatch method + * of the Redux store. This is handy for a variety of tasks, such as expressing + * asynchronous actions in a concise manner, or logging every action payload. + * + * See `redux-thunk` package as an example of the Redux middleware. + * + * Because middleware is potentially asynchronous, this should be the first + * store enhancer in the composition chain. + * + * Note that each middleware will be given the `dispatch` and `getState` functions + * as named arguments. + * + * @param {...Function} middlewares The middleware chain to be applied. + * @returns {Function} A store enhancer applying the middleware. + */ + function applyMiddleware() { + for (var _len = arguments.length, middlewares = Array(_len), _key = 0; _key < _len; _key++) { + middlewares[_key] = arguments[_key]; + } + + return function (createStore) { + return function (reducer, initialState, enhancer) { + var store = createStore(reducer, initialState, enhancer); + var _dispatch = store.dispatch; + var chain = []; + + var middlewareAPI = { + getState: store.getState, + dispatch: function dispatch(action) { + return _dispatch(action); + } + }; + chain = middlewares.map(function (middleware) { + return middleware(middlewareAPI); + }); + _dispatch = _compose2["default"].apply(undefined, chain)(store.dispatch); + + return _extends({}, store, { + dispatch: _dispatch + }); + }; + }; + } + +/***/ }, +/* 6 */ +/***/ function(module, exports) { + + 'use strict'; + + exports.__esModule = true; + exports["default"] = bindActionCreators; + function bindActionCreator(actionCreator, dispatch) { + return function () { + return dispatch(actionCreator.apply(undefined, arguments)); + }; + } + + /** + * Turns an object whose values are action creators, into an object with the + * same keys, but with every function wrapped into a `dispatch` call so they + * may be invoked directly. This is just a convenience method, as you can call + * `store.dispatch(MyActionCreators.doSomething())` yourself just fine. + * + * For convenience, you can also pass a single function as the first argument, + * and get a function in return. + * + * @param {Function|Object} actionCreators An object whose values are action + * creator functions. One handy way to obtain it is to use ES6 `import * as` + * syntax. You may also pass a single function. + * + * @param {Function} dispatch The `dispatch` function available on your Redux + * store. + * + * @returns {Function|Object} The object mimicking the original object, but with + * every action creator wrapped into the `dispatch` call. If you passed a + * function as `actionCreators`, the return value will also be a single + * function. + */ + function bindActionCreators(actionCreators, dispatch) { + if (typeof actionCreators === 'function') { + return bindActionCreator(actionCreators, dispatch); + } + + if (typeof actionCreators !== 'object' || actionCreators === null) { + throw new Error('bindActionCreators expected an object or a function, instead received ' + (actionCreators === null ? 'null' : typeof actionCreators) + '. ' + 'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?'); + } + + var keys = Object.keys(actionCreators); + var boundActionCreators = {}; + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + var actionCreator = actionCreators[key]; + if (typeof actionCreator === 'function') { + boundActionCreators[key] = bindActionCreator(actionCreator, dispatch); + } + } + return boundActionCreators; + } + +/***/ }, +/* 7 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + exports.__esModule = true; + exports["default"] = combineReducers; + + var _createStore = __webpack_require__(2); + + var _isPlainObject = __webpack_require__(4); + + var _isPlainObject2 = _interopRequireDefault(_isPlainObject); + + var _warning = __webpack_require__(3); + + var _warning2 = _interopRequireDefault(_warning); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + + function getUndefinedStateErrorMessage(key, action) { + var actionType = action && action.type; + var actionName = actionType && '"' + actionType.toString() + '"' || 'an action'; + + return 'Reducer "' + key + '" returned undefined handling ' + actionName + '. ' + 'To ignore an action, you must explicitly return the previous state.'; + } + + function getUnexpectedStateShapeWarningMessage(inputState, reducers, action) { + var reducerKeys = Object.keys(reducers); + var argumentName = action && action.type === _createStore.ActionTypes.INIT ? 'initialState argument passed to createStore' : 'previous state received by the reducer'; + + if (reducerKeys.length === 0) { + return 'Store does not have a valid reducer. Make sure the argument passed ' + 'to combineReducers is an object whose values are reducers.'; + } + + if (!(0, _isPlainObject2["default"])(inputState)) { + return 'The ' + argumentName + ' has unexpected type of "' + {}.toString.call(inputState).match(/\s([a-z|A-Z]+)/)[1] + '". Expected argument to be an object with the following ' + ('keys: "' + reducerKeys.join('", "') + '"'); + } + + var unexpectedKeys = Object.keys(inputState).filter(function (key) { + return !reducers.hasOwnProperty(key); + }); + + if (unexpectedKeys.length > 0) { + return 'Unexpected ' + (unexpectedKeys.length > 1 ? 'keys' : 'key') + ' ' + ('"' + unexpectedKeys.join('", "') + '" found in ' + argumentName + '. ') + 'Expected to find one of the known reducer keys instead: ' + ('"' + reducerKeys.join('", "') + '". Unexpected keys will be ignored.'); + } + } + + function assertReducerSanity(reducers) { + Object.keys(reducers).forEach(function (key) { + var reducer = reducers[key]; + var initialState = reducer(undefined, { type: _createStore.ActionTypes.INIT }); + + if (typeof initialState === 'undefined') { + throw new Error('Reducer "' + key + '" returned undefined during initialization. ' + 'If the state passed to the reducer is undefined, you must ' + 'explicitly return the initial state. The initial state may ' + 'not be undefined.'); + } + + var type = '@@redux/PROBE_UNKNOWN_ACTION_' + Math.random().toString(36).substring(7).split('').join('.'); + if (typeof reducer(undefined, { type: type }) === 'undefined') { + throw new Error('Reducer "' + key + '" returned undefined when probed with a random type. ' + ('Don\'t try to handle ' + _createStore.ActionTypes.INIT + ' or other actions in "redux/*" ') + 'namespace. They are considered private. Instead, you must return the ' + 'current state for any unknown actions, unless it is undefined, ' + 'in which case you must return the initial state, regardless of the ' + 'action type. The initial state may not be undefined.'); + } + }); + } + + /** + * Turns an object whose values are different reducer functions, into a single + * reducer function. It will call every child reducer, and gather their results + * into a single state object, whose keys correspond to the keys of the passed + * reducer functions. + * + * @param {Object} reducers An object whose values correspond to different + * reducer functions that need to be combined into one. One handy way to obtain + * it is to use ES6 `import * as reducers` syntax. The reducers may never return + * undefined for any action. Instead, they should return their initial state + * if the state passed to them was undefined, and the current state for any + * unrecognized action. + * + * @returns {Function} A reducer function that invokes every reducer inside the + * passed object, and builds a state object with the same shape. + */ + function combineReducers(reducers) { + var reducerKeys = Object.keys(reducers); + var finalReducers = {}; + for (var i = 0; i < reducerKeys.length; i++) { + var key = reducerKeys[i]; + if (typeof reducers[key] === 'function') { + finalReducers[key] = reducers[key]; + } + } + var finalReducerKeys = Object.keys(finalReducers); + + var sanityError; + try { + assertReducerSanity(finalReducers); + } catch (e) { + sanityError = e; + } + + return function combination() { + var state = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; + var action = arguments[1]; + + if (sanityError) { + throw sanityError; + } + + if (true) { + var warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action); + if (warningMessage) { + (0, _warning2["default"])(warningMessage); + } + } + + var hasChanged = false; + var nextState = {}; + for (var i = 0; i < finalReducerKeys.length; i++) { + var key = finalReducerKeys[i]; + var reducer = finalReducers[key]; + var previousStateForKey = state[key]; + var nextStateForKey = reducer(previousStateForKey, action); + if (typeof nextStateForKey === 'undefined') { + var errorMessage = getUndefinedStateErrorMessage(key, action); + throw new Error(errorMessage); + } + nextState[key] = nextStateForKey; + hasChanged = hasChanged || nextStateForKey !== previousStateForKey; + } + return hasChanged ? nextState : state; + }; + } + +/***/ }, +/* 8 */ +/***/ function(module, exports) { + + /** + * Checks if `value` is a host object in IE < 9. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a host object, else `false`. + */ + function isHostObject(value) { + // Many host objects are `Object` objects that can coerce to strings + // despite having improperly defined `toString` methods. + var result = false; + if (value != null && typeof value.toString != 'function') { + try { + result = !!(value + ''); + } catch (e) {} + } + return result; + } + + module.exports = isHostObject; + + +/***/ }, +/* 9 */ +/***/ function(module, exports) { + + /** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ + function isObjectLike(value) { + return !!value && typeof value == 'object'; + } + + module.exports = isObjectLike; + + +/***/ } +/******/ ]) +}); +;
\ No newline at end of file diff --git a/devtools/client/shared/vendor/reselect.js b/devtools/client/shared/vendor/reselect.js new file mode 100644 index 000000000..4d51d342c --- /dev/null +++ b/devtools/client/shared/vendor/reselect.js @@ -0,0 +1,136 @@ +(function (global, factory) { + if (typeof define === "function" && define.amd) { + define('Reselect', ['exports'], factory); + } else if (typeof exports !== "undefined") { + factory(exports); + } else { + var mod = { + exports: {} + }; + factory(mod.exports); + global.Reselect = mod.exports; + } +})(this, function (exports) { + 'use strict'; + + exports.__esModule = true; + exports.defaultMemoize = defaultMemoize; + exports.createSelectorCreator = createSelectorCreator; + exports.createStructuredSelector = createStructuredSelector; + + function _toConsumableArray(arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { + arr2[i] = arr[i]; + } + + return arr2; + } else { + return Array.from(arr); + } + } + + function defaultEqualityCheck(a, b) { + return a === b; + } + + function defaultMemoize(func) { + var equalityCheck = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultEqualityCheck; + + var lastArgs = null; + var lastResult = null; + var isEqualToLastArg = function isEqualToLastArg(value, index) { + return equalityCheck(value, lastArgs[index]); + }; + return function () { + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + if (lastArgs === null || lastArgs.length !== args.length || !args.every(isEqualToLastArg)) { + lastResult = func.apply(undefined, args); + } + lastArgs = args; + return lastResult; + }; + } + + function getDependencies(funcs) { + var dependencies = Array.isArray(funcs[0]) ? funcs[0] : funcs; + + if (!dependencies.every(function (dep) { + return typeof dep === 'function'; + })) { + var dependencyTypes = dependencies.map(function (dep) { + return typeof dep; + }).join(', '); + throw new Error('Selector creators expect all input-selectors to be functions, ' + ('instead received the following types: [' + dependencyTypes + ']')); + } + + return dependencies; + } + + function createSelectorCreator(memoize) { + for (var _len2 = arguments.length, memoizeOptions = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + memoizeOptions[_key2 - 1] = arguments[_key2]; + } + + return function () { + for (var _len3 = arguments.length, funcs = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + funcs[_key3] = arguments[_key3]; + } + + var recomputations = 0; + var resultFunc = funcs.pop(); + var dependencies = getDependencies(funcs); + + var memoizedResultFunc = memoize.apply(undefined, [function () { + recomputations++; + return resultFunc.apply(undefined, arguments); + }].concat(memoizeOptions)); + + var selector = function selector(state, props) { + for (var _len4 = arguments.length, args = Array(_len4 > 2 ? _len4 - 2 : 0), _key4 = 2; _key4 < _len4; _key4++) { + args[_key4 - 2] = arguments[_key4]; + } + + var params = dependencies.map(function (dependency) { + return dependency.apply(undefined, [state, props].concat(args)); + }); + return memoizedResultFunc.apply(undefined, _toConsumableArray(params)); + }; + + selector.resultFunc = resultFunc; + selector.recomputations = function () { + return recomputations; + }; + selector.resetRecomputations = function () { + return recomputations = 0; + }; + return selector; + }; + } + + var createSelector = exports.createSelector = createSelectorCreator(defaultMemoize); + + function createStructuredSelector(selectors) { + var selectorCreator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : createSelector; + + if (typeof selectors !== 'object') { + throw new Error('createStructuredSelector expects first argument to be an object ' + ('where each property is a selector, instead received a ' + typeof selectors)); + } + var objectKeys = Object.keys(selectors); + return selectorCreator(objectKeys.map(function (key) { + return selectors[key]; + }), function () { + for (var _len5 = arguments.length, values = Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { + values[_key5] = arguments[_key5]; + } + + return values.reduce(function (composition, value, index) { + composition[objectKeys[index]] = value; + return composition; + }, {}); + }); + } +}); diff --git a/devtools/client/shared/vendor/seamless-immutable.js b/devtools/client/shared/vendor/seamless-immutable.js new file mode 100644 index 000000000..ef893f384 --- /dev/null +++ b/devtools/client/shared/vendor/seamless-immutable.js @@ -0,0 +1,392 @@ +(function(){ + "use strict"; + + function addPropertyTo(target, methodName, value) { + Object.defineProperty(target, methodName, { + enumerable: false, + configurable: false, + writable: false, + value: value + }); + } + + function banProperty(target, methodName) { + addPropertyTo(target, methodName, function() { + throw new ImmutableError("The " + methodName + + " method cannot be invoked on an Immutable data structure."); + }); + } + + var immutabilityTag = "__immutable_invariants_hold"; + + function addImmutabilityTag(target) { + addPropertyTo(target, immutabilityTag, true); + } + + function isImmutable(target) { + if (typeof target === "object") { + return target === null || target.hasOwnProperty(immutabilityTag); + } else { + // In JavaScript, only objects are even potentially mutable. + // strings, numbers, null, and undefined are all naturally immutable. + return true; + } + } + + function isMergableObject(target) { + return target !== null && typeof target === "object" && !(target instanceof Array) && !(target instanceof Date); + } + + var mutatingObjectMethods = [ + "setPrototypeOf" + ]; + + var nonMutatingObjectMethods = [ + "keys" + ]; + + var mutatingArrayMethods = mutatingObjectMethods.concat([ + "push", "pop", "sort", "splice", "shift", "unshift", "reverse" + ]); + + var nonMutatingArrayMethods = nonMutatingObjectMethods.concat([ + "map", "filter", "slice", "concat", "reduce", "reduceRight" + ]); + + function ImmutableError(message) { + var err = new Error(message); + err.__proto__ = ImmutableError; + + return err; + } + ImmutableError.prototype = Error.prototype; + + function makeImmutable(obj, bannedMethods) { + // Tag it so we can quickly tell it's immutable later. + addImmutabilityTag(obj); + + if ("development" === "development") { + // Make all mutating methods throw exceptions. + for (var index in bannedMethods) { + if (bannedMethods.hasOwnProperty(index)) { + banProperty(obj, bannedMethods[index]); + } + } + + // Freeze it and return it. + Object.freeze(obj); + } + + return obj; + } + + function makeMethodReturnImmutable(obj, methodName) { + var currentMethod = obj[methodName]; + + addPropertyTo(obj, methodName, function() { + return Immutable(currentMethod.apply(obj, arguments)); + }); + } + + function makeImmutableArray(array) { + // Don't change their implementations, but wrap these functions to make sure + // they always return an immutable value. + for (var index in nonMutatingArrayMethods) { + if (nonMutatingArrayMethods.hasOwnProperty(index)) { + var methodName = nonMutatingArrayMethods[index]; + makeMethodReturnImmutable(array, methodName); + } + } + + addPropertyTo(array, "flatMap", flatMap); + addPropertyTo(array, "asObject", asObject); + addPropertyTo(array, "asMutable", asMutableArray); + + for(var i = 0, length = array.length; i < length; i++) { + array[i] = Immutable(array[i]); + } + + return makeImmutable(array, mutatingArrayMethods); + } + + /** + * Effectively performs a map() over the elements in the array, using the + * provided iterator, except that whenever the iterator returns an array, that + * array's elements are added to the final result instead of the array itself. + * + * @param {function} iterator - The iterator function that will be invoked on each element in the array. It will receive three arguments: the current value, the current index, and the current object. + */ + function flatMap(iterator) { + // Calling .flatMap() with no arguments is a no-op. Don't bother cloning. + if (arguments.length === 0) { + return this; + } + + var result = [], + length = this.length, + index; + + for (index = 0; index < length; index++) { + var iteratorResult = iterator(this[index], index, this); + + if (iteratorResult instanceof Array) { + // Concatenate Array results into the return value we're building up. + result.push.apply(result, iteratorResult); + } else { + // Handle non-Array results the same way map() does. + result.push(iteratorResult); + } + } + + return makeImmutableArray(result); + } + + /** + * Returns an Immutable copy of the object without the given keys included. + * + * @param {array} keysToRemove - A list of strings representing the keys to exclude in the return value. Instead of providing a single array, this method can also be called by passing multiple strings as separate arguments. + */ + function without(keysToRemove) { + // Calling .without() with no arguments is a no-op. Don't bother cloning. + if (arguments.length === 0) { + return this; + } + + // If we weren't given an array, use the arguments list. + if (!(keysToRemove instanceof Array)) { + keysToRemove = Array.prototype.slice.call(arguments); + } + + var result = this.instantiateEmptyObject(); + + for (var key in this) { + if (this.hasOwnProperty(key) && (keysToRemove.indexOf(key) === -1)) { + result[key] = this[key]; + } + } + + return makeImmutableObject(result, + {instantiateEmptyObject: this.instantiateEmptyObject}); + } + + function asMutableArray(opts) { + var result = [], i, length; + + if(opts && opts.deep) { + for(i = 0, length = this.length; i < length; i++) { + result.push( asDeepMutable(this[i]) ); + } + } else { + for(i = 0, length = this.length; i < length; i++) { + result.push(this[i]); + } + } + + return result; + } + + /** + * Effectively performs a [map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) over the elements in the array, expecting that the iterator function + * will return an array of two elements - the first representing a key, the other + * a value. Then returns an Immutable Object constructed of those keys and values. + * + * @param {function} iterator - A function which should return an array of two elements - the first representing the desired key, the other the desired value. + */ + function asObject(iterator) { + // If no iterator was provided, assume the identity function + // (suggesting this array is already a list of key/value pairs.) + if (typeof iterator !== "function") { + iterator = function(value) { return value; }; + } + + var result = {}, + length = this.length, + index; + + for (index = 0; index < length; index++) { + var pair = iterator(this[index], index, this), + key = pair[0], + value = pair[1]; + + result[key] = value; + } + + return makeImmutableObject(result); + } + + function asDeepMutable(obj) { + if(!obj || !obj.hasOwnProperty(immutabilityTag) || obj instanceof Date) { return obj; } + return obj.asMutable({deep: true}); + } + + function quickCopy(src, dest) { + for (var key in src) { + if (src.hasOwnProperty(key)) { + dest[key] = src[key]; + } + } + + return dest; + } + + /** + * Returns an Immutable Object containing the properties and values of both + * this object and the provided object, prioritizing the provided object's + * values whenever the same key is present in both objects. + * + * @param {object} other - The other object to merge. Multiple objects can be passed as an array. In such a case, the later an object appears in that list, the higher its priority. + * @param {object} config - Optional config object that contains settings. Supported settings are: {deep: true} for deep merge and {merger: mergerFunc} where mergerFunc is a function + * that takes a property from both objects. If anything is returned it overrides the normal merge behaviour. + */ + function merge(other, config) { + // Calling .merge() with no arguments is a no-op. Don't bother cloning. + if (arguments.length === 0) { + return this; + } + + if (other === null || (typeof other !== "object")) { + throw new TypeError("Immutable#merge can only be invoked with objects or arrays, not " + JSON.stringify(other)); + } + + var anyChanges = false, + result = quickCopy(this, this.instantiateEmptyObject()), // A shallow clone of this object. + receivedArray = (other instanceof Array), + deep = config && config.deep, + merger = config && config.merger, + key; + + // Use the given key to extract a value from the given object, then place + // that value in the result object under the same key. If that resulted + // in a change from this object's value at that key, set anyChanges = true. + function addToResult(currentObj, otherObj, key) { + var immutableValue = Immutable(otherObj[key]); + var mergerResult = merger && merger(currentObj[key], immutableValue, config); + if (merger && mergerResult && mergerResult === currentObj[key]) return; + + anyChanges = anyChanges || + mergerResult !== undefined || + (!currentObj.hasOwnProperty(key) || + ((immutableValue !== currentObj[key]) && + // Avoid false positives due to (NaN !== NaN) evaluating to true + (immutableValue === immutableValue))); + + if (mergerResult) { + result[key] = mergerResult; + } else if (deep && isMergableObject(currentObj[key]) && isMergableObject(immutableValue)) { + result[key] = currentObj[key].merge(immutableValue, config); + } else { + result[key] = immutableValue; + } + } + + // Achieve prioritization by overriding previous values that get in the way. + if (!receivedArray) { + // The most common use case: just merge one object into the existing one. + for (key in other) { + if (other.hasOwnProperty(key)) { + addToResult(this, other, key); + } + } + } else { + // We also accept an Array + for (var index=0; index < other.length; index++) { + var otherFromArray = other[index]; + + for (key in otherFromArray) { + if (otherFromArray.hasOwnProperty(key)) { + addToResult(this, otherFromArray, key); + } + } + } + } + + if (anyChanges) { + return makeImmutableObject(result, + {instantiateEmptyObject: this.instantiateEmptyObject}); + } else { + return this; + } + } + + function asMutableObject(opts) { + var result = this.instantiateEmptyObject(), key; + + if(opts && opts.deep) { + for (key in this) { + if (this.hasOwnProperty(key)) { + result[key] = asDeepMutable(this[key]); + } + } + } else { + for (key in this) { + if (this.hasOwnProperty(key)) { + result[key] = this[key]; + } + } + } + + return result; + } + + // Creates plain object to be used for cloning + function instantiatePlainObject() { + return {}; + } + + // Finalizes an object with immutable methods, freezes it, and returns it. + function makeImmutableObject(obj, options) { + var instantiateEmptyObject = + (options && options.instantiateEmptyObject) ? + options.instantiateEmptyObject : instantiatePlainObject; + + addPropertyTo(obj, "merge", merge); + addPropertyTo(obj, "without", without); + addPropertyTo(obj, "asMutable", asMutableObject); + addPropertyTo(obj, "instantiateEmptyObject", instantiateEmptyObject); + + return makeImmutable(obj, mutatingObjectMethods); + } + + function Immutable(obj, options) { + if (isImmutable(obj)) { + return obj; + } else if (obj instanceof Array) { + return makeImmutableArray(obj.slice()); + } else if (obj instanceof Date) { + return makeImmutable(new Date(obj.getTime())); + } else { + // Don't freeze the object we were given; make a clone and use that. + var prototype = options && options.prototype; + var instantiateEmptyObject = + (!prototype || prototype === Object.prototype) ? + instantiatePlainObject : (function() { return Object.create(prototype); }); + var clone = instantiateEmptyObject(); + + for (var key in obj) { + if (obj.hasOwnProperty(key)) { + clone[key] = Immutable(obj[key]); + } + } + + return makeImmutableObject(clone, + {instantiateEmptyObject: instantiateEmptyObject}); + } + } + + // Export the library + Immutable.isImmutable = isImmutable; + Immutable.ImmutableError = ImmutableError; + + Object.freeze(Immutable); + + /* istanbul ignore if */ + if (typeof module === "object") { + module.exports = Immutable; + } else if (typeof exports === "object") { + exports.Immutable = Immutable; + } else if (typeof window === "object") { + window.Immutable = Immutable; + } else if (typeof global === "object") { + global.Immutable = Immutable; + } +})(); |