Repository: casesandberg/react-color Branch: master Commit: bc9a0e1dc5d1 Files: 197 Total size: 2.0 MB Directory structure: gitextract_nu_8j6t6/ ├── .babelrc ├── .github/ │ └── CONTRIBUTING.md ├── .gitignore ├── .storybook/ │ ├── SyncColorField.js │ ├── addons.js │ ├── config.js │ └── report.js ├── .travis.yml ├── CODE_OF_CONDUCT.md ├── LICENSE ├── README.md ├── docs/ │ ├── build/ │ │ └── bundle.js │ ├── components/ │ │ └── home/ │ │ ├── Home.js │ │ ├── HomeDocumentation.js │ │ └── HomeFeature.js │ ├── documentation/ │ │ ├── 01-about.md │ │ ├── 02-getting-started.md │ │ ├── 02.01-install.md │ │ ├── 02.02-include.md │ │ ├── 03-api.md │ │ ├── 03.01-color.md │ │ ├── 03.02-onChange.md │ │ ├── 03.03-onChangeComplete.md │ │ ├── 03.04-individual.md │ │ ├── 03.05-customStyles.md │ │ ├── 04-create.md │ │ ├── 04.01-parent.md │ │ ├── 04.02-helpers.md │ │ ├── 05-examples.md │ │ └── index.js │ ├── index.html │ └── index.js ├── examples/ │ ├── basic/ │ │ ├── .gitignore │ │ ├── package.json │ │ ├── public/ │ │ │ └── index.html │ │ └── src/ │ │ ├── App.js │ │ └── index.js │ ├── basic-positioning/ │ │ ├── .gitignore │ │ ├── package.json │ │ ├── public/ │ │ │ └── index.html │ │ └── src/ │ │ ├── App.js │ │ └── index.js │ ├── basic-toggle-open-closed/ │ │ ├── .gitignore │ │ ├── package.json │ │ ├── public/ │ │ │ └── index.html │ │ └── src/ │ │ ├── App.js │ │ └── index.js │ ├── basic-with-react-hooks/ │ │ ├── .gitignore │ │ ├── package.json │ │ ├── public/ │ │ │ └── index.html │ │ └── src/ │ │ ├── App.js │ │ └── index.js │ ├── custom-picker/ │ │ ├── .gitignore │ │ ├── package.json │ │ ├── public/ │ │ │ └── index.html │ │ └── src/ │ │ ├── App.js │ │ ├── MyPicker.js │ │ └── index.js │ ├── custom-pointer/ │ │ ├── .gitignore │ │ ├── package.json │ │ ├── public/ │ │ │ └── index.html │ │ └── src/ │ │ ├── App.js │ │ ├── MyPicker.js │ │ ├── MyPointer.js │ │ └── index.js │ ├── with-portals/ │ │ ├── .gitignore │ │ ├── package.json │ │ ├── public/ │ │ │ └── index.html │ │ └── src/ │ │ ├── App.js │ │ ├── Modal.js │ │ ├── Portal.js │ │ └── index.js │ └── with-redux/ │ ├── .gitignore │ ├── package.json │ ├── public/ │ │ └── index.html │ └── src/ │ ├── App.js │ ├── index.js │ └── reducer.js ├── package.json ├── scripts/ │ ├── docs-dist.js │ ├── docs-server.js │ ├── restore-original-babelrc.js │ └── use-module-babelrc.js ├── src/ │ ├── Alpha.js │ ├── Block.js │ ├── Chrome.js │ ├── Circle.js │ ├── Compact.js │ ├── Custom.js │ ├── Github.js │ ├── Google.js │ ├── Hue.js │ ├── Material.js │ ├── Photoshop.js │ ├── Sketch.js │ ├── Slider.js │ ├── Swatches.js │ ├── Twitter.js │ ├── components/ │ │ ├── alpha/ │ │ │ ├── Alpha.js │ │ │ ├── AlphaPointer.js │ │ │ ├── __snapshots__/ │ │ │ │ └── spec.js.snap │ │ │ └── spec.js │ │ ├── block/ │ │ │ ├── Block.js │ │ │ ├── BlockSwatches.js │ │ │ ├── __snapshots__/ │ │ │ │ └── spec.js.snap │ │ │ ├── spec.js │ │ │ └── story.js │ │ ├── chrome/ │ │ │ ├── Chrome.js │ │ │ ├── ChromeFields.js │ │ │ ├── ChromePointer.js │ │ │ ├── ChromePointerCircle.js │ │ │ ├── __snapshots__/ │ │ │ │ └── spec.js.snap │ │ │ ├── spec.js │ │ │ └── story.js │ │ ├── circle/ │ │ │ ├── Circle.js │ │ │ ├── CircleSwatch.js │ │ │ ├── __snapshots__/ │ │ │ │ └── spec.js.snap │ │ │ ├── spec.js │ │ │ └── story.js │ │ ├── common/ │ │ │ ├── Alpha.js │ │ │ ├── Checkboard.js │ │ │ ├── ColorWrap.js │ │ │ ├── EditableInput.js │ │ │ ├── Hue.js │ │ │ ├── Raised.js │ │ │ ├── Saturation.js │ │ │ ├── Swatch.js │ │ │ ├── __snapshots__/ │ │ │ │ └── spec.js.snap │ │ │ ├── index.js │ │ │ └── spec.js │ │ ├── compact/ │ │ │ ├── Compact.js │ │ │ ├── CompactColor.js │ │ │ ├── CompactFields.js │ │ │ ├── __snapshots__/ │ │ │ │ └── spec.js.snap │ │ │ ├── spec.js │ │ │ └── story.js │ │ ├── github/ │ │ │ ├── Github.js │ │ │ ├── GithubSwatch.js │ │ │ ├── __snapshots__/ │ │ │ │ └── spec.js.snap │ │ │ ├── spec.js │ │ │ └── story.js │ │ ├── google/ │ │ │ ├── Google.js │ │ │ ├── GoogleFields.js │ │ │ ├── GooglePointer.js │ │ │ ├── GooglePointerCircle.js │ │ │ ├── __snapshots__/ │ │ │ │ └── spec.js.snap │ │ │ ├── spec.js │ │ │ └── story.js │ │ ├── hue/ │ │ │ ├── Hue.js │ │ │ ├── HuePointer.js │ │ │ ├── __snapshots__/ │ │ │ │ └── spec.js.snap │ │ │ └── spec.js │ │ ├── material/ │ │ │ ├── Material.js │ │ │ ├── __snapshots__/ │ │ │ │ └── spec.js.snap │ │ │ ├── spec.js │ │ │ └── story.js │ │ ├── photoshop/ │ │ │ ├── Photoshop.js │ │ │ ├── PhotoshopButton.js │ │ │ ├── PhotoshopFields.js │ │ │ ├── PhotoshopPointer.js │ │ │ ├── PhotoshopPointerCircle.js │ │ │ ├── PhotoshopPreviews.js │ │ │ ├── __snapshots__/ │ │ │ │ └── spec.js.snap │ │ │ ├── spec.js │ │ │ └── story.js │ │ ├── sketch/ │ │ │ ├── Sketch.js │ │ │ ├── SketchFields.js │ │ │ ├── SketchPresetColors.js │ │ │ ├── __snapshots__/ │ │ │ │ └── spec.js.snap │ │ │ ├── spec.js │ │ │ └── story.js │ │ ├── slider/ │ │ │ ├── Slider.js │ │ │ ├── SliderPointer.js │ │ │ ├── SliderSwatch.js │ │ │ ├── SliderSwatches.js │ │ │ ├── __snapshots__/ │ │ │ │ └── spec.js.snap │ │ │ └── spec.js │ │ ├── swatches/ │ │ │ ├── Swatches.js │ │ │ ├── SwatchesColor.js │ │ │ ├── SwatchesGroup.js │ │ │ ├── __snapshots__/ │ │ │ │ └── spec.js.snap │ │ │ ├── spec.js │ │ │ └── story.js │ │ └── twitter/ │ │ ├── Twitter.js │ │ ├── __snapshots__/ │ │ │ └── spec.js.snap │ │ ├── spec.js │ │ └── story.js │ ├── helpers/ │ │ ├── alpha.js │ │ ├── checkboard.js │ │ ├── color.js │ │ ├── hue.js │ │ ├── index.js │ │ ├── interaction.js │ │ ├── saturation.js │ │ └── spec.js │ └── index.js └── webpack.config.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .babelrc ================================================ { "presets": [ "es2015", "stage-0", "react" ] } ================================================ FILE: .github/CONTRIBUTING.md ================================================ # Contributing Fork and then clone the repo git clone git@github.com:your-username/react-color.git Install all npm scripts: npm install Make Changes. If you want to contribute check out the [help wanted](https://github.com/casesandberg/react-color/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22) issues for things that need fixing. To run the docs server locally run `npm run docs` and open http://localhost:9100/docs/. If you end up making any changes to the documentation or documentation site make sure to run `npm run docs-dist` when creating a pull request. Before submitting a pull request run `npm run test` to run the unit-tests and `npm run eslint` to check for linting errors in your changes. ================================================ FILE: .gitignore ================================================ *.log *.DS_Store node_modules package-lock.json lib es .babelrc_backup ================================================ FILE: .storybook/SyncColorField.js ================================================ import React from 'react' export default class SyncColorField extends React.Component { constructor(props) { super(props) this.state = { colorField: props.component.defaultProps.color, } } render() { const handleChange = ({ hex }) => this.setState({ colorField: hex }) return React.cloneElement(this.props.children, { onChange: handleChange, color: this.state.colorField, }) } } ================================================ FILE: .storybook/addons.js ================================================ import '@storybook/addon-options/register' import '@storybook/addon-knobs/register' ================================================ FILE: .storybook/config.js ================================================ import { configure, addDecorator } from '@storybook/react'; import { setOptions } from '@storybook/addon-options'; import centered from '@storybook/addon-centered'; import { withKnobs } from '@storybook/addon-knobs'; setOptions({ name: 'React Color', url: 'http://casesandberg.github.io/react-color/', downPanelInRight: true, }) addDecorator(centered); addDecorator(withKnobs); const req = require.context('../src/components', true, /\.?story\.js$/) const loadStories = () => req.keys().forEach((filename) => req(filename)) configure(loadStories, module); ================================================ FILE: .storybook/report.js ================================================ import React from 'react' import _ from 'lodash' import PropTypes from 'prop-types' import PROP_TYPE_SECRET from 'prop-types/lib/ReactPropTypesSecret' import { number, color, select, array, boolean } from '@storybook/addon-knobs' const THIS_STRING_SHOULDNT_MATCH = 'THIS_STRING_SHOULDNT_MATCH' export const generatePropReport = ({ propTypes, defaultProps }) => { const props = {} // console.log(propTypes.foo({ ['foo']: THIS_STRING_SHOULDNT_MATCH }, 'foo', null, 'prop', 'foo', PROP_TYPE_SECRET)) _.each(propTypes, (type, prop) => { const error = type({[prop]: THIS_STRING_SHOULDNT_MATCH}, prop, 'Component', 'prop', prop, PROP_TYPE_SECRET) if (error) { const argType = { [PropTypes.array]: 'array', [PropTypes.bool]: 'boolean', [PropTypes.func]: 'function', [PropTypes.number]: 'number', [PropTypes.object]: 'object', [PropTypes.string]: 'string', // [PropTypes.symbol]: 'symbol', }[error.args] props[prop] = { ...props[prop], type: error.type } const args = argType || error.args if (args) { props[prop] = { ...props[prop], args } } } else { props[prop] = { ...props[prop], type: 'string' } } if (defaultProps[prop]) { props[prop] = { ...props[prop], default: defaultProps[prop] } } }) // _.each(defaultProps, (defaultValue, prop) => { // props[prop] = { ...props[prop], default: defaultValue } // }) return props } export const renderWithKnobs = (Component, props = {}, children = null, knobsSettings = {}) => { const knobs = generatePropReport(Component) const makeLabel = ({ name, type, defaultProp }) => { return `${ name }${ type ? ` (${ type }${ defaultProp ? ` = ${ defaultProp }` : '' })` : '' }` } const knobProps = _.reduce(knobs, (all, prop, name) => { if (prop.type === 'enum') { const label = makeLabel({ name: name, type: JSON.stringify(prop.args), defaultProp: prop.default }) const options = _.reduce(prop.args, (options, value) => { options[value] = value return options }, {}) all[name] = select(label, options, prop.default) } if (prop.type === 'number') { const label = makeLabel({ name, type: prop.type, defaultProp: prop.default }) all[name] = number(label, prop.default, knobsSettings[name]) } if (prop.type === 'array') { const label = makeLabel({ name, type: prop.type, defaultProp: prop.default }) all[name] = array(label, prop.default, knobsSettings[name] || ', ') } if (prop.type === 'arrayOf') { const label = makeLabel({ name, type: `[]${ prop.args }s` }) all[name] = array(label, prop.default, knobsSettings[name] || ', ') } if (prop.type === 'boolean') { const label = makeLabel({ name, type: prop.type, defaultProp: prop.default }) all[name] = boolean(label, prop.default) } return all }, {}) return {children} } ================================================ FILE: .travis.yml ================================================ language: node_js node_js: - 6 notifications: email: on_success: never script: npm test cache: directories: - node_modules ================================================ FILE: CODE_OF_CONDUCT.md ================================================ # Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at case@casesandberg.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/4/ ================================================ FILE: LICENSE ================================================ The MIT License (MIT) Copyright (c) 2015 Case Sandberg 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. ================================================ FILE: README.md ================================================ # [React Color](http://casesandberg.github.io/react-color/) [![Npm Version][npm-version-image]][npm-version-url] [![Build Status][travis-svg]][travis-url] [![License][license-image]][license-url] [![Downloads][downloads-image]][downloads-url] * **13 Different Pickers** - Sketch, Photoshop, Chrome and many more * **Make Your Own** - Use the building block components to make your own ## Demo ![Demo](https://media.giphy.com/media/26FfggT53qE304CwE/giphy.gif) [**Live Demo**](http://casesandberg.github.io/react-color/) ## Installation & Usage ```sh npm install react-color --save ``` ### Include the Component ```js import React from 'react' import { SketchPicker } from 'react-color' class Component extends React.Component { render() { return } } ``` You can import `AlphaPicker` `BlockPicker` `ChromePicker` `CirclePicker` `CompactPicker` `GithubPicker` `HuePicker` `MaterialPicker` `PhotoshopPicker` `SketchPicker` `SliderPicker` `SwatchesPicker` `TwitterPicker` respectively. > 100% inline styles via [ReactCSS](http://reactcss.com/) [travis-svg]: https://travis-ci.org/casesandberg/react-color.svg [travis-url]: https://travis-ci.org/casesandberg/react-color [license-image]: http://img.shields.io/npm/l/react-color.svg [license-url]: LICENSE [downloads-image]: http://img.shields.io/npm/dm/react-color.svg [downloads-url]: http://npm-stat.com/charts.html?package=react-color [npm-version-image]: https://img.shields.io/npm/v/react-color.svg [npm-version-url]: https://www.npmjs.com/package/react-color ================================================ FILE: docs/build/bundle.js ================================================ /******/ (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 = "docs/build/"; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ((function(modules) { // Check all modules for deduplicated modules for(var i in modules) { if(Object.prototype.hasOwnProperty.call(modules, i)) { switch(typeof modules[i]) { case "function": break; case "object": // Module can be created from a template modules[i] = (function(_m) { var args = _m.slice(1), fn = modules[_m[0]]; return function (a,b,c) { fn.apply(this, [a,b,c].concat(args)); }; }(modules[i])); break; default: // Module is a copy of another module modules[i] = modules[modules[i]]; break; } } } return modules; }([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(1); /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(32); var _reactDom2 = _interopRequireDefault(_reactDom); var _Home = __webpack_require__(171); var _Home2 = _interopRequireDefault(_Home); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // const html = ReactDOMServer.renderToString(React.createElement(Home)) // console.log(html) if (typeof document !== 'undefined') { _reactDom2.default.render(_react2.default.createElement(_Home2.default), document.getElementById('root')); } // import ReactDOMServer from 'react-dom-server' module.exports = _Home2.default; /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; module.exports = __webpack_require__(3); /***/ }), /* 3 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(4); var ReactBaseClasses = __webpack_require__(5); var ReactChildren = __webpack_require__(14); var ReactDOMFactories = __webpack_require__(22); var ReactElement = __webpack_require__(16); var ReactPropTypes = __webpack_require__(23); var ReactVersion = __webpack_require__(28); var createReactClass = __webpack_require__(29); var onlyChild = __webpack_require__(31); var createElement = ReactElement.createElement; var createFactory = ReactElement.createFactory; var cloneElement = ReactElement.cloneElement; if (false) { var lowPriorityWarning = require('./lowPriorityWarning'); var canDefineProperty = require('./canDefineProperty'); var ReactElementValidator = require('./ReactElementValidator'); var didWarnPropTypesDeprecated = false; createElement = ReactElementValidator.createElement; createFactory = ReactElementValidator.createFactory; cloneElement = ReactElementValidator.cloneElement; } var __spread = _assign; var createMixin = function (mixin) { return mixin; }; if (false) { var warnedForSpread = false; var warnedForCreateMixin = false; __spread = function () { lowPriorityWarning(warnedForSpread, 'React.__spread is deprecated and should not be used. Use ' + 'Object.assign directly or another helper function with similar ' + 'semantics. You may be seeing this warning due to your compiler. ' + 'See https://fb.me/react-spread-deprecation for more details.'); warnedForSpread = true; return _assign.apply(null, arguments); }; createMixin = function (mixin) { lowPriorityWarning(warnedForCreateMixin, 'React.createMixin is deprecated and should not be used. ' + 'In React v16.0, it will be removed. ' + 'You can use this mixin directly instead. ' + 'See https://fb.me/createmixin-was-never-implemented for more info.'); warnedForCreateMixin = true; return mixin; }; } var React = { // Modern Children: { map: ReactChildren.map, forEach: ReactChildren.forEach, count: ReactChildren.count, toArray: ReactChildren.toArray, only: onlyChild }, Component: ReactBaseClasses.Component, PureComponent: ReactBaseClasses.PureComponent, createElement: createElement, cloneElement: cloneElement, isValidElement: ReactElement.isValidElement, // Classic PropTypes: ReactPropTypes, createClass: createReactClass, createFactory: createFactory, createMixin: createMixin, // This looks DOM specific but these are actually isomorphic helpers // since they are just generating DOM strings. DOM: ReactDOMFactories, version: ReactVersion, // Deprecated hook for JSX spread, don't use this for anything. __spread: __spread }; if (false) { var warnedForCreateClass = false; if (canDefineProperty) { Object.defineProperty(React, 'PropTypes', { get: function () { lowPriorityWarning(didWarnPropTypesDeprecated, 'Accessing PropTypes via the main React package is deprecated,' + ' and will be removed in React v16.0.' + ' Use the latest available v15.* prop-types package from npm instead.' + ' For info on usage, compatibility, migration and more, see ' + 'https://fb.me/prop-types-docs'); didWarnPropTypesDeprecated = true; return ReactPropTypes; } }); Object.defineProperty(React, 'createClass', { get: function () { lowPriorityWarning(warnedForCreateClass, 'Accessing createClass via the main React package is deprecated,' + ' and will be removed in React v16.0.' + " Use a plain JavaScript class instead. If you're not yet " + 'ready to migrate, create-react-class v15.* is available ' + 'on npm as a temporary, drop-in replacement. ' + 'For more info see https://fb.me/react-create-class'); warnedForCreateClass = true; return createReactClass; } }); } // React.DOM factories are deprecated. Wrap these methods so that // invocations of the React.DOM namespace and alert users to switch // to the `react-dom-factories` package. React.DOM = {}; var warnedForFactories = false; Object.keys(ReactDOMFactories).forEach(function (factory) { React.DOM[factory] = function () { if (!warnedForFactories) { lowPriorityWarning(false, 'Accessing factories like React.DOM.%s has been deprecated ' + 'and will be removed in v16.0+. Use the ' + 'react-dom-factories package instead. ' + ' Version 1.0 provides a drop-in replacement.' + ' For more info, see https://fb.me/react-dom-factories', factory); warnedForFactories = true; } return ReactDOMFactories[factory].apply(ReactDOMFactories, arguments); }; }); } module.exports = React; /***/ }), /* 4 */ /***/ (function(module, exports) { /* object-assign (c) Sindre Sorhus @license MIT */ 'use strict'; /* eslint-disable no-unused-vars */ var getOwnPropertySymbols = Object.getOwnPropertySymbols; var hasOwnProperty = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } function shouldUseNative() { try { if (!Object.assign) { return false; } // Detect buggy property enumeration order in older V8 versions. // https://bugs.chromium.org/p/v8/issues/detail?id=4118 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers test1[5] = 'de'; if (Object.getOwnPropertyNames(test1)[0] === '5') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test2 = {}; for (var i = 0; i < 10; i++) { test2['_' + String.fromCharCode(i)] = i; } var order2 = Object.getOwnPropertyNames(test2).map(function (n) { return test2[n]; }); if (order2.join('') !== '0123456789') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test3 = {}; 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { test3[letter] = letter; }); if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') { return false; } return true; } catch (err) { // We don't expect any of the above to throw, but better to be safe. return false; } } module.exports = shouldUseNative() ? Object.assign : function (target, source) { var from; var to = toObject(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } if (getOwnPropertySymbols) { symbols = getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; /***/ }), /* 5 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(6), _assign = __webpack_require__(4); var ReactNoopUpdateQueue = __webpack_require__(7); var canDefineProperty = __webpack_require__(10); var emptyObject = __webpack_require__(11); var invariant = __webpack_require__(12); var lowPriorityWarning = __webpack_require__(13); /** * 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) ? false ? invariant(false, 'setState(...): takes an object of state variables to update or a function which returns an object of state variables.') : _prodInvariant('85') : void 0; this.updater.enqueueSetState(this, partialState); if (callback) { this.updater.enqueueCallback(this, callback, 'setState'); } }; /** * 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, 'forceUpdate'); } }; /** * 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 (false) { var deprecatedAPIs = { isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'], replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).'] }; var defineDeprecationWarning = function (methodName, info) { if (canDefineProperty) { Object.defineProperty(ReactComponent.prototype, methodName, { get: function () { lowPriorityWarning(false, '%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]); return undefined; } }); } }; for (var fnName in deprecatedAPIs) { if (deprecatedAPIs.hasOwnProperty(fnName)) { defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); } } } /** * Base class helpers for the updating state of a component. */ function ReactPureComponent(props, context, updater) { // Duplicated from ReactComponent. 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; } function ComponentDummy() {} ComponentDummy.prototype = ReactComponent.prototype; ReactPureComponent.prototype = new ComponentDummy(); ReactPureComponent.prototype.constructor = ReactPureComponent; // Avoid an extra prototype jump for these methods. _assign(ReactPureComponent.prototype, ReactComponent.prototype); ReactPureComponent.prototype.isPureReactComponent = true; module.exports = { Component: ReactComponent, PureComponent: ReactPureComponent }; /***/ }), /* 6 */ /***/ (function(module, exports) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; /** * WARNING: DO NOT manually require this module. * This is a replacement for `invariant(...)` used by the error code system * and will _only_ be required by the corresponding babel pass. * It always throws. */ function reactProdInvariant(code) { var argCount = arguments.length - 1; var message = 'Minified React error #' + code + '; visit ' + 'http://facebook.github.io/react/docs/error-decoder.html?invariant=' + code; for (var argIdx = 0; argIdx < argCount; argIdx++) { message += '&args[]=' + encodeURIComponent(arguments[argIdx + 1]); } message += ' for the full message or use the non-minified dev environment' + ' for full errors and additional helpful warnings.'; var error = new Error(message); error.name = 'Invariant Violation'; error.framesToPop = 1; // we don't care about reactProdInvariant's own frame throw error; } module.exports = reactProdInvariant; /***/ }), /* 7 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var warning = __webpack_require__(8); function warnNoop(publicInstance, callerName) { if (false) { var constructor = publicInstance.constructor; process.env.NODE_ENV !== '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, constructor && (constructor.displayName || constructor.name) || 'ReactClass') : void 0; } } /** * 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) { warnNoop(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) { warnNoop(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) { warnNoop(publicInstance, 'setState'); } }; module.exports = ReactNoopUpdateQueue; /***/ }), /* 8 */ /***/ (function(module, exports, __webpack_require__) { /** * 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. * */ 'use strict'; var emptyFunction = __webpack_require__(9); /** * 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 (false) { (function () { var printWarning = function printWarning(format) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } 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) {} }; warning = function warning(condition, format) { 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) { for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) { args[_key2 - 2] = arguments[_key2]; } printWarning.apply(undefined, [format].concat(args)); } }; })(); } module.exports = warning; /***/ }), /* 9 */ /***/ (function(module, exports) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in 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 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. */ var emptyFunction = 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; /***/ }), /* 10 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var canDefineProperty = false; if (false) { try { // $FlowFixMe https://github.com/facebook/flow/issues/285 Object.defineProperty({}, 'x', { get: function () {} }); canDefineProperty = true; } catch (x) { // IE will fail on defineProperty } } module.exports = canDefineProperty; /***/ }), /* 11 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var emptyObject = {}; if (false) { Object.freeze(emptyObject); } module.exports = emptyObject; /***/ }), /* 12 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ '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 validateFormat = function validateFormat(format) {}; if (false) { validateFormat = function validateFormat(format) { if (format === undefined) { throw new Error('invariant requires an error message argument'); } }; } function invariant(condition, format, a, b, c, d, e, f) { validateFormat(format); 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; /***/ }), /* 13 */ /***/ (function(module, exports, __webpack_require__) { /** * 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. * */ 'use strict'; /** * Forked from fbjs/warning: * https://github.com/facebook/fbjs/blob/e66ba20ad5be433eb54423f2b097d829324d9de6/packages/fbjs/src/__forks__/warning.js * * Only change is we use console.warn instead of console.error, * and do nothing when 'console' is not supported. * This really simplifies the code. * --- * 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 lowPriorityWarning = function () {}; if (false) { var printWarning = function (format) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function () { return args[argIndex++]; }); if (typeof console !== 'undefined') { console.warn(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) {} }; lowPriorityWarning = function (condition, format) { if (format === undefined) { throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument'); } if (!condition) { for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) { args[_key2 - 2] = arguments[_key2]; } printWarning.apply(undefined, [format].concat(args)); } }; } module.exports = lowPriorityWarning; /***/ }), /* 14 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var PooledClass = __webpack_require__(15); var ReactElement = __webpack_require__(16); var emptyFunction = __webpack_require__(9); var traverseAllChildren = __webpack_require__(19); 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, context = bookKeeping.context; func.call(context, child, bookKeeping.count++); } /** * Iterates through children that are typically specified as `props.children`. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.foreach * * 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, keyPrefix = bookKeeping.keyPrefix, func = bookKeeping.func, 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.key && (!child || child.key !== mappedChild.key) ? 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`. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.map * * 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`. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.count * * @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. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.toarray */ 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; /***/ }), /* 15 */ [443, 6], /* 16 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(4); var ReactCurrentOwner = __webpack_require__(17); var warning = __webpack_require__(8); var canDefineProperty = __webpack_require__(10); var hasOwnProperty = Object.prototype.hasOwnProperty; var REACT_ELEMENT_TYPE = __webpack_require__(18); var RESERVED_PROPS = { key: true, ref: true, __self: true, __source: true }; var specialPropKeyWarningShown, specialPropRefWarningShown; function hasValidRef(config) { if (false) { if (hasOwnProperty.call(config, 'ref')) { var getter = Object.getOwnPropertyDescriptor(config, 'ref').get; if (getter && getter.isReactWarning) { return false; } } } return config.ref !== undefined; } function hasValidKey(config) { if (false) { if (hasOwnProperty.call(config, 'key')) { var getter = Object.getOwnPropertyDescriptor(config, 'key').get; if (getter && getter.isReactWarning) { return false; } } } return config.key !== undefined; } function defineKeyPropWarningGetter(props, displayName) { var warnAboutAccessingKey = function () { if (!specialPropKeyWarningShown) { specialPropKeyWarningShown = true; false ? warning(false, '%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName) : void 0; } }; warnAboutAccessingKey.isReactWarning = true; Object.defineProperty(props, 'key', { get: warnAboutAccessingKey, configurable: true }); } function defineRefPropWarningGetter(props, displayName) { var warnAboutAccessingRef = function () { if (!specialPropRefWarningShown) { specialPropRefWarningShown = true; false ? warning(false, '%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName) : void 0; } }; warnAboutAccessingRef.isReactWarning = true; Object.defineProperty(props, 'ref', { get: warnAboutAccessingRef, configurable: true }); } /** * Factory method to create a new React element. This no longer adheres to * the class pattern, so do not use new to call it. Also, no instanceof check * will work. Instead test $$typeof field against Symbol.for('react.element') to check * if something is a React Element. * * @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 (false) { // 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; } if (Object.freeze) { Object.freeze(element.props); Object.freeze(element); } } return element; }; /** * Create and return a new ReactElement of the given type. * See https://facebook.github.io/react/docs/top-level-api.html#react.createelement */ 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) { if (hasValidRef(config)) { ref = config.ref; } if (hasValidKey(config)) { key = '' + 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 (hasOwnProperty.call(config, 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]; } if (false) { if (Object.freeze) { Object.freeze(childArray); } } props.children = childArray; } // Resolve default props if (type && type.defaultProps) { var defaultProps = type.defaultProps; for (propName in defaultProps) { if (props[propName] === undefined) { props[propName] = defaultProps[propName]; } } } if (false) { if (key || ref) { if (typeof props.$$typeof === 'undefined' || props.$$typeof !== REACT_ELEMENT_TYPE) { var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type; if (key) { defineKeyPropWarningGetter(props, displayName); } if (ref) { defineRefPropWarningGetter(props, displayName); } } } } return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); }; /** * Return a function that produces ReactElements of a given type. * See https://facebook.github.io/react/docs/top-level-api.html#react.createfactory */ 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. `.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; }; /** * Clone and return a new ReactElement using element as the starting point. * See https://facebook.github.io/react/docs/top-level-api.html#react.cloneelement */ 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 (hasValidRef(config)) { // Silently steal the ref from the parent. ref = config.ref; owner = ReactCurrentOwner.current; } if (hasValidKey(config)) { key = '' + config.key; } // Remaining properties override existing props var defaultProps; if (element.type && element.type.defaultProps) { defaultProps = element.type.defaultProps; } for (propName in config) { if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { if (config[propName] === undefined && defaultProps !== undefined) { // Resolve default props props[propName] = defaultProps[propName]; } else { 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); }; /** * Verifies the object is a ReactElement. * See https://facebook.github.io/react/docs/top-level-api.html#react.isvalidelement * @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; /***/ }), /* 17 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ '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; /***/ }), /* 18 */ /***/ (function(module, exports) { /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; // 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; module.exports = REACT_ELEMENT_TYPE; /***/ }), /* 19 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(6); var ReactCurrentOwner = __webpack_require__(17); var REACT_ELEMENT_TYPE = __webpack_require__(18); var getIteratorFn = __webpack_require__(20); var invariant = __webpack_require__(12); var KeyEscapeUtils = __webpack_require__(21); var warning = __webpack_require__(8); var SEPARATOR = '.'; var SUBSEPARATOR = ':'; /** * This is inlined from ReactElement since this file is shared between * isomorphic and renderers. We could extract this to a * */ /** * TODO: Test that a single child and an array with one item have the same key * pattern. */ var didWarnAboutMaps = false; /** * 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) { // Do some typechecking here since we call this blindly. We want to ensure // that we don't block potential future ES APIs. if (component && typeof component === 'object' && component.key != null) { // Explicit key return KeyEscapeUtils.escape(component.key); } // Implicit key determined by the index in the set return index.toString(36); } /** * @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' || // The following is inlined from ReactElement. This means we can optimize // some checks. React Fiber also inlines this logic for similar purposes. type === 'object' && children.$$typeof === REACT_ELEMENT_TYPE) { 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 (false) { var mapsAsChildrenAddendum = ''; if (ReactCurrentOwner.current) { var mapsAsChildrenOwnerName = ReactCurrentOwner.current.getName(); if (mapsAsChildrenOwnerName) { mapsAsChildrenAddendum = ' Check the render method of `' + mapsAsChildrenOwnerName + '`.'; } } process.env.NODE_ENV !== '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.%s', mapsAsChildrenAddendum) : void 0; 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 + KeyEscapeUtils.escape(entry[0]) + SUBSEPARATOR + getComponentKey(child, 0); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } } } else if (type === 'object') { var addendum = ''; if (false) { 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); true ? false ? 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) : _prodInvariant('31', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : void 0; } } 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; /***/ }), /* 20 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ '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; /***/ }), /* 21 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; /** * Escape and wrap key so it is safe to use as a reactid * * @param {string} key to be escaped. * @return {string} the escaped key. */ function escape(key) { var escapeRegex = /[=:]/g; var escaperLookup = { '=': '=0', ':': '=2' }; var escapedString = ('' + key).replace(escapeRegex, function (match) { return escaperLookup[match]; }); return '$' + escapedString; } /** * Unescape and unwrap key for human-readable display * * @param {string} key to unescape. * @return {string} the unescaped key. */ function unescape(key) { var unescapeRegex = /(=0|=2)/g; var unescaperLookup = { '=0': '=', '=2': ':' }; var keySubstring = key[0] === '.' && key[1] === '$' ? key.substring(2) : key.substring(1); return ('' + keySubstring).replace(unescapeRegex, function (match) { return unescaperLookup[match]; }); } var KeyEscapeUtils = { escape: escape, unescape: unescape }; module.exports = KeyEscapeUtils; /***/ }), /* 22 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ReactElement = __webpack_require__(16); /** * Create a factory that creates HTML tag elements. * * @private */ var createDOMFactory = ReactElement.createFactory; if (false) { var ReactElementValidator = require('./ReactElementValidator'); createDOMFactory = ReactElementValidator.createFactory; } /** * Creates a mapping from supported HTML tags to `ReactDOMComponent` classes. * * @public */ var ReactDOMFactories = { a: createDOMFactory('a'), abbr: createDOMFactory('abbr'), address: createDOMFactory('address'), area: createDOMFactory('area'), article: createDOMFactory('article'), aside: createDOMFactory('aside'), audio: createDOMFactory('audio'), b: createDOMFactory('b'), base: createDOMFactory('base'), bdi: createDOMFactory('bdi'), bdo: createDOMFactory('bdo'), big: createDOMFactory('big'), blockquote: createDOMFactory('blockquote'), body: createDOMFactory('body'), br: createDOMFactory('br'), button: createDOMFactory('button'), canvas: createDOMFactory('canvas'), caption: createDOMFactory('caption'), cite: createDOMFactory('cite'), code: createDOMFactory('code'), col: createDOMFactory('col'), colgroup: createDOMFactory('colgroup'), data: createDOMFactory('data'), datalist: createDOMFactory('datalist'), dd: createDOMFactory('dd'), del: createDOMFactory('del'), details: createDOMFactory('details'), dfn: createDOMFactory('dfn'), dialog: createDOMFactory('dialog'), div: createDOMFactory('div'), dl: createDOMFactory('dl'), dt: createDOMFactory('dt'), em: createDOMFactory('em'), embed: createDOMFactory('embed'), fieldset: createDOMFactory('fieldset'), figcaption: createDOMFactory('figcaption'), figure: createDOMFactory('figure'), footer: createDOMFactory('footer'), form: createDOMFactory('form'), h1: createDOMFactory('h1'), h2: createDOMFactory('h2'), h3: createDOMFactory('h3'), h4: createDOMFactory('h4'), h5: createDOMFactory('h5'), h6: createDOMFactory('h6'), head: createDOMFactory('head'), header: createDOMFactory('header'), hgroup: createDOMFactory('hgroup'), hr: createDOMFactory('hr'), html: createDOMFactory('html'), i: createDOMFactory('i'), iframe: createDOMFactory('iframe'), img: createDOMFactory('img'), input: createDOMFactory('input'), ins: createDOMFactory('ins'), kbd: createDOMFactory('kbd'), keygen: createDOMFactory('keygen'), label: createDOMFactory('label'), legend: createDOMFactory('legend'), li: createDOMFactory('li'), link: createDOMFactory('link'), main: createDOMFactory('main'), map: createDOMFactory('map'), mark: createDOMFactory('mark'), menu: createDOMFactory('menu'), menuitem: createDOMFactory('menuitem'), meta: createDOMFactory('meta'), meter: createDOMFactory('meter'), nav: createDOMFactory('nav'), noscript: createDOMFactory('noscript'), object: createDOMFactory('object'), ol: createDOMFactory('ol'), optgroup: createDOMFactory('optgroup'), option: createDOMFactory('option'), output: createDOMFactory('output'), p: createDOMFactory('p'), param: createDOMFactory('param'), picture: createDOMFactory('picture'), pre: createDOMFactory('pre'), progress: createDOMFactory('progress'), q: createDOMFactory('q'), rp: createDOMFactory('rp'), rt: createDOMFactory('rt'), ruby: createDOMFactory('ruby'), s: createDOMFactory('s'), samp: createDOMFactory('samp'), script: createDOMFactory('script'), section: createDOMFactory('section'), select: createDOMFactory('select'), small: createDOMFactory('small'), source: createDOMFactory('source'), span: createDOMFactory('span'), strong: createDOMFactory('strong'), style: createDOMFactory('style'), sub: createDOMFactory('sub'), summary: createDOMFactory('summary'), sup: createDOMFactory('sup'), table: createDOMFactory('table'), tbody: createDOMFactory('tbody'), td: createDOMFactory('td'), textarea: createDOMFactory('textarea'), tfoot: createDOMFactory('tfoot'), th: createDOMFactory('th'), thead: createDOMFactory('thead'), time: createDOMFactory('time'), title: createDOMFactory('title'), tr: createDOMFactory('tr'), track: createDOMFactory('track'), u: createDOMFactory('u'), ul: createDOMFactory('ul'), 'var': createDOMFactory('var'), video: createDOMFactory('video'), wbr: createDOMFactory('wbr'), // SVG circle: createDOMFactory('circle'), clipPath: createDOMFactory('clipPath'), defs: createDOMFactory('defs'), ellipse: createDOMFactory('ellipse'), g: createDOMFactory('g'), image: createDOMFactory('image'), line: createDOMFactory('line'), linearGradient: createDOMFactory('linearGradient'), mask: createDOMFactory('mask'), path: createDOMFactory('path'), pattern: createDOMFactory('pattern'), polygon: createDOMFactory('polygon'), polyline: createDOMFactory('polyline'), radialGradient: createDOMFactory('radialGradient'), rect: createDOMFactory('rect'), stop: createDOMFactory('stop'), svg: createDOMFactory('svg'), text: createDOMFactory('text'), tspan: createDOMFactory('tspan') }; module.exports = ReactDOMFactories; /***/ }), /* 23 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _require = __webpack_require__(16), isValidElement = _require.isValidElement; var factory = __webpack_require__(24); module.exports = factory(isValidElement); /***/ }), /* 24 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; // React 15.5 references this module, and assumes PropTypes are still callable in production. // Therefore we re-export development-only version with all the PropTypes checks here. // However if one is migrating to the `prop-types` npm library, they will go through the // `index.js` entry point, and it will branch depending on the environment. var factory = __webpack_require__(25); module.exports = function(isValidElement) { // It is still allowed in 15.5. var throwOnDirectAccess = false; return factory(isValidElement, throwOnDirectAccess); }; /***/ }), /* 25 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; var emptyFunction = __webpack_require__(9); var invariant = __webpack_require__(12); var warning = __webpack_require__(8); var ReactPropTypesSecret = __webpack_require__(26); var checkPropTypes = __webpack_require__(27); module.exports = function(isValidElement, throwOnDirectAccess) { /* 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; } } /** * 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 = '<>'; // Important! // Keep this list in sync with production version in `./factoryWithThrowingShims.js`. var ReactPropTypes = { array: createPrimitiveTypeChecker('array'), bool: createPrimitiveTypeChecker('boolean'), func: createPrimitiveTypeChecker('function'), number: createPrimitiveTypeChecker('number'), object: createPrimitiveTypeChecker('object'), string: createPrimitiveTypeChecker('string'), symbol: createPrimitiveTypeChecker('symbol'), any: createAnyTypeChecker(), arrayOf: createArrayOfTypeChecker, element: createElementTypeChecker(), instanceOf: createInstanceTypeChecker, node: createNodeChecker(), objectOf: createObjectOfTypeChecker, oneOf: createEnumTypeChecker, oneOfType: createUnionTypeChecker, shape: createShapeTypeChecker }; /** * inlined Object.is polyfill to avoid requiring consumers ship their own * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is */ /*eslint-disable no-self-compare*/ function is(x, y) { // SameValue algorithm if (x === y) { // Steps 1-5, 7-10 // Steps 6.b-6.e: +0 != -0 return x !== 0 || 1 / x === 1 / y; } else { // Step 6.a: NaN == NaN return x !== x && y !== y; } } /*eslint-enable no-self-compare*/ /** * We use an Error-like object for backward compatibility as people may call * PropTypes directly and inspect their output. However, we don't use real * Errors anymore. We don't inspect their stack anyway, and creating them * is prohibitively expensive if they are created too often, such as what * happens in oneOfType() for any type before the one that matched. */ function PropTypeError(message) { this.message = message; this.stack = ''; } // Make `instanceof Error` still work for returned errors. PropTypeError.prototype = Error.prototype; function createChainableTypeChecker(validate) { if (false) { var manualPropTypeCallCache = {}; var manualPropTypeWarningCount = 0; } function checkType(isRequired, props, propName, componentName, location, propFullName, secret) { componentName = componentName || ANONYMOUS; propFullName = propFullName || propName; if (secret !== ReactPropTypesSecret) { if (throwOnDirectAccess) { // New behavior only for users of `prop-types` package invariant( false, 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' + 'Use `PropTypes.checkPropTypes()` to call them. ' + 'Read more at http://fb.me/use-check-prop-types' ); } else if (false) { // Old behavior for people using React.PropTypes var cacheKey = componentName + ':' + propName; if ( !manualPropTypeCallCache[cacheKey] && // Avoid spamming the console because they are often not actionable except for lib authors manualPropTypeWarningCount < 3 ) { warning( false, 'You are manually calling a React.PropTypes validation ' + 'function for the `%s` prop on `%s`. This is deprecated ' + 'and will throw in the standalone `prop-types` package. ' + 'You may be seeing this warning due to a third-party PropTypes ' + 'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.', propFullName, componentName ); manualPropTypeCallCache[cacheKey] = true; manualPropTypeWarningCount++; } } } if (props[propName] == null) { if (isRequired) { if (props[propName] === null) { return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.')); } return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.')); } 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, secret) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== expectedType) { // `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 PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.')); } return null; } return createChainableTypeChecker(validate); } function createAnyTypeChecker() { return createChainableTypeChecker(emptyFunction.thatReturnsNull); } function createArrayOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.'); } var propValue = props[propName]; if (!Array.isArray(propValue)) { var propType = getPropType(propValue); return new PropTypeError('Invalid ' + location + ' `' + 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 + ']', ReactPropTypesSecret); if (error instanceof Error) { return error; } } return null; } return createChainableTypeChecker(validate); } function createElementTypeChecker() { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; if (!isValidElement(propValue)) { var propType = getPropType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` 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 expectedClassName = expectedClass.name || ANONYMOUS; var actualClassName = getClassName(props[propName]); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.')); } return null; } return createChainableTypeChecker(validate); } function createEnumTypeChecker(expectedValues) { if (!Array.isArray(expectedValues)) { false ? warning(false, 'Invalid argument supplied to oneOf, expected an instance of array.') : void 0; return emptyFunction.thatReturnsNull; } function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; for (var i = 0; i < expectedValues.length; i++) { if (is(propValue, expectedValues[i])) { return null; } } var valuesString = JSON.stringify(expectedValues); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.')); } return createChainableTypeChecker(validate); } function createObjectOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.'); } var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + 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, ReactPropTypesSecret); if (error instanceof Error) { return error; } } } return null; } return createChainableTypeChecker(validate); } function createUnionTypeChecker(arrayOfTypeCheckers) { if (!Array.isArray(arrayOfTypeCheckers)) { false ? warning(false, 'Invalid argument supplied to oneOfType, expected an instance of array.') : void 0; return emptyFunction.thatReturnsNull; } for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (typeof checker !== 'function') { warning( false, 'Invalid argument supplid to oneOfType. Expected an array of check functions, but ' + 'received %s at index %s.', getPostfixForTypeWarning(checker), i ); return emptyFunction.thatReturnsNull; } } 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, ReactPropTypesSecret) == null) { return null; } } return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.')); } return createChainableTypeChecker(validate); } function createNodeChecker() { function validate(props, propName, componentName, location, propFullName) { if (!isNode(props[propName])) { return new PropTypeError('Invalid ' + location + ' `' + 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') { return new PropTypeError('Invalid ' + location + ' `' + 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, ReactPropTypesSecret); 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 || 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; } } function isSymbol(propType, propValue) { // Native Symbol. if (propType === 'symbol') { return true; } // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol' if (propValue['@@toStringTag'] === 'Symbol') { return true; } // Fallback for non-spec compliant Symbols which are polyfilled. if (typeof Symbol === 'function' && propValue instanceof Symbol) { return true; } 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'; } if (isSymbol(propType, propValue)) { return 'symbol'; } return propType; } // This handles more types than `getPropType`. Only used for error messages. // See `createPrimitiveTypeChecker`. function getPreciseType(propValue) { if (typeof propValue === 'undefined' || propValue === null) { return '' + propValue; } var propType = getPropType(propValue); if (propType === 'object') { if (propValue instanceof Date) { return 'date'; } else if (propValue instanceof RegExp) { return 'regexp'; } } return propType; } // Returns a string that is postfixed to a warning about an invalid type. // For example, "undefined" or "of type array" function getPostfixForTypeWarning(value) { var type = getPreciseType(value); switch (type) { case 'array': case 'object': return 'an ' + type; case 'boolean': case 'date': case 'regexp': return 'a ' + type; default: return type; } } // Returns class name of the object, if any. function getClassName(propValue) { if (!propValue.constructor || !propValue.constructor.name) { return ANONYMOUS; } return propValue.constructor.name; } ReactPropTypes.checkPropTypes = checkPropTypes; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; /***/ }), /* 26 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; module.exports = ReactPropTypesSecret; /***/ }), /* 27 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; if (false) { var invariant = require('fbjs/lib/invariant'); var warning = require('fbjs/lib/warning'); var ReactPropTypesSecret = require('./lib/ReactPropTypesSecret'); var loggedTypeFailures = {}; } /** * Assert that the values match with the type specs. * Error messages are memorized and will only be shown once. * * @param {object} typeSpecs Map of name to a ReactPropType * @param {object} values Runtime values that need to be type-checked * @param {string} location e.g. "prop", "context", "child context" * @param {string} componentName Name of the component for error messages. * @param {?Function} getStack Returns the component stack. * @private */ function checkPropTypes(typeSpecs, values, location, componentName, getStack) { if (false) { for (var typeSpecName in typeSpecs) { if (typeSpecs.hasOwnProperty(typeSpecName)) { 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. invariant(typeof typeSpecs[typeSpecName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', componentName || 'React class', location, typeSpecName); error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret); } catch (ex) { error = ex; } 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', location, typeSpecName, typeof error); 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 stack = getStack ? getStack() : ''; warning(false, 'Failed %s type: %s%s', location, error.message, stack != null ? stack : ''); } } } } } module.exports = checkPropTypes; /***/ }), /* 28 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; module.exports = '15.6.1'; /***/ }), /* 29 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _require = __webpack_require__(5), Component = _require.Component; var _require2 = __webpack_require__(16), isValidElement = _require2.isValidElement; var ReactNoopUpdateQueue = __webpack_require__(7); var factory = __webpack_require__(30); module.exports = factory(Component, isValidElement, ReactNoopUpdateQueue); /***/ }), /* 30 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(4); var emptyObject = __webpack_require__(11); var _invariant = __webpack_require__(12); if (false) { var warning = require('fbjs/lib/warning'); } var MIXINS_KEY = 'mixins'; // Helper function to allow the creation of anonymous functions which do not // have .name set to the name of the variable being assigned to. function identity(fn) { return fn; } var ReactPropTypeLocationNames; if (false) { ReactPropTypeLocationNames = { prop: 'prop', context: 'context', childContext: 'child context' }; } else { ReactPropTypeLocationNames = {}; } function factory(ReactComponent, isValidElement, ReactNoopUpdateQueue) { /** * Policies that describe methods in `ReactClassInterface`. */ var injectedMixins = []; /** * Composite components are higher-level components that compose other composite * or host 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
Hello World
; * } * }); * * 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: '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: 'DEFINE_MANY', /** * Definition of prop types for this component. * * @type {object} * @optional */ propTypes: 'DEFINE_MANY', /** * Definition of context types for this component. * * @type {object} * @optional */ contextTypes: 'DEFINE_MANY', /** * Definition of context types this component sets for its children. * * @type {object} * @optional */ childContextTypes: '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: '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: 'DEFINE_MANY_MERGED', /** * @return {object} * @optional */ getChildContext: '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
Hello, {name}!
; * } * * @return {ReactComponent} * @required */ render: '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: '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: '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: '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: '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: '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: '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: '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: '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 (false) { validateTypeDef(Constructor, childContextTypes, 'childContext'); } Constructor.childContextTypes = _assign( {}, Constructor.childContextTypes, childContextTypes ); }, contextTypes: function(Constructor, contextTypes) { if (false) { validateTypeDef(Constructor, contextTypes, '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 (false) { validateTypeDef(Constructor, propTypes, 'prop'); } Constructor.propTypes = _assign({}, Constructor.propTypes, propTypes); }, statics: function(Constructor, statics) { mixStaticSpecIntoComponent(Constructor, statics); }, autobind: function() {} }; 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 only in __DEV__ if (false) { 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 ); } } } } function validateMethodOverride(isAlreadyDefined, name) { var specPolicy = ReactClassInterface.hasOwnProperty(name) ? ReactClassInterface[name] : null; // Disallow overriding of base class methods unless explicitly allowed. if (ReactClassMixin.hasOwnProperty(name)) { _invariant( specPolicy === 'OVERRIDE_BASE', 'ReactClassInterface: You are attempting to override ' + '`%s` from your class specification. Ensure that your method names ' + 'do not overlap with React methods.', name ); } // Disallow defining methods more than once unless explicitly allowed. if (isAlreadyDefined) { _invariant( specPolicy === 'DEFINE_MANY' || specPolicy === 'DEFINE_MANY_MERGED', 'ReactClassInterface: You are attempting to define ' + '`%s` on your component more than once. This conflict may be due ' + 'to a mixin.', name ); } } /** * Mixin helper which handles policy validation and reserved * specification keys when building React classes. */ function mixSpecIntoComponent(Constructor, spec) { if (!spec) { if (false) { var typeofSpec = typeof spec; var isMixinValid = typeofSpec === 'object' && spec !== null; if (process.env.NODE_ENV !== 'production') { warning( isMixinValid, "%s: You're attempting to include a mixin that is either null " + 'or not an object. Check the mixins included by the component, ' + 'as well as any mixins they include themselves. ' + 'Expected object but got %s.', Constructor.displayName || 'ReactClass', spec === null ? null : typeofSpec ); } } return; } _invariant( typeof spec !== 'function', "ReactClass: You're attempting to " + 'use a component class or function as a mixin. Instead, just use a ' + 'regular object.' ); _invariant( !isValidElement(spec), "ReactClass: You're attempting to " + 'use a component as a mixin. Instead, just use a regular object.' ); var proto = Constructor.prototype; var autoBindPairs = proto.__reactAutoBindPairs; // 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]; var isAlreadyDefined = proto.hasOwnProperty(name); validateMethodOverride(isAlreadyDefined, 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 isFunction = typeof property === 'function'; var shouldAutoBind = isFunction && !isReactClassMethod && !isAlreadyDefined && spec.autobind !== false; if (shouldAutoBind) { autoBindPairs.push(name, property); proto[name] = property; } else { if (isAlreadyDefined) { var specPolicy = ReactClassInterface[name]; // These cases should already be caught by validateMethodOverride. _invariant( isReactClassMethod && (specPolicy === 'DEFINE_MANY_MERGED' || specPolicy === 'DEFINE_MANY'), 'ReactClass: Unexpected spec policy %s for key %s ' + 'when mixing in component specs.', specPolicy, name ); // For methods which are defined more than once, call the existing // methods before calling the new property, merging if appropriate. if (specPolicy === 'DEFINE_MANY_MERGED') { proto[name] = createMergedResultFunction(proto[name], property); } else if (specPolicy === 'DEFINE_MANY') { proto[name] = createChainedFunction(proto[name], property); } } else { proto[name] = property; if (false) { // 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; _invariant( !isReserved, '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 ); var isInherited = name in Constructor; _invariant( !isInherited, 'ReactClass: You are attempting to define ' + '`%s` on your component more than once. This conflict may be ' + 'due to a mixin.', name ); 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) { _invariant( one && two && typeof one === 'object' && typeof two === 'object', 'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.' ); for (var key in two) { if (two.hasOwnProperty(key)) { _invariant( one[key] === undefined, '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 ); 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 (false) { boundMethod.__reactBoundContext = component; boundMethod.__reactBoundMethod = method; boundMethod.__reactBoundArguments = null; var componentName = component.constructor.displayName; var _bind = boundMethod.bind; 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) { if (process.env.NODE_ENV !== 'production') { warning( false, 'bind(): React component methods may only be bound to the ' + 'component instance. See %s', componentName ); } } else if (!args.length) { if (process.env.NODE_ENV !== '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 ); } return boundMethod; } var reboundMethod = _bind.apply(boundMethod, arguments); reboundMethod.__reactBoundContext = component; reboundMethod.__reactBoundMethod = method; reboundMethod.__reactBoundArguments = args; return reboundMethod; }; } return boundMethod; } /** * Binds all auto-bound methods in a component. * * @param {object} component Component whose method is going to be bound. */ function bindAutoBindMethods(component) { var pairs = component.__reactAutoBindPairs; for (var i = 0; i < pairs.length; i += 2) { var autoBindKey = pairs[i]; var method = pairs[i + 1]; component[autoBindKey] = bindAutoBindMethod(component, method); } } var IsMountedPreMixin = { componentDidMount: function() { this.__isMounted = true; } }; var IsMountedPostMixin = { componentWillUnmount: function() { this.__isMounted = false; } }; /** * 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, callback); }, /** * Checks whether or not this composite component is mounted. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function() { if (false) { warning( this.__didWarnIsMounted, '%s: isMounted is deprecated. Instead, make sure to clean up ' + 'subscriptions and pending requests in componentWillUnmount to ' + 'prevent memory leaks.', (this.constructor && this.constructor.displayName) || this.name || 'Component' ); this.__didWarnIsMounted = true; } return !!this.__isMounted; } }; var ReactClassComponent = function() {}; _assign( ReactClassComponent.prototype, ReactComponent.prototype, ReactClassMixin ); /** * Creates a composite component class given a class specification. * See https://facebook.github.io/react/docs/top-level-api.html#react.createclass * * @param {object} spec Class specification (which must define `render`). * @return {function} Component constructor function. * @public */ function createClass(spec) { // To keep our warnings more understandable, we'll use a little hack here to // ensure that Constructor.name !== 'Constructor'. This makes sure we don't // unnecessarily identify a class without displayName as 'Constructor'. var Constructor = identity(function(props, context, updater) { // This constructor gets overridden by mocks. The argument is used // by mocks to assert on what gets mounted. if (false) { warning( this instanceof Constructor, 'Something is calling a React component directly. Use a factory or ' + 'JSX instead. See: https://fb.me/react-legacyfactory' ); } // Wire up auto-binding if (this.__reactAutoBindPairs.length) { 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 (false) { // We allow auto-mocks to proceed as if they're returning null. if ( initialState === undefined && this.getInitialState._isMockFunction ) { // This is probably bad practice. Consider warning here and // deprecating this convenience. initialState = null; } } _invariant( typeof initialState === 'object' && !Array.isArray(initialState), '%s.getInitialState(): must return an object or null', Constructor.displayName || 'ReactCompositeComponent' ); this.state = initialState; }); Constructor.prototype = new ReactClassComponent(); Constructor.prototype.constructor = Constructor; Constructor.prototype.__reactAutoBindPairs = []; injectedMixins.forEach(mixSpecIntoComponent.bind(null, Constructor)); mixSpecIntoComponent(Constructor, IsMountedPreMixin); mixSpecIntoComponent(Constructor, spec); mixSpecIntoComponent(Constructor, IsMountedPostMixin); // Initialize the defaultProps property after all mixins have been merged. if (Constructor.getDefaultProps) { Constructor.defaultProps = Constructor.getDefaultProps(); } if (false) { // 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 = {}; } } _invariant( Constructor.prototype.render, 'createClass(...): Class specification must implement a `render` method.' ); if (false) { 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' ); warning( !Constructor.prototype.componentWillRecieveProps, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', spec.displayName || 'A component' ); } // 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; } return createClass; } module.exports = factory; /***/ }), /* 31 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(6); var ReactElement = __webpack_require__(16); var invariant = __webpack_require__(12); /** * Returns the first child in a collection of children and verifies that there * is only one child in the collection. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.only * * 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 {ReactElement} The first and only `ReactElement` contained in the * structure. */ function onlyChild(children) { !ReactElement.isValidElement(children) ? false ? invariant(false, 'React.Children.only expected to receive a single React element child.') : _prodInvariant('143') : void 0; return children; } module.exports = onlyChild; /***/ }), /* 32 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; module.exports = __webpack_require__(33); /***/ }), /* 33 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ /* globals __REACT_DEVTOOLS_GLOBAL_HOOK__*/ 'use strict'; var ReactDOMComponentTree = __webpack_require__(34); var ReactDefaultInjection = __webpack_require__(38); var ReactMount = __webpack_require__(162); var ReactReconciler = __webpack_require__(59); var ReactUpdates = __webpack_require__(56); var ReactVersion = __webpack_require__(167); var findDOMNode = __webpack_require__(168); var getHostComponentFromComposite = __webpack_require__(169); var renderSubtreeIntoContainer = __webpack_require__(170); var warning = __webpack_require__(8); ReactDefaultInjection.inject(); var ReactDOM = { findDOMNode: findDOMNode, render: ReactMount.render, unmountComponentAtNode: ReactMount.unmountComponentAtNode, version: ReactVersion, /* eslint-disable camelcase */ unstable_batchedUpdates: ReactUpdates.batchedUpdates, unstable_renderSubtreeIntoContainer: renderSubtreeIntoContainer /* eslint-enable camelcase */ }; // Inject the runtime into a devtools global hook regardless of browser. // Allows for debugging when the hook is injected on the page. if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject === 'function') { __REACT_DEVTOOLS_GLOBAL_HOOK__.inject({ ComponentTree: { getClosestInstanceFromNode: ReactDOMComponentTree.getClosestInstanceFromNode, getNodeFromInstance: function (inst) { // inst is an internal instance (but could be a composite) if (inst._renderedComponent) { inst = getHostComponentFromComposite(inst); } if (inst) { return ReactDOMComponentTree.getNodeFromInstance(inst); } else { return null; } } }, Mount: ReactMount, Reconciler: ReactReconciler }); } if (false) { var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment'); 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) { // Firefox does not have the issue with devtools loaded over file:// var showFileUrlMessage = window.location.protocol.indexOf('http') === -1 && navigator.userAgent.indexOf('Firefox') === -1; console.debug('Download the React DevTools ' + (showFileUrlMessage ? 'and use an HTTP server (instead of a file: URL) ' : '') + 'for a better development experience: ' + 'https://fb.me/react-devtools'); } } var testFunc = function testFn() {}; process.env.NODE_ENV !== 'production' ? warning((testFunc.name || testFunc.toString()).indexOf('testFn') !== -1, "It looks like you're using a minified copy of the development build " + 'of React. When deploying React apps to production, make sure to use ' + 'the production build which skips development warnings and is faster. ' + 'See https://fb.me/react-minification for more details.') : void 0; // 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; process.env.NODE_ENV !== 'production' ? warning(!ieCompatibilityMode, 'Internet Explorer is running in compatibility mode; please add the ' + 'following tag to your HTML to prevent this from happening: ' + '') : void 0; 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.trim]; for (var i = 0; i < expectedFeatures.length; i++) { if (!expectedFeatures[i]) { process.env.NODE_ENV !== 'production' ? warning(false, 'One or more ES5 shims expected by React are not available: ' + 'https://fb.me/react-warning-polyfills') : void 0; break; } } } } if (false) { var ReactInstrumentation = require('./ReactInstrumentation'); var ReactDOMUnknownPropertyHook = require('./ReactDOMUnknownPropertyHook'); var ReactDOMNullInputValuePropHook = require('./ReactDOMNullInputValuePropHook'); var ReactDOMInvalidARIAHook = require('./ReactDOMInvalidARIAHook'); ReactInstrumentation.debugTool.addHook(ReactDOMUnknownPropertyHook); ReactInstrumentation.debugTool.addHook(ReactDOMNullInputValuePropHook); ReactInstrumentation.debugTool.addHook(ReactDOMInvalidARIAHook); } module.exports = ReactDOM; /***/ }), /* 34 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(35); var DOMProperty = __webpack_require__(36); var ReactDOMComponentFlags = __webpack_require__(37); var invariant = __webpack_require__(12); var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME; var Flags = ReactDOMComponentFlags; var internalInstanceKey = '__reactInternalInstance$' + Math.random().toString(36).slice(2); /** * Check if a given node should be cached. */ function shouldPrecacheNode(node, nodeID) { return node.nodeType === 1 && node.getAttribute(ATTR_NAME) === String(nodeID) || node.nodeType === 8 && node.nodeValue === ' react-text: ' + nodeID + ' ' || node.nodeType === 8 && node.nodeValue === ' react-empty: ' + nodeID + ' '; } /** * Drill down (through composites and empty components) until we get a host or * host text component. * * This is pretty polymorphic but unavoidable with the current structure we have * for `_renderedChildren`. */ function getRenderedHostOrTextFromComponent(component) { var rendered; while (rendered = component._renderedComponent) { component = rendered; } return component; } /** * Populate `_hostNode` on the rendered host/text component with the given * DOM node. The passed `inst` can be a composite. */ function precacheNode(inst, node) { var hostInst = getRenderedHostOrTextFromComponent(inst); hostInst._hostNode = node; node[internalInstanceKey] = hostInst; } function uncacheNode(inst) { var node = inst._hostNode; if (node) { delete node[internalInstanceKey]; inst._hostNode = null; } } /** * Populate `_hostNode` on each child of `inst`, assuming that the children * match up with the DOM (element) children of `node`. * * We cache entire levels at once to avoid an n^2 problem where we access the * children of a node sequentially and have to walk from the start to our target * node every time. * * Since we update `_renderedChildren` and the actual DOM at (slightly) * different times, we could race here and see a newer `_renderedChildren` than * the DOM nodes we see. To avoid this, ReactMultiChild calls * `prepareToManageChildren` before we change `_renderedChildren`, at which * time the container's child nodes are always cached (until it unmounts). */ function precacheChildNodes(inst, node) { if (inst._flags & Flags.hasCachedChildNodes) { return; } var children = inst._renderedChildren; var childNode = node.firstChild; outer: for (var name in children) { if (!children.hasOwnProperty(name)) { continue; } var childInst = children[name]; var childID = getRenderedHostOrTextFromComponent(childInst)._domID; if (childID === 0) { // We're currently unmounting this child in ReactMultiChild; skip it. continue; } // We assume the child nodes are in the same order as the child instances. for (; childNode !== null; childNode = childNode.nextSibling) { if (shouldPrecacheNode(childNode, childID)) { precacheNode(childInst, childNode); continue outer; } } // We reached the end of the DOM children without finding an ID match. true ? false ? invariant(false, 'Unable to find element with ID %s.', childID) : _prodInvariant('32', childID) : void 0; } inst._flags |= Flags.hasCachedChildNodes; } /** * Given a DOM node, return the closest ReactDOMComponent or * ReactDOMTextComponent instance ancestor. */ function getClosestInstanceFromNode(node) { if (node[internalInstanceKey]) { return node[internalInstanceKey]; } // Walk up the tree until we find an ancestor whose instance we have cached. var parents = []; while (!node[internalInstanceKey]) { parents.push(node); if (node.parentNode) { node = node.parentNode; } else { // Top of the tree. This node must not be part of a React tree (or is // unmounted, potentially). return null; } } var closest; var inst; for (; node && (inst = node[internalInstanceKey]); node = parents.pop()) { closest = inst; if (parents.length) { precacheChildNodes(inst, node); } } return closest; } /** * Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent * instance, or null if the node was not rendered by this React. */ function getInstanceFromNode(node) { var inst = getClosestInstanceFromNode(node); if (inst != null && inst._hostNode === node) { return inst; } else { return null; } } /** * Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding * DOM node. */ function getNodeFromInstance(inst) { // Without this first invariant, passing a non-DOM-component triggers the next // invariant for a missing parent, which is super confusing. !(inst._hostNode !== undefined) ? false ? invariant(false, 'getNodeFromInstance: Invalid argument.') : _prodInvariant('33') : void 0; if (inst._hostNode) { return inst._hostNode; } // Walk up the tree until we find an ancestor whose DOM node we have cached. var parents = []; while (!inst._hostNode) { parents.push(inst); !inst._hostParent ? false ? invariant(false, 'React DOM tree root should always have a node reference.') : _prodInvariant('34') : void 0; inst = inst._hostParent; } // Now parents contains each ancestor that does *not* have a cached native // node, and `inst` is the deepest ancestor that does. for (; parents.length; inst = parents.pop()) { precacheChildNodes(inst, inst._hostNode); } return inst._hostNode; } var ReactDOMComponentTree = { getClosestInstanceFromNode: getClosestInstanceFromNode, getInstanceFromNode: getInstanceFromNode, getNodeFromInstance: getNodeFromInstance, precacheChildNodes: precacheChildNodes, precacheNode: precacheNode, uncacheNode: uncacheNode }; module.exports = ReactDOMComponentTree; /***/ }), /* 35 */ 6, /* 36 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(35); var invariant = __webpack_require__(12); 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_PROPERTY: 0x1, HAS_BOOLEAN_VALUE: 0x4, HAS_NUMERIC_VALUE: 0x8, HAS_POSITIVE_NUMERIC_VALUE: 0x10 | 0x8, HAS_OVERLOADED_BOOLEAN_VALUE: 0x20, /** * 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) ? false ? 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) : _prodInvariant('48', propName) : void 0; var lowerCased = propName.toLowerCase(); var propConfig = Properties[propName]; var propertyInfo = { attributeName: lowerCased, attributeNamespace: null, propertyName: propName, mutationMethod: null, mustUseProperty: checkMask(propConfig, Injection.MUST_USE_PROPERTY), 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.hasBooleanValue + propertyInfo.hasNumericValue + propertyInfo.hasOverloadedBooleanValue <= 1) ? false ? invariant(false, 'DOMProperty: Value can be one of boolean, overloaded boolean, or numeric value, but not a combination: %s', propName) : _prodInvariant('50', propName) : void 0; if (false) { DOMProperty.getPossibleStandardName[lowerCased] = propName; } if (DOMAttributeNames.hasOwnProperty(propName)) { var attributeName = DOMAttributeNames[propName]; propertyInfo.attributeName = attributeName; if (false) { 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; } } }; /* eslint-disable max-len */ var ATTRIBUTE_NAME_START_CHAR = ':A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD'; /* eslint-enable max-len */ /** * 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', ROOT_ATTRIBUTE_NAME: 'data-reactroot', ATTRIBUTE_NAME_START_CHAR: ATTRIBUTE_NAME_START_CHAR, ATTRIBUTE_NAME_CHAR: ATTRIBUTE_NAME_START_CHAR + '\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040', /** * 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. * mustUseProperty: * Whether the property must be accessed and mutated as an object property. * 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__. * * autofocus is predefined, because adding it to the property whitelist * causes unintended side effects. * * @type {Object} */ getPossibleStandardName: false ? { autofocus: 'autoFocus' } : 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; }, injection: DOMPropertyInjection }; module.exports = DOMProperty; /***/ }), /* 37 */ /***/ (function(module, exports) { /** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ReactDOMComponentFlags = { hasCachedChildNodes: 1 << 0 }; module.exports = ReactDOMComponentFlags; /***/ }), /* 38 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ARIADOMPropertyConfig = __webpack_require__(39); var BeforeInputEventPlugin = __webpack_require__(40); var ChangeEventPlugin = __webpack_require__(55); var DefaultEventPluginOrder = __webpack_require__(68); var EnterLeaveEventPlugin = __webpack_require__(69); var HTMLDOMPropertyConfig = __webpack_require__(74); var ReactComponentBrowserEnvironment = __webpack_require__(75); var ReactDOMComponent = __webpack_require__(88); var ReactDOMComponentTree = __webpack_require__(34); var ReactDOMEmptyComponent = __webpack_require__(133); var ReactDOMTreeTraversal = __webpack_require__(134); var ReactDOMTextComponent = __webpack_require__(135); var ReactDefaultBatchingStrategy = __webpack_require__(136); var ReactEventListener = __webpack_require__(137); var ReactInjection = __webpack_require__(140); var ReactReconcileTransaction = __webpack_require__(141); var SVGDOMPropertyConfig = __webpack_require__(149); var SelectEventPlugin = __webpack_require__(150); var SimpleEventPlugin = __webpack_require__(151); 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.EventPluginUtils.injectComponentTree(ReactDOMComponentTree); ReactInjection.EventPluginUtils.injectTreeTraversal(ReactDOMTreeTraversal); /** * 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.HostComponent.injectGenericComponentClass(ReactDOMComponent); ReactInjection.HostComponent.injectTextComponentClass(ReactDOMTextComponent); ReactInjection.DOMProperty.injectDOMPropertyConfig(ARIADOMPropertyConfig); ReactInjection.DOMProperty.injectDOMPropertyConfig(HTMLDOMPropertyConfig); ReactInjection.DOMProperty.injectDOMPropertyConfig(SVGDOMPropertyConfig); ReactInjection.EmptyComponent.injectEmptyComponentFactory(function (instantiate) { return new ReactDOMEmptyComponent(instantiate); }); ReactInjection.Updates.injectReconcileTransaction(ReactReconcileTransaction); ReactInjection.Updates.injectBatchingStrategy(ReactDefaultBatchingStrategy); ReactInjection.Component.injectEnvironment(ReactComponentBrowserEnvironment); } module.exports = { inject: inject }; /***/ }), /* 39 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ARIADOMPropertyConfig = { Properties: { // Global States and Properties 'aria-current': 0, // state 'aria-details': 0, 'aria-disabled': 0, // state 'aria-hidden': 0, // state 'aria-invalid': 0, // state 'aria-keyshortcuts': 0, 'aria-label': 0, 'aria-roledescription': 0, // Widget Attributes 'aria-autocomplete': 0, 'aria-checked': 0, 'aria-expanded': 0, 'aria-haspopup': 0, 'aria-level': 0, 'aria-modal': 0, 'aria-multiline': 0, 'aria-multiselectable': 0, 'aria-orientation': 0, 'aria-placeholder': 0, 'aria-pressed': 0, 'aria-readonly': 0, 'aria-required': 0, 'aria-selected': 0, 'aria-sort': 0, 'aria-valuemax': 0, 'aria-valuemin': 0, 'aria-valuenow': 0, 'aria-valuetext': 0, // Live Region Attributes 'aria-atomic': 0, 'aria-busy': 0, 'aria-live': 0, 'aria-relevant': 0, // Drag-and-Drop Attributes 'aria-dropeffect': 0, 'aria-grabbed': 0, // Relationship Attributes 'aria-activedescendant': 0, 'aria-colcount': 0, 'aria-colindex': 0, 'aria-colspan': 0, 'aria-controls': 0, 'aria-describedby': 0, 'aria-errormessage': 0, 'aria-flowto': 0, 'aria-labelledby': 0, 'aria-owns': 0, 'aria-posinset': 0, 'aria-rowcount': 0, 'aria-rowindex': 0, 'aria-rowspan': 0, 'aria-setsize': 0 }, DOMAttributeNames: {}, DOMPropertyNames: {} }; module.exports = ARIADOMPropertyConfig; /***/ }), /* 40 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var EventPropagators = __webpack_require__(41); var ExecutionEnvironment = __webpack_require__(48); var FallbackCompositionState = __webpack_require__(49); var SyntheticCompositionEvent = __webpack_require__(52); var SyntheticInputEvent = __webpack_require__(54); 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); // Events and their corresponding property names. var eventTypes = { beforeInput: { phasedRegistrationNames: { bubbled: 'onBeforeInput', captured: 'onBeforeInputCapture' }, dependencies: ['topCompositionEnd', 'topKeyPress', 'topTextInput', 'topPaste'] }, compositionEnd: { phasedRegistrationNames: { bubbled: 'onCompositionEnd', captured: 'onCompositionEndCapture' }, dependencies: ['topBlur', 'topCompositionEnd', 'topKeyDown', 'topKeyPress', 'topKeyUp', 'topMouseDown'] }, compositionStart: { phasedRegistrationNames: { bubbled: 'onCompositionStart', captured: 'onCompositionStartCapture' }, dependencies: ['topBlur', 'topCompositionStart', 'topKeyDown', 'topKeyPress', 'topKeyUp', 'topMouseDown'] }, compositionUpdate: { phasedRegistrationNames: { bubbled: 'onCompositionUpdate', captured: 'onCompositionUpdateCapture' }, dependencies: ['topBlur', 'topCompositionUpdate', 'topKeyDown', 'topKeyPress', 'topKeyUp', '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 'topCompositionStart': return eventTypes.compositionStart; case 'topCompositionEnd': return eventTypes.compositionEnd; case '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 === '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 'topKeyUp': // Command keys insert or clear IME input. return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1; case 'topKeyDown': // Expect IME keyCode on each keydown. If we get any other // code we must have exited earlier. return nativeEvent.keyCode !== START_KEYCODE; case 'topKeyPress': case 'topMouseDown': case '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; /** * @return {?object} A SyntheticCompositionEvent. */ function extractCompositionEvent(topLevelType, targetInst, 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(nativeEventTarget); } else if (eventType === eventTypes.compositionEnd) { if (currentComposition) { fallbackData = currentComposition.getData(); } } } var event = SyntheticCompositionEvent.getPooled(eventType, targetInst, 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 'topCompositionEnd': return getDataFromCustomEvent(nativeEvent); case '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 '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 composition event is available, we extract a string only at // compositionevent, otherwise extract it at fallback events. if (currentComposition) { if (topLevelType === 'topCompositionEnd' || !canUseCompositionEvent && isFallbackCompositionEnd(topLevelType, nativeEvent)) { var chars = currentComposition.getData(); FallbackCompositionState.release(currentComposition); currentComposition = null; return chars; } return null; } switch (topLevelType) { case '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 '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 'topCompositionEnd': return useFallbackCompositionData ? null : nativeEvent.data; default: return null; } } /** * Extract a SyntheticInputEvent for `beforeInput`, based on either native * `textInput` or fallback behavior. * * @return {?object} A SyntheticInputEvent. */ function extractBeforeInputEvent(topLevelType, targetInst, 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, targetInst, 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, extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { return [extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget), extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget)]; } }; module.exports = BeforeInputEventPlugin; /***/ }), /* 41 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var EventPluginHub = __webpack_require__(42); var EventPluginUtils = __webpack_require__(44); var accumulateInto = __webpack_require__(46); var forEachAccumulated = __webpack_require__(47); var warning = __webpack_require__(8); 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(inst, event, propagationPhase) { var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase]; return getListener(inst, 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(inst, phase, event) { if (false) { process.env.NODE_ENV !== 'production' ? warning(inst, 'Dispatching inst must not be null') : void 0; } var listener = listenerAtPhase(inst, event, phase); if (listener) { event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); event._dispatchInstances = accumulateInto(event._dispatchInstances, inst); } } /** * 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) { EventPluginUtils.traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event); } } /** * Same as `accumulateTwoPhaseDispatchesSingle`, but skips over the targetID. */ function accumulateTwoPhaseDispatchesSingleSkipTarget(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { var targetInst = event._targetInst; var parentInst = targetInst ? EventPluginUtils.getParentInstance(targetInst) : null; EventPluginUtils.traverseTwoPhase(parentInst, 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(inst, ignoredDirection, event) { if (event && event.dispatchConfig.registrationName) { var registrationName = event.dispatchConfig.registrationName; var listener = getListener(inst, registrationName); if (listener) { event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); event._dispatchInstances = accumulateInto(event._dispatchInstances, inst); } } } /** * Accumulates dispatches on an `SyntheticEvent`, but only for the * `dispatchMarker`. * @param {SyntheticEvent} event */ function accumulateDirectDispatchesSingle(event) { if (event && event.dispatchConfig.registrationName) { accumulateDispatches(event._targetInst, null, event); } } function accumulateTwoPhaseDispatches(events) { forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle); } function accumulateTwoPhaseDispatchesSkipTarget(events) { forEachAccumulated(events, accumulateTwoPhaseDispatchesSingleSkipTarget); } function accumulateEnterLeaveDispatches(leave, enter, from, to) { EventPluginUtils.traverseEnterLeave(from, to, 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; /***/ }), /* 42 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(35); var EventPluginRegistry = __webpack_require__(43); var EventPluginUtils = __webpack_require__(44); var ReactErrorUtils = __webpack_require__(45); var accumulateInto = __webpack_require__(46); var forEachAccumulated = __webpack_require__(47); var invariant = __webpack_require__(12); /** * 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); }; var getDictionaryKey = function (inst) { // Prevents V8 performance issue: // https://github.com/facebook/react/pull/7232 return '.' + inst._rootNodeID; }; function isInteractive(tag) { return tag === 'button' || tag === 'input' || tag === 'select' || tag === 'textarea'; } function shouldPreventMouseEvent(name, type, props) { switch (name) { case 'onClick': case 'onClickCapture': case 'onDoubleClick': case 'onDoubleClickCapture': case 'onMouseDown': case 'onMouseDownCapture': case 'onMouseMove': case 'onMouseMoveCapture': case 'onMouseUp': case 'onMouseUpCapture': return !!(props.disabled && isInteractive(type)); default: return false; } } /** * 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 {array} InjectedEventPluginOrder * @public */ injectEventPluginOrder: EventPluginRegistry.injectEventPluginOrder, /** * @param {object} injectedNamesToPlugins Map from names to plugin modules. */ injectEventPluginsByName: EventPluginRegistry.injectEventPluginsByName }, /** * Stores `listener` at `listenerBank[registrationName][key]`. Is idempotent. * * @param {object} inst The instance, which is the source of events. * @param {string} registrationName Name of listener (e.g. `onClick`). * @param {function} listener The callback to store. */ putListener: function (inst, registrationName, listener) { !(typeof listener === 'function') ? false ? invariant(false, 'Expected %s listener to be a function, instead got type %s', registrationName, typeof listener) : _prodInvariant('94', registrationName, typeof listener) : void 0; var key = getDictionaryKey(inst); var bankForRegistrationName = listenerBank[registrationName] || (listenerBank[registrationName] = {}); bankForRegistrationName[key] = listener; var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; if (PluginModule && PluginModule.didPutListener) { PluginModule.didPutListener(inst, registrationName, listener); } }, /** * @param {object} inst The instance, which is the source of events. * @param {string} registrationName Name of listener (e.g. `onClick`). * @return {?function} The stored callback. */ getListener: function (inst, registrationName) { // TODO: shouldPreventMouseEvent is DOM-specific and definitely should not // live here; needs to be moved to a better place soon var bankForRegistrationName = listenerBank[registrationName]; if (shouldPreventMouseEvent(registrationName, inst._currentElement.type, inst._currentElement.props)) { return null; } var key = getDictionaryKey(inst); return bankForRegistrationName && bankForRegistrationName[key]; }, /** * Deletes a listener from the registration bank. * * @param {object} inst The instance, which is the source of events. * @param {string} registrationName Name of listener (e.g. `onClick`). */ deleteListener: function (inst, registrationName) { var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; if (PluginModule && PluginModule.willDeleteListener) { PluginModule.willDeleteListener(inst, registrationName); } var bankForRegistrationName = listenerBank[registrationName]; // TODO: This should never be null -- when is it? if (bankForRegistrationName) { var key = getDictionaryKey(inst); delete bankForRegistrationName[key]; } }, /** * Deletes all listeners for the DOM element with the supplied ID. * * @param {object} inst The instance, which is the source of events. */ deleteAllListeners: function (inst) { var key = getDictionaryKey(inst); for (var registrationName in listenerBank) { if (!listenerBank.hasOwnProperty(registrationName)) { continue; } if (!listenerBank[registrationName][key]) { continue; } var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; if (PluginModule && PluginModule.willDeleteListener) { PluginModule.willDeleteListener(inst, registrationName); } delete listenerBank[registrationName][key]; } }, /** * Allows registered plugins an opportunity to extract events from top-level * native browser events. * * @return {*} An accumulation of synthetic events. * @internal */ extractEvents: function (topLevelType, targetInst, 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, targetInst, 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 ? false ? invariant(false, 'processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented.') : _prodInvariant('95') : void 0; // 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; /***/ }), /* 43 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var _prodInvariant = __webpack_require__(35); var invariant = __webpack_require__(12); /** * 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) ? false ? invariant(false, 'EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `%s`.', pluginName) : _prodInvariant('96', pluginName) : void 0; if (EventPluginRegistry.plugins[pluginIndex]) { continue; } !pluginModule.extractEvents ? false ? invariant(false, 'EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `%s` does not.', pluginName) : _prodInvariant('97', pluginName) : void 0; EventPluginRegistry.plugins[pluginIndex] = pluginModule; var publishedEvents = pluginModule.eventTypes; for (var eventName in publishedEvents) { !publishEventForPlugin(publishedEvents[eventName], pluginModule, eventName) ? false ? invariant(false, 'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.', eventName, pluginName) : _prodInvariant('98', eventName, pluginName) : void 0; } } } /** * 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) ? false ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same event name, `%s`.', eventName) : _prodInvariant('99', eventName) : void 0; 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] ? false ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same registration name, `%s`.', registrationName) : _prodInvariant('100', registrationName) : void 0; EventPluginRegistry.registrationNameModules[registrationName] = pluginModule; EventPluginRegistry.registrationNameDependencies[registrationName] = pluginModule.eventTypes[eventName].dependencies; if (false) { var lowerCasedName = registrationName.toLowerCase(); EventPluginRegistry.possibleRegistrationNames[lowerCasedName] = registrationName; if (registrationName === 'onDoubleClick') { EventPluginRegistry.possibleRegistrationNames.ondblclick = registrationName; } } } /** * 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: {}, /** * Mapping from lowercase registration names to the properly cased version, * used to warn in the case of missing event handlers. Available * only in __DEV__. * @type {Object} */ possibleRegistrationNames: false ? {} : null, // Trust the developer to only use possibleRegistrationNames in __DEV__ /** * 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 ? false ? invariant(false, 'EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React.') : _prodInvariant('101') : void 0; // 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] ? false ? invariant(false, 'EventPluginRegistry: Cannot inject two different event plugins using the same name, `%s`.', pluginName) : _prodInvariant('102', pluginName) : void 0; 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; } if (dispatchConfig.phasedRegistrationNames !== undefined) { // pulling phasedRegistrationNames out of dispatchConfig helps Flow see // that it is not undefined. var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; for (var phase in phasedRegistrationNames) { if (!phasedRegistrationNames.hasOwnProperty(phase)) { continue; } var pluginModule = EventPluginRegistry.registrationNameModules[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]; } } if (false) { var possibleRegistrationNames = EventPluginRegistry.possibleRegistrationNames; for (var lowerCasedName in possibleRegistrationNames) { if (possibleRegistrationNames.hasOwnProperty(lowerCasedName)) { delete possibleRegistrationNames[lowerCasedName]; } } } } }; module.exports = EventPluginRegistry; /***/ }), /* 44 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(35); var ReactErrorUtils = __webpack_require__(45); var invariant = __webpack_require__(12); var warning = __webpack_require__(8); /** * Injected dependencies: */ /** * - `ComponentTree`: [required] Module that can convert between React instances * and actual node references. */ var ComponentTree; var TreeTraversal; var injection = { injectComponentTree: function (Injected) { ComponentTree = Injected; if (false) { process.env.NODE_ENV !== 'production' ? warning(Injected && Injected.getNodeFromInstance && Injected.getInstanceFromNode, 'EventPluginUtils.injection.injectComponentTree(...): Injected ' + 'module is missing getNodeFromInstance or getInstanceFromNode.') : void 0; } }, injectTreeTraversal: function (Injected) { TreeTraversal = Injected; if (false) { process.env.NODE_ENV !== 'production' ? warning(Injected && Injected.isAncestor && Injected.getLowestCommonAncestor, 'EventPluginUtils.injection.injectTreeTraversal(...): Injected ' + 'module is missing isAncestor or getLowestCommonAncestor.') : void 0; } } }; function isEndish(topLevelType) { return topLevelType === 'topMouseUp' || topLevelType === 'topTouchEnd' || topLevelType === 'topTouchCancel'; } function isMoveish(topLevelType) { return topLevelType === 'topMouseMove' || topLevelType === 'topTouchMove'; } function isStartish(topLevelType) { return topLevelType === 'topMouseDown' || topLevelType === 'topTouchStart'; } var validateEventDispatches; if (false) { validateEventDispatches = function (event) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; var listenersIsArr = Array.isArray(dispatchListeners); var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0; var instancesIsArr = Array.isArray(dispatchInstances); var instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0; process.env.NODE_ENV !== 'production' ? warning(instancesIsArr === listenersIsArr && instancesLen === listenersLen, 'EventPluginUtils: Invalid `event`.') : void 0; }; } /** * 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 {*} inst Internal component instance */ function executeDispatch(event, simulated, listener, inst) { var type = event.type || 'unknown-event'; event.currentTarget = EventPluginUtils.getNodeFromInstance(inst); if (simulated) { ReactErrorUtils.invokeGuardedCallbackWithCatch(type, listener, event); } else { ReactErrorUtils.invokeGuardedCallback(type, listener, event); } event.currentTarget = null; } /** * Standard/simple iteration through an event's collected dispatches. */ function executeDispatchesInOrder(event, simulated) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; if (false) { validateEventDispatches(event); } if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; } // Listeners and Instances are two parallel arrays that are always in sync. executeDispatch(event, simulated, dispatchListeners[i], dispatchInstances[i]); } } else if (dispatchListeners) { executeDispatch(event, simulated, dispatchListeners, dispatchInstances); } event._dispatchListeners = null; event._dispatchInstances = 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 dispatchInstances = event._dispatchInstances; if (false) { validateEventDispatches(event); } if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; } // Listeners and Instances are two parallel arrays that are always in sync. if (dispatchListeners[i](event, dispatchInstances[i])) { return dispatchInstances[i]; } } } else if (dispatchListeners) { if (dispatchListeners(event, dispatchInstances)) { return dispatchInstances; } } return null; } /** * @see executeDispatchesInOrderStopAtTrueImpl */ function executeDispatchesInOrderStopAtTrue(event) { var ret = executeDispatchesInOrderStopAtTrueImpl(event); event._dispatchInstances = 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 (false) { validateEventDispatches(event); } var dispatchListener = event._dispatchListeners; var dispatchInstance = event._dispatchInstances; !!Array.isArray(dispatchListener) ? false ? invariant(false, 'executeDirectDispatch(...): Invalid `event`.') : _prodInvariant('103') : void 0; event.currentTarget = dispatchListener ? EventPluginUtils.getNodeFromInstance(dispatchInstance) : null; var res = dispatchListener ? dispatchListener(event) : null; event.currentTarget = null; event._dispatchListeners = null; event._dispatchInstances = 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, getInstanceFromNode: function (node) { return ComponentTree.getInstanceFromNode(node); }, getNodeFromInstance: function (node) { return ComponentTree.getNodeFromInstance(node); }, isAncestor: function (a, b) { return TreeTraversal.isAncestor(a, b); }, getLowestCommonAncestor: function (a, b) { return TreeTraversal.getLowestCommonAncestor(a, b); }, getParentInstance: function (inst) { return TreeTraversal.getParentInstance(inst); }, traverseTwoPhase: function (target, fn, arg) { return TreeTraversal.traverseTwoPhase(target, fn, arg); }, traverseEnterLeave: function (from, to, fn, argFrom, argTo) { return TreeTraversal.traverseEnterLeave(from, to, fn, argFrom, argTo); }, injection: injection }; module.exports = EventPluginUtils; /***/ }), /* 45 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ '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) { try { func(a); } catch (x) { if (caughtError === null) { caughtError = x; } } } 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 (false) { /** * 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.createElement('react'); ReactErrorUtils.invokeGuardedCallback = function (name, func, a) { var boundFunc = func.bind(null, a); 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; /***/ }), /* 46 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var _prodInvariant = __webpack_require__(35); var invariant = __webpack_require__(12); /** * 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) ? false ? invariant(false, 'accumulateInto(...): Accumulated items must not be null or undefined.') : _prodInvariant('30') : void 0; 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). if (Array.isArray(current)) { if (Array.isArray(next)) { current.push.apply(current, next); return current; } current.push(next); return current; } if (Array.isArray(next)) { // A bit too dangerous to mutate `next`. return [current].concat(next); } return [current, next]; } module.exports = accumulateInto; /***/ }), /* 47 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ '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). */ function forEachAccumulated(arr, cb, scope) { if (Array.isArray(arr)) { arr.forEach(cb, scope); } else if (arr) { cb.call(scope, arr); } } module.exports = forEachAccumulated; /***/ }), /* 48 */ /***/ (function(module, exports) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ '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; /***/ }), /* 49 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(4); var PooledClass = __webpack_require__(50); var getTextContentAccessor = __webpack_require__(51); /** * 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; /***/ }), /* 50 */ [443, 35], /* 51 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ExecutionEnvironment = __webpack_require__(48); 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 elements don't support innerText even when
does. contentKey = 'textContent' in document.documentElement ? 'textContent' : 'innerText'; } return contentKey; } module.exports = getTextContentAccessor; /***/ }), /* 52 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var SyntheticEvent = __webpack_require__(53); /** * @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) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticCompositionEvent, CompositionEventInterface); module.exports = SyntheticCompositionEvent; /***/ }), /* 53 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(4); var PooledClass = __webpack_require__(50); var emptyFunction = __webpack_require__(9); var warning = __webpack_require__(8); var didWarnForAddedNewProperty = false; var isProxySupported = typeof Proxy === 'function'; var shouldBeReleasedProperties = ['dispatchConfig', '_targetInst', 'nativeEvent', 'isDefaultPrevented', 'isPropagationStopped', '_dispatchListeners', '_dispatchInstances']; /** * @interface Event * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var EventInterface = { type: null, target: 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 {*} targetInst Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @param {DOMEventTarget} nativeEventTarget Target node. */ function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) { if (false) { // these have a getter/setter for warnings delete this.nativeEvent; delete this.preventDefault; delete this.stopPropagation; } this.dispatchConfig = dispatchConfig; this._targetInst = targetInst; this.nativeEvent = nativeEvent; var Interface = this.constructor.Interface; for (var propName in Interface) { if (!Interface.hasOwnProperty(propName)) { continue; } if (false) { delete this[propName]; // this has a getter/setter for warnings } var normalize = Interface[propName]; if (normalize) { this[propName] = normalize(nativeEvent); } else { if (propName === 'target') { this.target = nativeEventTarget; } 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; return this; } _assign(SyntheticEvent.prototype, { preventDefault: function () { this.defaultPrevented = true; var event = this.nativeEvent; if (!event) { return; } if (event.preventDefault) { event.preventDefault(); // eslint-disable-next-line valid-typeof } else if (typeof event.returnValue !== 'unknown') { event.returnValue = false; } this.isDefaultPrevented = emptyFunction.thatReturnsTrue; }, stopPropagation: function () { var event = this.nativeEvent; if (!event) { return; } if (event.stopPropagation) { event.stopPropagation(); // eslint-disable-next-line valid-typeof } else if (typeof event.cancelBubble !== 'unknown') { // The ChangeEventPlugin registers a "propertychange" event for // IE. This event does not support bubbling or cancelling, and // any references to cancelBubble throw "Member not found". A // typeof check of "unknown" circumvents this issue (and is also // IE specific). 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) { if (false) { Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName])); } else { this[propName] = null; } } for (var i = 0; i < shouldBeReleasedProperties.length; i++) { this[shouldBeReleasedProperties[i]] = null; } if (false) { Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null)); Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', emptyFunction)); Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', emptyFunction)); } } }); SyntheticEvent.Interface = EventInterface; if (false) { if (isProxySupported) { /*eslint-disable no-func-assign */ SyntheticEvent = new Proxy(SyntheticEvent, { construct: function (target, args) { return this.apply(target, Object.create(target.prototype), args); }, apply: function (constructor, that, args) { return new Proxy(constructor.apply(that, args), { set: function (target, prop, value) { if (prop !== 'isPersistent' && !target.constructor.Interface.hasOwnProperty(prop) && shouldBeReleasedProperties.indexOf(prop) === -1) { process.env.NODE_ENV !== 'production' ? warning(didWarnForAddedNewProperty || target.isPersistent(), "This synthetic event is reused for performance reasons. If you're " + "seeing this, you're adding a new property in the synthetic event object. " + 'The property is never released. See ' + 'https://fb.me/react-event-pooling for more information.') : void 0; didWarnForAddedNewProperty = true; } target[prop] = value; return true; } }); } }); /*eslint-enable no-func-assign */ } } /** * Helper to reduce boilerplate when creating subclasses. * * @param {function} Class * @param {?object} Interface */ SyntheticEvent.augmentClass = function (Class, Interface) { var Super = this; var E = function () {}; E.prototype = Super.prototype; var prototype = new E(); _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; /** * Helper to nullify syntheticEvent instance properties when destructing * * @param {object} SyntheticEvent * @param {String} propName * @return {object} defineProperty object */ function getPooledWarningPropertyDefinition(propName, getVal) { var isFunction = typeof getVal === 'function'; return { configurable: true, set: set, get: get }; function set(val) { var action = isFunction ? 'setting the method' : 'setting the property'; warn(action, 'This is effectively a no-op'); return val; } function get() { var action = isFunction ? 'accessing the method' : 'accessing the property'; var result = isFunction ? 'This is a no-op function' : 'This is set to null'; warn(action, result); return getVal; } function warn(action, result) { var warningCondition = false; false ? warning(warningCondition, "This synthetic event is reused for performance reasons. If you're seeing this, " + "you're %s `%s` on a released/nullified synthetic event. %s. " + 'If you must keep the original synthetic event around, use event.persist(). ' + 'See https://fb.me/react-event-pooling for more information.', action, propName, result) : void 0; } } /***/ }), /* 54 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var SyntheticEvent = __webpack_require__(53); /** * @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) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticInputEvent, InputEventInterface); module.exports = SyntheticInputEvent; /***/ }), /* 55 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var EventPluginHub = __webpack_require__(42); var EventPropagators = __webpack_require__(41); var ExecutionEnvironment = __webpack_require__(48); var ReactDOMComponentTree = __webpack_require__(34); var ReactUpdates = __webpack_require__(56); var SyntheticEvent = __webpack_require__(53); var inputValueTracking = __webpack_require__(64); var getEventTarget = __webpack_require__(65); var isEventSupported = __webpack_require__(66); var isTextInputElement = __webpack_require__(67); var eventTypes = { change: { phasedRegistrationNames: { bubbled: 'onChange', captured: 'onChangeCapture' }, dependencies: ['topBlur', 'topChange', 'topClick', 'topFocus', 'topInput', 'topKeyDown', 'topKeyUp', 'topSelectionChange'] } }; function createAndAccumulateChangeEvent(inst, nativeEvent, target) { var event = SyntheticEvent.getPooled(eventTypes.change, inst, nativeEvent, target); event.type = 'change'; EventPropagators.accumulateTwoPhaseDispatches(event); return event; } /** * For IE shims */ var activeElement = null; var activeElementInst = 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') && (!document.documentMode || document.documentMode > 8); } function manualDispatchChangeEvent(nativeEvent) { var event = createAndAccumulateChangeEvent(activeElementInst, nativeEvent, getEventTarget(nativeEvent)); // 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, targetInst) { activeElement = target; activeElementInst = targetInst; activeElement.attachEvent('onchange', manualDispatchChangeEvent); } function stopWatchingForChangeEventIE8() { if (!activeElement) { return; } activeElement.detachEvent('onchange', manualDispatchChangeEvent); activeElement = null; activeElementInst = null; } function getInstIfValueChanged(targetInst, nativeEvent) { var updated = inputValueTracking.updateValueIfChanged(targetInst); var simulated = nativeEvent.simulated === true && ChangeEventPlugin._allowSimulatedPassThrough; if (updated || simulated) { return targetInst; } } function getTargetInstForChangeEvent(topLevelType, targetInst) { if (topLevelType === 'topChange') { return targetInst; } } function handleEventsForChangeEventIE8(topLevelType, target, targetInst) { if (topLevelType === 'topFocus') { // stopWatching() should be a noop here but we call it just in case we // missed a blur event somehow. stopWatchingForChangeEventIE8(); startWatchingForChangeEventIE8(target, targetInst); } else if (topLevelType === '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 IE <=9) 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, targetInst) { activeElement = target; activeElementInst = targetInst; activeElement.attachEvent('onpropertychange', handlePropertyChange); } /** * (For IE <=9) Removes the event listeners from the currently-tracked element, * if any exists. */ function stopWatchingForValueChange() { if (!activeElement) { return; } activeElement.detachEvent('onpropertychange', handlePropertyChange); activeElement = null; activeElementInst = null; } /** * (For IE <=9) 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; } if (getInstIfValueChanged(activeElementInst, nativeEvent)) { manualDispatchChangeEvent(nativeEvent); } } function handleEventsForInputEventPolyfill(topLevelType, target, targetInst) { if (topLevelType === '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(target, targetInst); } else if (topLevelType === 'topBlur') { stopWatchingForValueChange(); } } // For IE8 and IE9. function getTargetInstForInputEventPolyfill(topLevelType, targetInst, nativeEvent) { if (topLevelType === 'topSelectionChange' || topLevelType === 'topKeyUp' || topLevelType === '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. return getInstIfValueChanged(activeElementInst, nativeEvent); } } /** * 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. var nodeName = elem.nodeName; return nodeName && nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio'); } function getTargetInstForClickEvent(topLevelType, targetInst, nativeEvent) { if (topLevelType === 'topClick') { return getInstIfValueChanged(targetInst, nativeEvent); } } function getTargetInstForInputOrChangeEvent(topLevelType, targetInst, nativeEvent) { if (topLevelType === 'topInput' || topLevelType === 'topChange') { return getInstIfValueChanged(targetInst, nativeEvent); } } function handleControlledInputBlur(inst, node) { // TODO: In IE, inst is occasionally null. Why? if (inst == null) { return; } // Fiber and ReactDOM keep wrapper state in separate places var state = inst._wrapperState || node._wrapperState; if (!state || !state.controlled || node.type !== 'number') { return; } // If controlled, assign the value attribute to the current value on blur var value = '' + node.value; if (node.getAttribute('value') !== value) { node.setAttribute('value', value); } } /** * 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, _allowSimulatedPassThrough: true, _isInputEventSupported: isInputEventSupported, extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { var targetNode = targetInst ? ReactDOMComponentTree.getNodeFromInstance(targetInst) : window; var getTargetInstFunc, handleEventFunc; if (shouldUseChangeEvent(targetNode)) { if (doesChangeEventBubble) { getTargetInstFunc = getTargetInstForChangeEvent; } else { handleEventFunc = handleEventsForChangeEventIE8; } } else if (isTextInputElement(targetNode)) { if (isInputEventSupported) { getTargetInstFunc = getTargetInstForInputOrChangeEvent; } else { getTargetInstFunc = getTargetInstForInputEventPolyfill; handleEventFunc = handleEventsForInputEventPolyfill; } } else if (shouldUseClickEvent(targetNode)) { getTargetInstFunc = getTargetInstForClickEvent; } if (getTargetInstFunc) { var inst = getTargetInstFunc(topLevelType, targetInst, nativeEvent); if (inst) { var event = createAndAccumulateChangeEvent(inst, nativeEvent, nativeEventTarget); return event; } } if (handleEventFunc) { handleEventFunc(topLevelType, targetNode, targetInst); } // When blurring, set the value attribute for number inputs if (topLevelType === 'topBlur') { handleControlledInputBlur(targetInst, targetNode); } } }; module.exports = ChangeEventPlugin; /***/ }), /* 56 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(35), _assign = __webpack_require__(4); var CallbackQueue = __webpack_require__(57); var PooledClass = __webpack_require__(50); var ReactFeatureFlags = __webpack_require__(58); var ReactReconciler = __webpack_require__(59); var Transaction = __webpack_require__(63); var invariant = __webpack_require__(12); var dirtyComponents = []; var updateBatchNumber = 0; var asapCallbackQueue = CallbackQueue.getPooled(); var asapEnqueued = false; var batchingStrategy = null; function ensureInjected() { !(ReactUpdates.ReactReconcileTransaction && batchingStrategy) ? false ? invariant(false, 'ReactUpdates: must inject a reconcile transaction class and batching strategy') : _prodInvariant('123') : void 0; } 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( /* useCreateElement */true); } _assign(ReactUpdatesFlushTransaction.prototype, Transaction, { 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.perform.call(this, this.reconcileTransaction.perform, this.reconcileTransaction, method, scope, a); } }); PooledClass.addPoolingTo(ReactUpdatesFlushTransaction); function batchedUpdates(callback, a, b, c, d, e) { ensureInjected(); return 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) ? false ? invariant(false, 'Expected flush transaction\'s stored dirty-components length (%s) to match dirty-components array length (%s).', len, dirtyComponents.length) : _prodInvariant('124', len, dirtyComponents.length) : void 0; // 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); // Any updates enqueued while reconciling must be performed after this entire // batch. Otherwise, if dirtyComponents is [A, B] where A has children B and // C, B could update twice in a single batch if C's render enqueues an update // to B (since B would have already updated, we should skip it, and the only // way we can know to do so is by checking the batch counter). updateBatchNumber++; 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; var markerName; if (ReactFeatureFlags.logTopLevelRenders) { var namedComponent = component; // Duck type TopLevelWrapper. This is probably always true. if (component._currentElement.type.isReactTopLevelWrapper) { namedComponent = component._renderedComponent; } markerName = 'React update: ' + namedComponent.getName(); console.time(markerName); } ReactReconciler.performUpdateIfNecessary(component, transaction.reconcileTransaction, updateBatchNumber); if (markerName) { console.timeEnd(markerName); } 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); } } }; /** * 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 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); if (component._updateBatchNumber == null) { component._updateBatchNumber = updateBatchNumber + 1; } } /** * 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 ? false ? invariant(false, 'ReactUpdates.asap: Can\'t enqueue an asap callback in a context whereupdates are not being batched.') : _prodInvariant('125') : void 0; asapCallbackQueue.enqueue(callback, context); asapEnqueued = true; } var ReactUpdatesInjection = { injectReconcileTransaction: function (ReconcileTransaction) { !ReconcileTransaction ? false ? invariant(false, 'ReactUpdates: must provide a reconcile transaction class') : _prodInvariant('126') : void 0; ReactUpdates.ReactReconcileTransaction = ReconcileTransaction; }, injectBatchingStrategy: function (_batchingStrategy) { !_batchingStrategy ? false ? invariant(false, 'ReactUpdates: must provide a batching strategy') : _prodInvariant('127') : void 0; !(typeof _batchingStrategy.batchedUpdates === 'function') ? false ? invariant(false, 'ReactUpdates: must provide a batchedUpdates() function') : _prodInvariant('128') : void 0; !(typeof _batchingStrategy.isBatchingUpdates === 'boolean') ? false ? invariant(false, 'ReactUpdates: must provide an isBatchingUpdates boolean attribute') : _prodInvariant('129') : void 0; 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; /***/ }), /* 57 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var _prodInvariant = __webpack_require__(35); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var PooledClass = __webpack_require__(50); var invariant = __webpack_require__(12); /** * 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 */ var CallbackQueue = function () { function CallbackQueue(arg) { _classCallCheck(this, CallbackQueue); this._callbacks = null; this._contexts = null; this._arg = arg; } /** * 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 */ CallbackQueue.prototype.enqueue = function enqueue(callback, context) { this._callbacks = this._callbacks || []; this._callbacks.push(callback); this._contexts = this._contexts || []; 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 */ CallbackQueue.prototype.notifyAll = function notifyAll() { var callbacks = this._callbacks; var contexts = this._contexts; var arg = this._arg; if (callbacks && contexts) { !(callbacks.length === contexts.length) ? false ? invariant(false, 'Mismatched list of contexts in callback queue') : _prodInvariant('24') : void 0; this._callbacks = null; this._contexts = null; for (var i = 0; i < callbacks.length; i++) { callbacks[i].call(contexts[i], arg); } callbacks.length = 0; contexts.length = 0; } }; CallbackQueue.prototype.checkpoint = function checkpoint() { return this._callbacks ? this._callbacks.length : 0; }; CallbackQueue.prototype.rollback = function rollback(len) { if (this._callbacks && this._contexts) { this._callbacks.length = len; this._contexts.length = len; } }; /** * Resets the internal queue. * * @internal */ CallbackQueue.prototype.reset = function reset() { this._callbacks = null; this._contexts = null; }; /** * `PooledClass` looks for this. */ CallbackQueue.prototype.destructor = function destructor() { this.reset(); }; return CallbackQueue; }(); module.exports = PooledClass.addPoolingTo(CallbackQueue); /***/ }), /* 58 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var ReactFeatureFlags = { // When true, call console.time() before and .timeEnd() after each top-level // render (both initial renders and updates). Useful when looking at prod-mode // timeline profiles in Chrome, for example. logTopLevelRenders: false }; module.exports = ReactFeatureFlags; /***/ }), /* 59 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ReactRef = __webpack_require__(60); var ReactInstrumentation = __webpack_require__(62); var warning = __webpack_require__(8); /** * 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 {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {?object} the containing host component instance * @param {?object} info about the host container * @return {?string} Rendered markup to be inserted into the DOM. * @final * @internal */ mountComponent: function (internalInstance, transaction, hostParent, hostContainerInfo, context, parentDebugID) // 0 in production and for roots { if (false) { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeforeMountComponent(internalInstance._debugID, internalInstance._currentElement, parentDebugID); } } var markup = internalInstance.mountComponent(transaction, hostParent, hostContainerInfo, context, parentDebugID); if (internalInstance._currentElement && internalInstance._currentElement.ref != null) { transaction.getReactMountReady().enqueue(attachRefs, internalInstance); } if (false) { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onMountComponent(internalInstance._debugID); } } return markup; }, /** * Returns a value that can be passed to * ReactComponentEnvironment.replaceNodeWithMarkup. */ getHostNode: function (internalInstance) { return internalInstance.getHostNode(); }, /** * Releases any resources allocated by `mountComponent`. * * @final * @internal */ unmountComponent: function (internalInstance, safely) { if (false) { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeforeUnmountComponent(internalInstance._debugID); } } ReactRef.detachRefs(internalInstance, internalInstance._currentElement); internalInstance.unmountComponent(safely); if (false) { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onUnmountComponent(internalInstance._debugID); } } }, /** * 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; } if (false) { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeforeUpdateComponent(internalInstance._debugID, nextElement); } } 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); } if (false) { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onUpdateComponent(internalInstance._debugID); } } }, /** * Flush any dirty changes in a component. * * @param {ReactComponent} internalInstance * @param {ReactReconcileTransaction} transaction * @internal */ performUpdateIfNecessary: function (internalInstance, transaction, updateBatchNumber) { if (internalInstance._updateBatchNumber !== updateBatchNumber) { // The component's enqueued batch number should always be the current // batch or the following one. false ? warning(internalInstance._updateBatchNumber == null || internalInstance._updateBatchNumber === updateBatchNumber + 1, 'performUpdateIfNecessary: Unexpected batch number (current %s, ' + 'pending %s)', updateBatchNumber, internalInstance._updateBatchNumber) : void 0; return; } if (false) { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeforeUpdateComponent(internalInstance._debugID, internalInstance._currentElement); } } internalInstance.performUpdateIfNecessary(transaction); if (false) { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onUpdateComponent(internalInstance._debugID); } } } }; module.exports = ReactReconciler; /***/ }), /* 60 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var ReactOwner = __webpack_require__(61); 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 || typeof element !== 'object') { 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 prevRef = null; var prevOwner = null; if (prevElement !== null && typeof prevElement === 'object') { prevRef = prevElement.ref; prevOwner = prevElement._owner; } var nextRef = null; var nextOwner = null; if (nextElement !== null && typeof nextElement === 'object') { nextRef = nextElement.ref; nextOwner = nextElement._owner; } return prevRef !== nextRef || // If owner changes but we have an unchanged function ref, don't update refs typeof nextRef === 'string' && nextOwner !== prevOwner; }; ReactRef.detachRefs = function (instance, element) { if (element === null || typeof element !== 'object') { return; } var ref = element.ref; if (ref != null) { detachRef(ref, instance, element._owner); } }; module.exports = ReactRef; /***/ }), /* 61 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var _prodInvariant = __webpack_require__(35); var invariant = __webpack_require__(12); /** * @param {?object} object * @return {boolean} True if `object` is a valid owner. * @final */ function isValidOwner(object) { return !!(object && typeof object.attachRef === 'function' && typeof object.detachRef === 'function'); } /** * 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 ( *
* *
* ); * }, * 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 = { /** * 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) { !isValidOwner(owner) ? false ? 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).') : _prodInvariant('119') : void 0; 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) { !isValidOwner(owner) ? false ? 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).') : _prodInvariant('120') : void 0; var ownerPublicInstance = owner.getPublicInstance(); // Check that `component`'s owner is still alive and that `component` is still the current ref // because we do not want to detach the ref if another component stole it. if (ownerPublicInstance && ownerPublicInstance.refs[ref] === component.getPublicInstance()) { owner.detachRef(ref); } } }; module.exports = ReactOwner; /***/ }), /* 62 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; // Trust the developer to only use ReactInstrumentation with a __DEV__ check var debugTool = null; if (false) { var ReactDebugTool = require('./ReactDebugTool'); debugTool = ReactDebugTool; } module.exports = { debugTool: debugTool }; /***/ }), /* 63 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var _prodInvariant = __webpack_require__(35); var invariant = __webpack_require__(12); var OBSERVED_ERROR = {}; /** * `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. * *
	 *                       wrappers (injected at creation time)
	 *                                      +        +
	 *                                      |        |
	 *                    +-----------------|--------|--------------+
	 *                    |                 v        |              |
	 *                    |      +---------------+   |              |
	 *                    |   +--|    wrapper1   |---|----+         |
	 *                    |   |  +---------------+   v    |         |
	 *                    |   |          +-------------+  |         |
	 *                    |   |     +----|   wrapper2  |--------+   |
	 *                    |   |     |    +-------------+  |     |   |
	 *                    |   |     |                     |     |   |
	 *                    |   v     v                     v     v   | wrapper
	 *                    | +---+ +---+   +---------+   +---+ +---+ | invariants
	 * perform(anyMethod) | |   | |   |   |         |   |   | |   | | maintained
	 * +----------------->|-|---|-|---|-->|anyMethod|---|---|-|---|-|-------->
	 *                    | |   | |   |   |         |   |   | |   | |
	 *                    | |   | |   |   |         |   |   | |   | |
	 *                    | |   | |   |   |         |   |   | |   | |
	 *                    | +---+ +---+   +---------+   +---+ +---+ |
	 *                    |  initialize                    close    |
	 *                    +-----------------------------------------+
	 * 
* * 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} transactionWrapper Wrapper modules * that implement `initialize` and `close`. * @return {Transaction} Single transaction for reuse in thread. * * @class Transaction */ var TransactionImpl = { /** * 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} Array of transaction wrappers. */ getTransactionWrappers: null, isInTransaction: function () { return !!this._isInTransaction; }, /* eslint-disable space-before-function-paren */ /** * 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) { /* eslint-enable space-before-function-paren */ !!this.isInTransaction() ? false ? invariant(false, 'Transaction.perform(...): Cannot initialize a transaction when there is already an outstanding transaction.') : _prodInvariant('27') : void 0; 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] = OBSERVED_ERROR; this.wrapperInitData[i] = wrapper.initialize ? wrapper.initialize.call(this) : null; } finally { if (this.wrapperInitData[i] === 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() ? false ? invariant(false, 'Transaction.closeAll(): Cannot close transaction when none are open.') : _prodInvariant('28') : void 0; 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 !== 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; } }; module.exports = TransactionImpl; /***/ }), /* 64 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ReactDOMComponentTree = __webpack_require__(34); function isCheckable(elem) { var type = elem.type; var nodeName = elem.nodeName; return nodeName && nodeName.toLowerCase() === 'input' && (type === 'checkbox' || type === 'radio'); } function getTracker(inst) { return inst._wrapperState.valueTracker; } function attachTracker(inst, tracker) { inst._wrapperState.valueTracker = tracker; } function detachTracker(inst) { delete inst._wrapperState.valueTracker; } function getValueFromNode(node) { var value; if (node) { value = isCheckable(node) ? '' + node.checked : node.value; } return value; } var inputValueTracking = { // exposed for testing _getTrackerFromNode: function (node) { return getTracker(ReactDOMComponentTree.getInstanceFromNode(node)); }, track: function (inst) { if (getTracker(inst)) { return; } var node = ReactDOMComponentTree.getNodeFromInstance(inst); var valueField = isCheckable(node) ? 'checked' : 'value'; var descriptor = Object.getOwnPropertyDescriptor(node.constructor.prototype, valueField); var currentValue = '' + node[valueField]; // if someone has already defined a value or Safari, then bail // and don't track value will cause over reporting of changes, // but it's better then a hard failure // (needed for certain tests that spyOn input values and Safari) if (node.hasOwnProperty(valueField) || typeof descriptor.get !== 'function' || typeof descriptor.set !== 'function') { return; } Object.defineProperty(node, valueField, { enumerable: descriptor.enumerable, configurable: true, get: function () { return descriptor.get.call(this); }, set: function (value) { currentValue = '' + value; descriptor.set.call(this, value); } }); attachTracker(inst, { getValue: function () { return currentValue; }, setValue: function (value) { currentValue = '' + value; }, stopTracking: function () { detachTracker(inst); delete node[valueField]; } }); }, updateValueIfChanged: function (inst) { if (!inst) { return false; } var tracker = getTracker(inst); if (!tracker) { inputValueTracking.track(inst); return true; } var lastValue = tracker.getValue(); var nextValue = getValueFromNode(ReactDOMComponentTree.getNodeFromInstance(inst)); if (nextValue !== lastValue) { tracker.setValue(nextValue); return true; } return false; }, stopTracking: function (inst) { var tracker = getTracker(inst); if (tracker) { tracker.stopTracking(); } } }; module.exports = inputValueTracking; /***/ }), /* 65 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ '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; // Normalize SVG element events #4963 if (target.correspondingUseElement) { target = target.correspondingUseElement; } // 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; /***/ }), /* 66 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ExecutionEnvironment = __webpack_require__(48); 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.createElement('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; /***/ }), /* 67 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ '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(); if (nodeName === 'input') { return !!supportedInputTypes[elem.type]; } if (nodeName === 'textarea') { return true; } return false; } module.exports = isTextInputElement; /***/ }), /* 68 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * 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 = ['ResponderEventPlugin', 'SimpleEventPlugin', 'TapEventPlugin', 'EnterLeaveEventPlugin', 'ChangeEventPlugin', 'SelectEventPlugin', 'BeforeInputEventPlugin']; module.exports = DefaultEventPluginOrder; /***/ }), /* 69 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var EventPropagators = __webpack_require__(41); var ReactDOMComponentTree = __webpack_require__(34); var SyntheticMouseEvent = __webpack_require__(70); var eventTypes = { mouseEnter: { registrationName: 'onMouseEnter', dependencies: ['topMouseOut', 'topMouseOver'] }, mouseLeave: { registrationName: 'onMouseLeave', dependencies: ['topMouseOut', 'topMouseOver'] } }; 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. */ extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { if (topLevelType === 'topMouseOver' && (nativeEvent.relatedTarget || nativeEvent.fromElement)) { return null; } if (topLevelType !== 'topMouseOut' && topLevelType !== 'topMouseOver') { // Must not be a mouse in or mouse out - ignoring. return null; } var win; if (nativeEventTarget.window === nativeEventTarget) { // `nativeEventTarget` is probably a window object. win = nativeEventTarget; } else { // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. var doc = nativeEventTarget.ownerDocument; if (doc) { win = doc.defaultView || doc.parentWindow; } else { win = window; } } var from; var to; if (topLevelType === 'topMouseOut') { from = targetInst; var related = nativeEvent.relatedTarget || nativeEvent.toElement; to = related ? ReactDOMComponentTree.getClosestInstanceFromNode(related) : null; } else { // Moving to a node from outside the window. from = null; to = targetInst; } if (from === to) { // Nothing pertains to our managed components. return null; } var fromNode = from == null ? win : ReactDOMComponentTree.getNodeFromInstance(from); var toNode = to == null ? win : ReactDOMComponentTree.getNodeFromInstance(to); var leave = SyntheticMouseEvent.getPooled(eventTypes.mouseLeave, from, nativeEvent, nativeEventTarget); leave.type = 'mouseleave'; leave.target = fromNode; leave.relatedTarget = toNode; var enter = SyntheticMouseEvent.getPooled(eventTypes.mouseEnter, to, nativeEvent, nativeEventTarget); enter.type = 'mouseenter'; enter.target = toNode; enter.relatedTarget = fromNode; EventPropagators.accumulateEnterLeaveDispatches(leave, enter, from, to); return [leave, enter]; } }; module.exports = EnterLeaveEventPlugin; /***/ }), /* 70 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var SyntheticUIEvent = __webpack_require__(71); var ViewportMetrics = __webpack_require__(72); var getEventModifierState = __webpack_require__(73); /** * @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) { return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticMouseEvent, MouseEventInterface); module.exports = SyntheticMouseEvent; /***/ }), /* 71 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var SyntheticEvent = __webpack_require__(53); var getEventTarget = __webpack_require__(65); /** * @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.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) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticUIEvent, UIEventInterface); module.exports = SyntheticUIEvent; /***/ }), /* 72 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ViewportMetrics = { currentScrollLeft: 0, currentScrollTop: 0, refreshScrollValues: function (scrollPosition) { ViewportMetrics.currentScrollLeft = scrollPosition.x; ViewportMetrics.currentScrollTop = scrollPosition.y; } }; module.exports = ViewportMetrics; /***/ }), /* 73 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ '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; /***/ }), /* 74 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var DOMProperty = __webpack_require__(36); var MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY; var HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE; 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 HTMLDOMPropertyConfig = { isCustomAttribute: RegExp.prototype.test.bind(new RegExp('^(data|aria)-[' + DOMProperty.ATTRIBUTE_NAME_CHAR + ']*$')), Properties: { /** * Standard Properties */ accept: 0, acceptCharset: 0, accessKey: 0, action: 0, allowFullScreen: HAS_BOOLEAN_VALUE, allowTransparency: 0, alt: 0, // specifies target context for links with `preload` type as: 0, async: HAS_BOOLEAN_VALUE, autoComplete: 0, // autoFocus is polyfilled/normalized by AutoFocusUtils // autoFocus: HAS_BOOLEAN_VALUE, autoPlay: HAS_BOOLEAN_VALUE, capture: HAS_BOOLEAN_VALUE, cellPadding: 0, cellSpacing: 0, charSet: 0, challenge: 0, checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, cite: 0, classID: 0, className: 0, cols: HAS_POSITIVE_NUMERIC_VALUE, colSpan: 0, content: 0, contentEditable: 0, contextMenu: 0, controls: HAS_BOOLEAN_VALUE, coords: 0, crossOrigin: 0, data: 0, // For `` acts as `src`. dateTime: 0, 'default': HAS_BOOLEAN_VALUE, defer: HAS_BOOLEAN_VALUE, dir: 0, disabled: HAS_BOOLEAN_VALUE, download: HAS_OVERLOADED_BOOLEAN_VALUE, draggable: 0, encType: 0, form: 0, formAction: 0, formEncType: 0, formMethod: 0, formNoValidate: HAS_BOOLEAN_VALUE, formTarget: 0, frameBorder: 0, headers: 0, height: 0, hidden: HAS_BOOLEAN_VALUE, high: 0, href: 0, hrefLang: 0, htmlFor: 0, httpEquiv: 0, icon: 0, id: 0, inputMode: 0, integrity: 0, is: 0, keyParams: 0, keyType: 0, kind: 0, label: 0, lang: 0, list: 0, loop: HAS_BOOLEAN_VALUE, low: 0, manifest: 0, marginHeight: 0, marginWidth: 0, max: 0, maxLength: 0, media: 0, mediaGroup: 0, method: 0, min: 0, minLength: 0, // Caution; `option.selected` is not updated if `select.multiple` is // disabled with `removeAttribute`. multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, muted: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, name: 0, nonce: 0, noValidate: HAS_BOOLEAN_VALUE, open: HAS_BOOLEAN_VALUE, optimum: 0, pattern: 0, placeholder: 0, playsInline: HAS_BOOLEAN_VALUE, poster: 0, preload: 0, profile: 0, radioGroup: 0, readOnly: HAS_BOOLEAN_VALUE, referrerPolicy: 0, rel: 0, required: HAS_BOOLEAN_VALUE, reversed: HAS_BOOLEAN_VALUE, role: 0, rows: HAS_POSITIVE_NUMERIC_VALUE, rowSpan: HAS_NUMERIC_VALUE, sandbox: 0, scope: 0, scoped: HAS_BOOLEAN_VALUE, scrolling: 0, seamless: HAS_BOOLEAN_VALUE, selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, shape: 0, size: HAS_POSITIVE_NUMERIC_VALUE, sizes: 0, span: HAS_POSITIVE_NUMERIC_VALUE, spellCheck: 0, src: 0, srcDoc: 0, srcLang: 0, srcSet: 0, start: HAS_NUMERIC_VALUE, step: 0, style: 0, summary: 0, tabIndex: 0, target: 0, title: 0, // Setting .type throws on non- tags type: 0, useMap: 0, value: 0, width: 0, wmode: 0, wrap: 0, /** * RDFa Properties */ about: 0, datatype: 0, inlist: 0, prefix: 0, // property is also supported for OpenGraph in meta tags. property: 0, resource: 0, 'typeof': 0, vocab: 0, /** * Non-standard Properties */ // autoCapitalize and autoCorrect are supported in Mobile Safari for // keyboard hints. autoCapitalize: 0, autoCorrect: 0, // autoSave allows WebKit/Blink to persist values of input fields on page reloads autoSave: 0, // color is for Safari mask-icon link color: 0, // itemProp, itemScope, itemType are for // Microdata support. See http://schema.org/docs/gs.html itemProp: 0, itemScope: HAS_BOOLEAN_VALUE, itemType: 0, // itemID and itemRef are for Microdata support as well but // only specified in the WHATWG spec document. See // https://html.spec.whatwg.org/multipage/microdata.html#microdata-dom-api itemID: 0, itemRef: 0, // results show looking glass icon and recent searches on input // search fields in WebKit/Blink results: 0, // IE-only attribute that specifies security restrictions on an iframe // as an alternative to the sandbox attribute on IE<10 security: 0, // IE-only attribute that controls focus behavior unselectable: 0 }, DOMAttributeNames: { acceptCharset: 'accept-charset', className: 'class', htmlFor: 'for', httpEquiv: 'http-equiv' }, DOMPropertyNames: {}, DOMMutationMethods: { value: function (node, value) { if (value == null) { return node.removeAttribute('value'); } // Number inputs get special treatment due to some edge cases in // Chrome. Let everything else assign the value attribute as normal. // https://github.com/facebook/react/issues/7253#issuecomment-236074326 if (node.type !== 'number' || node.hasAttribute('value') === false) { node.setAttribute('value', '' + value); } else if (node.validity && !node.validity.badInput && node.ownerDocument.activeElement !== node) { // Don't assign an attribute if validation reports bad // input. Chrome will clear the value. Additionally, don't // operate on inputs that have focus, otherwise Chrome might // strip off trailing decimal places and cause the user's // cursor position to jump to the beginning of the input. // // In ReactDOMInput, we have an onBlur event that will trigger // this function again when focus is lost. node.setAttribute('value', '' + value); } } } }; module.exports = HTMLDOMPropertyConfig; /***/ }), /* 75 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var DOMChildrenOperations = __webpack_require__(76); var ReactDOMIDOperations = __webpack_require__(87); /** * 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, replaceNodeWithMarkup: DOMChildrenOperations.dangerouslyReplaceNodeWithMarkup }; module.exports = ReactComponentBrowserEnvironment; /***/ }), /* 76 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var DOMLazyTree = __webpack_require__(77); var Danger = __webpack_require__(83); var ReactDOMComponentTree = __webpack_require__(34); var ReactInstrumentation = __webpack_require__(62); var createMicrosoftUnsafeLocalFunction = __webpack_require__(80); var setInnerHTML = __webpack_require__(79); var setTextContent = __webpack_require__(81); function getNodeAfter(parentNode, node) { // Special case for text components, which return [open, close] comments // from getHostNode. if (Array.isArray(node)) { node = node[1]; } return node ? node.nextSibling : parentNode.firstChild; } /** * 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 */ var insertChildAt = createMicrosoftUnsafeLocalFunction(function (parentNode, childNode, referenceNode) { // We rely exclusively on `insertBefore(node, null)` instead of also using // `appendChild(node)`. (Using `undefined` is not allowed by all browsers so // we are careful to use `null`.) parentNode.insertBefore(childNode, referenceNode); }); function insertLazyTreeChildAt(parentNode, childTree, referenceNode) { DOMLazyTree.insertTreeBefore(parentNode, childTree, referenceNode); } function moveChild(parentNode, childNode, referenceNode) { if (Array.isArray(childNode)) { moveDelimitedText(parentNode, childNode[0], childNode[1], referenceNode); } else { insertChildAt(parentNode, childNode, referenceNode); } } function removeChild(parentNode, childNode) { if (Array.isArray(childNode)) { var closingComment = childNode[1]; childNode = childNode[0]; removeDelimitedText(parentNode, childNode, closingComment); parentNode.removeChild(closingComment); } parentNode.removeChild(childNode); } function moveDelimitedText(parentNode, openingComment, closingComment, referenceNode) { var node = openingComment; while (true) { var nextNode = node.nextSibling; insertChildAt(parentNode, node, referenceNode); if (node === closingComment) { break; } node = nextNode; } } function removeDelimitedText(parentNode, startNode, closingComment) { while (true) { var node = startNode.nextSibling; if (node === closingComment) { // The closing comment is removed by ReactMultiChild. break; } else { parentNode.removeChild(node); } } } function replaceDelimitedText(openingComment, closingComment, stringText) { var parentNode = openingComment.parentNode; var nodeAfterComment = openingComment.nextSibling; if (nodeAfterComment === closingComment) { // There are no text nodes between the opening and closing comments; insert // a new one if stringText isn't empty. if (stringText) { insertChildAt(parentNode, document.createTextNode(stringText), nodeAfterComment); } } else { if (stringText) { // Set the text content of the first node after the opening comment, and // remove all following nodes up until the closing comment. setTextContent(nodeAfterComment, stringText); removeDelimitedText(parentNode, nodeAfterComment, closingComment); } else { removeDelimitedText(parentNode, openingComment, closingComment); } } if (false) { ReactInstrumentation.debugTool.onHostOperation({ instanceID: ReactDOMComponentTree.getInstanceFromNode(openingComment)._debugID, type: 'replace text', payload: stringText }); } } var dangerouslyReplaceNodeWithMarkup = Danger.dangerouslyReplaceNodeWithMarkup; if (false) { dangerouslyReplaceNodeWithMarkup = function (oldChild, markup, prevInstance) { Danger.dangerouslyReplaceNodeWithMarkup(oldChild, markup); if (prevInstance._debugID !== 0) { ReactInstrumentation.debugTool.onHostOperation({ instanceID: prevInstance._debugID, type: 'replace with', payload: markup.toString() }); } else { var nextInstance = ReactDOMComponentTree.getInstanceFromNode(markup.node); if (nextInstance._debugID !== 0) { ReactInstrumentation.debugTool.onHostOperation({ instanceID: nextInstance._debugID, type: 'mount', payload: markup.toString() }); } } }; } /** * Operations for updating with DOM children. */ var DOMChildrenOperations = { dangerouslyReplaceNodeWithMarkup: dangerouslyReplaceNodeWithMarkup, replaceDelimitedText: replaceDelimitedText, /** * Updates a component's children by processing a series of updates. The * update configurations are each expected to have a `parentNode` property. * * @param {array} updates List of update configurations. * @internal */ processUpdates: function (parentNode, updates) { if (false) { var parentNodeDebugID = ReactDOMComponentTree.getInstanceFromNode(parentNode)._debugID; } for (var k = 0; k < updates.length; k++) { var update = updates[k]; switch (update.type) { case 'INSERT_MARKUP': insertLazyTreeChildAt(parentNode, update.content, getNodeAfter(parentNode, update.afterNode)); if (false) { ReactInstrumentation.debugTool.onHostOperation({ instanceID: parentNodeDebugID, type: 'insert child', payload: { toIndex: update.toIndex, content: update.content.toString() } }); } break; case 'MOVE_EXISTING': moveChild(parentNode, update.fromNode, getNodeAfter(parentNode, update.afterNode)); if (false) { ReactInstrumentation.debugTool.onHostOperation({ instanceID: parentNodeDebugID, type: 'move child', payload: { fromIndex: update.fromIndex, toIndex: update.toIndex } }); } break; case 'SET_MARKUP': setInnerHTML(parentNode, update.content); if (false) { ReactInstrumentation.debugTool.onHostOperation({ instanceID: parentNodeDebugID, type: 'replace children', payload: update.content.toString() }); } break; case 'TEXT_CONTENT': setTextContent(parentNode, update.content); if (false) { ReactInstrumentation.debugTool.onHostOperation({ instanceID: parentNodeDebugID, type: 'replace text', payload: update.content.toString() }); } break; case 'REMOVE_NODE': removeChild(parentNode, update.fromNode); if (false) { ReactInstrumentation.debugTool.onHostOperation({ instanceID: parentNodeDebugID, type: 'remove child', payload: { fromIndex: update.fromIndex } }); } break; } } } }; module.exports = DOMChildrenOperations; /***/ }), /* 77 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var DOMNamespaces = __webpack_require__(78); var setInnerHTML = __webpack_require__(79); var createMicrosoftUnsafeLocalFunction = __webpack_require__(80); var setTextContent = __webpack_require__(81); var ELEMENT_NODE_TYPE = 1; var DOCUMENT_FRAGMENT_NODE_TYPE = 11; /** * In IE (8-11) and Edge, appending nodes with no children is dramatically * faster than appending a full subtree, so we essentially queue up the * .appendChild calls here and apply them so each node is added to its parent * before any children are added. * * In other browsers, doing so is slower or neutral compared to the other order * (in Firefox, twice as slow) so we only do this inversion in IE. * * See https://github.com/spicyj/innerhtml-vs-createelement-vs-clonenode. */ var enableLazy = typeof document !== 'undefined' && typeof document.documentMode === 'number' || typeof navigator !== 'undefined' && typeof navigator.userAgent === 'string' && /\bEdge\/\d/.test(navigator.userAgent); function insertTreeChildren(tree) { if (!enableLazy) { return; } var node = tree.node; var children = tree.children; if (children.length) { for (var i = 0; i < children.length; i++) { insertTreeBefore(node, children[i], null); } } else if (tree.html != null) { setInnerHTML(node, tree.html); } else if (tree.text != null) { setTextContent(node, tree.text); } } var insertTreeBefore = createMicrosoftUnsafeLocalFunction(function (parentNode, tree, referenceNode) { // DocumentFragments aren't actually part of the DOM after insertion so // appending children won't update the DOM. We need to ensure the fragment // is properly populated first, breaking out of our lazy approach for just // this level. Also, some plugins (like Flash Player) will read // nodes immediately upon insertion into the DOM, so // must also be populated prior to insertion into the DOM. if (tree.node.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE || tree.node.nodeType === ELEMENT_NODE_TYPE && tree.node.nodeName.toLowerCase() === 'object' && (tree.node.namespaceURI == null || tree.node.namespaceURI === DOMNamespaces.html)) { insertTreeChildren(tree); parentNode.insertBefore(tree.node, referenceNode); } else { parentNode.insertBefore(tree.node, referenceNode); insertTreeChildren(tree); } }); function replaceChildWithTree(oldNode, newTree) { oldNode.parentNode.replaceChild(newTree.node, oldNode); insertTreeChildren(newTree); } function queueChild(parentTree, childTree) { if (enableLazy) { parentTree.children.push(childTree); } else { parentTree.node.appendChild(childTree.node); } } function queueHTML(tree, html) { if (enableLazy) { tree.html = html; } else { setInnerHTML(tree.node, html); } } function queueText(tree, text) { if (enableLazy) { tree.text = text; } else { setTextContent(tree.node, text); } } function toString() { return this.node.nodeName; } function DOMLazyTree(node) { return { node: node, children: [], html: null, text: null, toString: toString }; } DOMLazyTree.insertTreeBefore = insertTreeBefore; DOMLazyTree.replaceChildWithTree = replaceChildWithTree; DOMLazyTree.queueChild = queueChild; DOMLazyTree.queueHTML = queueHTML; DOMLazyTree.queueText = queueText; module.exports = DOMLazyTree; /***/ }), /* 78 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var DOMNamespaces = { html: 'http://www.w3.org/1999/xhtml', mathml: 'http://www.w3.org/1998/Math/MathML', svg: 'http://www.w3.org/2000/svg' }; module.exports = DOMNamespaces; /***/ }), /* 79 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ExecutionEnvironment = __webpack_require__(48); var DOMNamespaces = __webpack_require__(78); var WHITESPACE_TEST = /^[ \r\n\t\f]/; var NONVISIBLE_TEST = /<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/; var createMicrosoftUnsafeLocalFunction = __webpack_require__(80); // SVG temp container for IE lacking innerHTML var reusableSVGContainer; /** * Set the innerHTML property of a node, ensuring that whitespace is preserved * even in IE8. * * @param {DOMElement} node * @param {string} html * @internal */ var setInnerHTML = createMicrosoftUnsafeLocalFunction(function (node, html) { // IE does not have innerHTML for SVG nodes, so instead we inject the // new markup in a temp node and then move the child nodes across into // the target node if (node.namespaceURI === DOMNamespaces.svg && !('innerHTML' in node)) { reusableSVGContainer = reusableSVGContainer || document.createElement('div'); reusableSVGContainer.innerHTML = '' + html + ''; var svgNode = reusableSVGContainer.firstChild; while (svgNode.firstChild) { node.appendChild(svgNode.firstChild); } } else { 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.createElement('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; } }; } testElement = null; } module.exports = setInnerHTML; /***/ }), /* 80 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ /* globals MSApp */ 'use strict'; /** * Create a function which has 'unsafe' privileges (required by windows8 apps) */ var createMicrosoftUnsafeLocalFunction = function (func) { if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) { return function (arg0, arg1, arg2, arg3) { MSApp.execUnsafeLocalFunction(function () { return func(arg0, arg1, arg2, arg3); }); }; } else { return func; } }; module.exports = createMicrosoftUnsafeLocalFunction; /***/ }), /* 81 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ExecutionEnvironment = __webpack_require__(48); var escapeTextContentForBrowser = __webpack_require__(82); var setInnerHTML = __webpack_require__(79); /** * 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
instead of the literal newline chars. innerHTML behaves * as it should. * * @param {DOMElement} node * @param {string} text * @internal */ var setTextContent = function (node, text) { if (text) { var firstChild = node.firstChild; if (firstChild && firstChild === node.lastChild && firstChild.nodeType === 3) { firstChild.nodeValue = text; return; } } node.textContent = text; }; if (ExecutionEnvironment.canUseDOM) { if (!('textContent' in document.documentElement)) { setTextContent = function (node, text) { if (node.nodeType === 3) { node.nodeValue = text; return; } setInnerHTML(node, escapeTextContentForBrowser(text)); }; } } module.exports = setTextContent; /***/ }), /* 82 */ /***/ (function(module, exports) { /** * Copyright 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in 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 on the escape-html library, which is used under the MIT License below: * * Copyright (c) 2012-2013 TJ Holowaychuk * Copyright (c) 2015 Andreas Lubbe * Copyright (c) 2015 Tiancheng "Timothy" Gu * * 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. * */ 'use strict'; // code copied and modified from escape-html /** * Module variables. * @private */ var matchHtmlRegExp = /["'&<>]/; /** * Escape special characters in the given string of html. * * @param {string} string The string to escape for inserting into HTML * @return {string} * @public */ function escapeHtml(string) { var str = '' + string; var match = matchHtmlRegExp.exec(str); if (!match) { return str; } var escape; var html = ''; var index = 0; var lastIndex = 0; for (index = match.index; index < str.length; index++) { switch (str.charCodeAt(index)) { case 34: // " escape = '"'; break; case 38: // & escape = '&'; break; case 39: // ' escape = '''; // modified from escape-html; used to be ''' break; case 60: // < escape = '<'; break; case 62: // > escape = '>'; break; default: continue; } if (lastIndex !== index) { html += str.substring(lastIndex, index); } lastIndex = index + 1; html += escape; } return lastIndex !== index ? html + str.substring(lastIndex, index) : html; } // end code copied and modified from escape-html /** * Escapes text to prevent scripting attacks. * * @param {*} text Text value to escape. * @return {string} An escaped string. */ function escapeTextContentForBrowser(text) { if (typeof text === 'boolean' || typeof text === 'number') { // this shortcircuit helps perf for types that we know will never have // special characters, especially given that this function is used often // for numeric dom ids. return '' + text; } return escapeHtml(text); } module.exports = escapeTextContentForBrowser; /***/ }), /* 83 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(35); var DOMLazyTree = __webpack_require__(77); var ExecutionEnvironment = __webpack_require__(48); var createNodesFromMarkup = __webpack_require__(84); var emptyFunction = __webpack_require__(9); var invariant = __webpack_require__(12); var Danger = { /** * 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 ? false ? 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.') : _prodInvariant('56') : void 0; !markup ? false ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Missing markup.') : _prodInvariant('57') : void 0; !(oldChild.nodeName !== 'HTML') ? false ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Cannot replace markup of the 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().') : _prodInvariant('58') : void 0; if (typeof markup === 'string') { var newChild = createNodesFromMarkup(markup, emptyFunction)[0]; oldChild.parentNode.replaceChild(newChild, oldChild); } else { DOMLazyTree.replaceChildWithTree(oldChild, markup); } } }; module.exports = Danger; /***/ }), /* 84 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in 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 */ /*eslint-disable fb-www/unsafe-html*/ var ExecutionEnvironment = __webpack_require__(48); var createArrayFromMixed = __webpack_require__(85); var getMarkupWrap = __webpack_require__(86); var invariant = __webpack_require__(12); /** * Dummy container used to render all markup. */ var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement('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 * ================================================ FILE: docs/index.js ================================================ 'use strict' import React from 'react' import ReactDOM from 'react-dom' // import ReactDOMServer from 'react-dom-server' import Home from './components/home/Home' // const html = ReactDOMServer.renderToString(React.createElement(Home)) // console.log(html) if (typeof document !== 'undefined') { ReactDOM.render( React.createElement(Home), document.getElementById('root') ) } module.exports = Home ================================================ FILE: examples/basic/.gitignore ================================================ # See https://help.github.com/ignore-files/ for more about ignoring files. # dependencies /node_modules # testing /coverage # production /build # misc .DS_Store .env.local .env.development.local .env.test.local .env.production.local npm-debug.log* yarn-debug.log* yarn-error.log* ================================================ FILE: examples/basic/package.json ================================================ { "name": "react-color-example-basic", "version": "0.1.0", "private": true, "dependencies": { "react": "^15.6.1", "react-color": "latest", "react-dom": "^15.6.1", "react-scripts": "1.0.12" }, "scripts": { "start": "react-scripts start" } } ================================================ FILE: examples/basic/public/index.html ================================================
================================================ FILE: examples/basic/src/App.js ================================================ /* eslint-disable no-console */ import React from 'react' import { SketchPicker } from 'react-color' export const App = () => { const handleColorChange = ({ hex }) => console.log(hex) return (
) } export default App ================================================ FILE: examples/basic/src/index.js ================================================ import React from 'react' import ReactDOM from 'react-dom' import App from './App' ReactDOM.render( , document.getElementById('root'), ) ================================================ FILE: examples/basic-positioning/.gitignore ================================================ # See https://help.github.com/ignore-files/ for more about ignoring files. # dependencies /node_modules # testing /coverage # production /build # misc .DS_Store .env.local .env.development.local .env.test.local .env.production.local npm-debug.log* yarn-debug.log* yarn-error.log* ================================================ FILE: examples/basic-positioning/package.json ================================================ { "name": "react-color-example-basic-positioning", "version": "0.1.0", "private": true, "dependencies": { "react": "^15.6.1", "react-color": "latest", "react-dom": "^15.6.1", "react-scripts": "1.0.12" }, "scripts": { "start": "react-scripts start" } } ================================================ FILE: examples/basic-positioning/public/index.html ================================================
================================================ FILE: examples/basic-positioning/src/App.js ================================================ /* eslint-disable no-console */ import React from 'react' import { BlockPicker } from 'react-color' export const App = () => { const handleColorChange = ({ hex }) => console.log(hex) return (
) } export default App ================================================ FILE: examples/basic-positioning/src/index.js ================================================ import React from 'react' import ReactDOM from 'react-dom' import App from './App' ReactDOM.render( , document.getElementById('root'), ) ================================================ FILE: examples/basic-toggle-open-closed/.gitignore ================================================ # See https://help.github.com/ignore-files/ for more about ignoring files. # dependencies /node_modules # testing /coverage # production /build # misc .DS_Store .env.local .env.development.local .env.test.local .env.production.local npm-debug.log* yarn-debug.log* yarn-error.log* ================================================ FILE: examples/basic-toggle-open-closed/package.json ================================================ { "name": "react-color-example-basic-toggle-open-closed", "version": "0.1.0", "private": true, "dependencies": { "react": "^15.6.1", "react-color": "latest", "react-dom": "^15.6.1", "react-scripts": "1.0.12" }, "scripts": { "start": "react-scripts start" } } ================================================ FILE: examples/basic-toggle-open-closed/public/index.html ================================================
================================================ FILE: examples/basic-toggle-open-closed/src/App.js ================================================ /* eslint-disable no-console */ import React from 'react' import { CompactPicker } from 'react-color' class App extends React.Component { state = { pickerVisible: false, } render() { const handleColorChange = ({ hex }) => console.log(hex) const onTogglePicker = () => this.setState({ pickerVisible: !this.state.pickerVisible }) return (
{ this.state.pickerVisible && (
) }
) } } export default App ================================================ FILE: examples/basic-toggle-open-closed/src/index.js ================================================ import React from 'react' import ReactDOM from 'react-dom' import App from './App' ReactDOM.render( , document.getElementById('root'), ) ================================================ FILE: examples/basic-with-react-hooks/.gitignore ================================================ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # dependencies /node_modules /.pnp .pnp.js # testing /coverage # production /build # misc .DS_Store .env.local .env.development.local .env.test.local .env.production.local npm-debug.log* yarn-debug.log* yarn-error.log* ================================================ FILE: examples/basic-with-react-hooks/package.json ================================================ { "name": "basic-with-react-hooks", "version": "0.1.0", "private": true, "dependencies": { "@testing-library/jest-dom": "^4.2.4", "@testing-library/react": "^9.3.2", "@testing-library/user-event": "^7.1.2", "react": "^16.13.1", "react-color": "^2.18.0", "react-dom": "^16.13.1", "react-scripts": "^3.4.1" }, "scripts": { "start": "react-scripts start" }, "eslintConfig": { "extends": "react-app" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } } ================================================ FILE: examples/basic-with-react-hooks/public/index.html ================================================ React App
================================================ FILE: examples/basic-with-react-hooks/src/App.js ================================================ import React, { useState } from "react"; import { SketchPicker } from "react-color"; const App = () => { const [color, setColor] = useState(); const handleChange = color => setColor(color); return (
); }; export default App; ================================================ FILE: examples/basic-with-react-hooks/src/index.js ================================================ import React from "react"; import ReactDOM from "react-dom"; import App from "./App"; ReactDOM.render(, document.getElementById("root")); ================================================ FILE: examples/custom-picker/.gitignore ================================================ # See https://help.github.com/ignore-files/ for more about ignoring files. # dependencies /node_modules # testing /coverage # production /build # misc .DS_Store .env.local .env.development.local .env.test.local .env.production.local npm-debug.log* yarn-debug.log* yarn-error.log* ================================================ FILE: examples/custom-picker/package.json ================================================ { "name": "react-color-example-custom-picker", "version": "0.1.0", "private": true, "dependencies": { "react": "^15.6.1", "react-color": "latest", "react-dom": "^15.6.1", "react-scripts": "1.0.12" }, "scripts": { "start": "react-scripts start" } } ================================================ FILE: examples/custom-picker/public/index.html ================================================
================================================ FILE: examples/custom-picker/src/App.js ================================================ /* eslint-disable no-console */ import React from 'react' import MyPicker from './MyPicker' export const App = () => { const handleColorChange = ({ hex }) => console.log(hex) return (
) } export default App ================================================ FILE: examples/custom-picker/src/MyPicker.js ================================================ import React from 'react' import { CustomPicker } from 'react-color' import { EditableInput, Hue } from 'react-color/lib/components/common' export const MyPicker = ({ hex, hsl, onChange }) => { const styles = { hue: { height: 10, position: 'relative', marginBottom: 10, }, input: { height: 34, border: `1px solid ${ hex }`, paddingLeft: 10, }, swatch: { width: 54, height: 38, background: hex, }, } return (
) } export default CustomPicker(MyPicker) ================================================ FILE: examples/custom-picker/src/index.js ================================================ import React from 'react' import ReactDOM from 'react-dom' import App from './App' ReactDOM.render( , document.getElementById('root'), ) ================================================ FILE: examples/custom-pointer/.gitignore ================================================ # See https://help.github.com/ignore-files/ for more about ignoring files. # dependencies /node_modules # testing /coverage # production /build # misc .DS_Store .env.local .env.development.local .env.test.local .env.production.local npm-debug.log* yarn-debug.log* yarn-error.log* ================================================ FILE: examples/custom-pointer/package.json ================================================ { "name": "react-color-example-custom-pointer", "version": "0.1.0", "private": true, "dependencies": { "react": "^15.6.1", "react-color": "latest", "react-dom": "^15.6.1", "react-scripts": "1.0.12" }, "scripts": { "start": "react-scripts start" } } ================================================ FILE: examples/custom-pointer/public/index.html ================================================
================================================ FILE: examples/custom-pointer/src/App.js ================================================ /* eslint-disable no-console */ import React from 'react' import MyPicker from './MyPicker' export const App = () => { const handleColorChange = ({ hex }) => console.log(hex) return (
) } export default App ================================================ FILE: examples/custom-pointer/src/MyPicker.js ================================================ /* eslint-disable no-console */ import React from 'react' import { CustomPicker } from 'react-color' import { Alpha } from 'react-color/lib/components/common' import MyPointer from './MyPointer' export const MyPicker = ({ rgb, hsl, onChange }) => { return (
) } export default CustomPicker(MyPicker) ================================================ FILE: examples/custom-pointer/src/MyPointer.js ================================================ import React from 'react' export const MyPointer = () => { return (
🔥
) } export default MyPointer ================================================ FILE: examples/custom-pointer/src/index.js ================================================ import React from 'react' import ReactDOM from 'react-dom' import App from './App' ReactDOM.render( , document.getElementById('root'), ) ================================================ FILE: examples/with-portals/.gitignore ================================================ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # dependencies /node_modules /.pnp .pnp.js # testing /coverage # production /build # misc .DS_Store .env.local .env.development.local .env.test.local .env.production.local npm-debug.log* yarn-debug.log* yarn-error.log* ================================================ FILE: examples/with-portals/package.json ================================================ { "dependencies": { "react": "^16.8.6", "react-color": "latest", "react-dom": "^16.8.6", "react-scripts": "3.0.1" }, "scripts": { "start": "SKIP_PREFLIGHT_CHECK=true react-scripts start" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } } ================================================ FILE: examples/with-portals/public/index.html ================================================
================================================ FILE: examples/with-portals/src/App.js ================================================ /* eslint-disable no-console */ import React from 'react' import Portal from './Portal' export class App extends React.Component { state = { pickerVisible: false, } handleToggleVisibility = () => { this.setState(({ pickerVisible }) => ({ pickerVisible: !pickerVisible, })) } handleColorChange = ({ hex }) => console.log(hex) render() { return (
{this.state.pickerVisible && ( )}
) } } export default App ================================================ FILE: examples/with-portals/src/Modal.js ================================================ import React from 'react' export const Modal = ({ children, onClose }) => (
{children}
) export default Modal ================================================ FILE: examples/with-portals/src/Portal.js ================================================ import React from 'react' import ReactDOM from 'react-dom' import { SketchPicker } from 'react-color' import Modal from './Modal' export const Portal = ({ onClose, onChange }) => { const contents = ( ) return ReactDOM.createPortal( contents, document.getElementById('root-portal') ) } export default Portal ================================================ FILE: examples/with-portals/src/index.js ================================================ import React from 'react' import ReactDOM from 'react-dom' import App from './App' ReactDOM.render( , document.getElementById('root') ) ================================================ FILE: examples/with-redux/.gitignore ================================================ # See https://help.github.com/ignore-files/ for more about ignoring files. # dependencies /node_modules # testing /coverage # production /build # misc .DS_Store .env.local .env.development.local .env.test.local .env.production.local npm-debug.log* yarn-debug.log* yarn-error.log* ================================================ FILE: examples/with-redux/package.json ================================================ { "name": "react-color-example-basic", "version": "0.1.0", "private": true, "dependencies": { "react": "^15.6.1", "react-color": "latest", "react-dom": "^15.6.1", "react-redux": "^5.0.6", "react-scripts": "1.0.12", "redux": "^3.7.2" }, "scripts": { "start": "react-scripts start" } } ================================================ FILE: examples/with-redux/public/index.html ================================================
================================================ FILE: examples/with-redux/src/App.js ================================================ /* eslint-disable no-console */ import React from 'react' import { connect } from 'react-redux' import { actions as appActions } from './reducer' import { SketchPicker } from 'react-color' export const App = ({ color, onChangeColor }) => { return (
) } const mapStateToProps = state => ({ color: state.color, }) const mapDispatchToProps = { onChangeColor: appActions.changeColor, } export default connect(mapStateToProps, mapDispatchToProps)(App) ================================================ FILE: examples/with-redux/src/index.js ================================================ import React from 'react' import ReactDOM from 'react-dom' import { createStore } from 'redux' import { reducer as app } from './reducer' import { Provider } from 'react-redux' import App from './App' ReactDOM.render( , document.getElementById('root'), ) ================================================ FILE: examples/with-redux/src/reducer.js ================================================ export const CHANGE_COLOR = 'APP/CHANGE_COLOR' export const actions = { changeColor: ({ hex }) => ({ type: CHANGE_COLOR, hex }), } const initialState = { color: '#F5A623', } export const reducer = (state = initialState, action) => { switch (action.type) { case CHANGE_COLOR: return { ...state, color: action.hex } default: return state } } ================================================ FILE: package.json ================================================ { "name": "react-color", "version": "2.19.3", "description": "A Collection of Color Pickers from Sketch, Photoshop, Chrome & more", "main": "lib/index.js", "module": "es/index.js", "repository": { "type": "git", "url": "git+https://github.com/casesandberg/react-color.git" }, "author": "case ", "license": "MIT", "bugs": { "url": "https://github.com/casesandberg/react-color/issues" }, "scripts": { "test": "npm run jest && npm run eslint", "jest": "jest", "eslint": "eslint src/**/*.js", "lib": "npm run clean-lib && babel src -d lib", "es": "npm run clean-es && node scripts/use-module-babelrc.js && babel src -d es && node scripts/restore-original-babelrc.js", "clean-lib": "rm -rf lib && mkdir lib", "clean-es": "rm -rf es && mkdir es", "prepublish": "npm run lib && npm run es", "docs": "npm run docs-server", "docs-server": "node ./scripts/docs-server", "docs-dist": "node ./scripts/docs-dist", "storybook": "start-storybook -p 6006", "build-storybook": "build-storybook -c .storybook -o .out", "chromatic": "chromatic --project-token=9z2kaxsuz" }, "sideEffects": false, "homepage": "http://casesandberg.github.io/react-color/", "keywords": [ "react", "color picker", "react-component", "colorpicker", "picker", "sketch", "chrome", "photoshop", "material design", "popup" ], "dependencies": { "@icons/material": "^0.2.4", "lodash": "^4.17.15", "lodash-es": "^4.17.15", "material-colors": "^1.2.1", "prop-types": "^15.5.10", "reactcss": "^1.2.0", "tinycolor2": "^1.4.1" }, "peerDependencies": { "react": "*" }, "devDependencies": { "@case/eslint-config": "^0.3.1", "@storybook/addon-centered": "^3.2.0", "@storybook/addon-knobs": "^3.2.0", "@storybook/addon-options": "^3.2.4", "@storybook/react": "^3.2.4", "babel-cli": "^6.8.0", "babel-core": "^6.10.4", "babel-jest": "^20.0.3", "babel-loader": "^6.2.1", "babel-plugin-transform-rename-import": "^2.3.0", "babel-preset-es2015": "^6.3.13", "babel-preset-react": "^6.3.13", "babel-preset-stage-0": "^6.3.13", "babel-register": "^6.5.2", "chai": "^3.3.0", "chai-spies": "^0.7.1", "css-loader": "^0.24.0", "enzyme": "2.8.2", "event-stream": "^3.3.1", "fbjs": "^0.8.6", "highlight.js": "^9.3.0", "html-loader": "^0.3.0", "html-webpack-plugin": "^3.2.0", "i": "^0.3.5", "jest": "^20.0.4", "jest-cli": "^20.0.4", "jsx-loader": "^0.13.2", "mocha": "^2.4.5", "normalize.css": "^4.1.1", "npm": "^5.3.0", "object-assign": "^4.1.0", "react": "^15.3.2", "react-addons-test-utils": "^0.14.0 || ^15.0.0", "react-context": "0.0.3", "react-dom": "^0.14.0 || ^15.0.0", "react-hot-loader": "^1.2.8", "react-mark": "0.0.4", "react-test-renderer": "^15.3.2", "remarkable": "^1.6.0", "require-dir": "^0.3.0", "rimraf": "^2.5.0", "style-loader": "^0.13.0", "testdom": "^2.0.0", "webpack": "^1.11.0", "webpack-dev-server": "^1.10.1" }, "files": [ "lib", "es" ], "jest": { "rootDir": "src", "testRegex": "spec.js$" }, "eslintConfig": { "extends": "@case", "rules": { "no-magic-numbers": 0 } }, "payload": { "builds": [ { "cmd": "npm run docs-dist", "files": [ "docs/build/bundle.js", "docs/index.js" ] } ] } } ================================================ FILE: scripts/docs-dist.js ================================================ 'use strict' var webpack = require('webpack') var webpackConfig = require('../webpack.config.js') let build = Object.create(webpackConfig) build.plugins = [ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production'), }, }), new webpack.optimize.DedupePlugin(), ] webpack(build, (err, stats) => { if (err) throw new Error('webpack-dev-server', err) }) ================================================ FILE: scripts/docs-server.js ================================================ 'use strict' var webpack = require('webpack') var WebpackDevServer = require('webpack-dev-server') var webpackConfig = require('../webpack.config.js') let port = 9100 let docs = Object.create(webpackConfig) docs.entry = ['webpack-dev-server/client?http://localhost:' + port, 'webpack/hot/dev-server', docs.entry[0]] docs.module.loaders[0].loaders.unshift('react-hot-loader') docs.module.loaders[1].loaders.unshift('react-hot-loader') docs.devtool = 'eval' docs.debug = true new WebpackDevServer(webpack(docs), { publicPath: '/' + docs.output.publicPath, hot: true, stats: { cached: false, cachedAssets: false, colors: true, exclude: ['node_modules', 'components'], }, }).listen(port, 'localhost', err => { if (err) throw new Error('webpack-dev-server', err) console.log('[webpack-dev-server]', 'http://localhost:' + port + '/') }) ================================================ FILE: scripts/restore-original-babelrc.js ================================================ const fs = require('fs') const path = require('path') const babelRCBackup = fs .readFileSync(path.join(__dirname, '../.babelrc_backup')) .toString() fs.writeFileSync( path.join(__dirname, '../.babelrc'), babelRCBackup ) ================================================ FILE: scripts/use-module-babelrc.js ================================================ const fs = require('fs') const path = require('path') const originalBabelRC = fs .readFileSync(path.join(__dirname, '../.babelrc')) .toString() fs.writeFileSync(path.join(__dirname, '../.babelrc_backup'), originalBabelRC) const esBabelRC = { presets: [ ['es2015', { modules: false }], 'stage-0', 'react', ], plugins: [ [ 'transform-rename-import', { 'original': 'lodash', 'replacement': 'lodash-es', }, ], ], } fs.writeFileSync(path.join(__dirname, '../.babelrc'), JSON.stringify(esBabelRC)) ================================================ FILE: src/Alpha.js ================================================ export default from './components/alpha/Alpha' ================================================ FILE: src/Block.js ================================================ export default from './components/block/Block' ================================================ FILE: src/Chrome.js ================================================ export default from './components/chrome/Chrome' ================================================ FILE: src/Circle.js ================================================ export default from './components/circle/Circle' ================================================ FILE: src/Compact.js ================================================ export default from './components/compact/Compact' ================================================ FILE: src/Custom.js ================================================ export default from './components/common/ColorWrap' ================================================ FILE: src/Github.js ================================================ export default from './components/github/Github' ================================================ FILE: src/Google.js ================================================ export default from './components/google/Google' ================================================ FILE: src/Hue.js ================================================ export default from './components/hue/Hue' ================================================ FILE: src/Material.js ================================================ export default from './components/material/Material' ================================================ FILE: src/Photoshop.js ================================================ export default from './components/photoshop/Photoshop' ================================================ FILE: src/Sketch.js ================================================ export default from './components/sketch/Sketch' ================================================ FILE: src/Slider.js ================================================ export default from './components/slider/Slider' ================================================ FILE: src/Swatches.js ================================================ export default from './components/swatches/Swatches' ================================================ FILE: src/Twitter.js ================================================ export default from './components/twitter/Twitter' ================================================ FILE: src/components/alpha/Alpha.js ================================================ import React from 'react' import reactCSS from 'reactcss' import { ColorWrap, Alpha } from '../common' import AlphaPointer from './AlphaPointer' export const AlphaPicker = ({ rgb, hsl, width, height, onChange, direction, style, renderers, pointer, className = '' }) => { const styles = reactCSS({ 'default': { picker: { position: 'relative', width, height, }, alpha: { radius: '2px', style, }, }, }) return (
) } AlphaPicker.defaultProps = { width: '316px', height: '16px', direction: 'horizontal', pointer: AlphaPointer, } export default ColorWrap(AlphaPicker) ================================================ FILE: src/components/alpha/AlphaPointer.js ================================================ import React from 'react' import reactCSS from 'reactcss' export const AlphaPointer = ({ direction }) => { const styles = reactCSS({ 'default': { picker: { width: '18px', height: '18px', borderRadius: '50%', transform: 'translate(-9px, -1px)', backgroundColor: 'rgb(248, 248, 248)', boxShadow: '0 1px 4px 0 rgba(0, 0, 0, 0.37)', }, }, 'vertical': { picker: { transform: 'translate(-3px, -9px)', }, }, }, { vertical: direction === 'vertical' }) return (
) } export default AlphaPointer ================================================ FILE: src/components/alpha/__snapshots__/spec.js.snap ================================================ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Alpha renders correctly 1`] = `
`; exports[`Alpha renders vertically 1`] = `
`; exports[`AlphaPointer renders correctly 1`] = `
`; ================================================ FILE: src/components/alpha/spec.js ================================================ /* global test, expect, jest */ import React from 'react' import renderer from 'react-test-renderer' import { mount } from 'enzyme' import * as color from '../../helpers/color' // import canvas from 'canvas' import Alpha from './Alpha' import { Alpha as CommonAlpha } from '../common' import AlphaPointer from './AlphaPointer' test('Alpha renders correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) // test('Alpha renders on server correctly', () => { // const tree = renderer.create( // // ).toJSON() // expect(tree).toMatchSnapshot() // }) test('Alpha onChange events correctly', () => { const changeSpy = jest.fn((data) => { expect(color.simpleCheckForValidColor(data)).toBeTruthy() }) const tree = mount( , ) expect(changeSpy).toHaveBeenCalledTimes(0) const alphaCommon = tree.find(CommonAlpha) alphaCommon.at(0).childAt(2).simulate('mouseDown', { pageX: 100, pageY: 10, }) expect(changeSpy).toHaveBeenCalled() }) test('Alpha renders vertically', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) test('AlphaPointer renders correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) ================================================ FILE: src/components/block/Block.js ================================================ import React from 'react' import PropTypes from 'prop-types' import reactCSS from 'reactcss' import merge from 'lodash/merge' import * as color from '../../helpers/color' import { ColorWrap, EditableInput, Checkboard } from '../common' import BlockSwatches from './BlockSwatches' export const Block = ({ onChange, onSwatchHover, hex, colors, width, triangle, styles: passedStyles = {}, className = '' }) => { const transparent = hex === 'transparent' const handleChange = (hexCode, e) => { color.isValidHex(hexCode) && onChange({ hex: hexCode, source: 'hex', }, e) } const styles = reactCSS(merge({ 'default': { card: { width, background: '#fff', boxShadow: '0 1px rgba(0,0,0,.1)', borderRadius: '6px', position: 'relative', }, head: { height: '110px', background: hex, borderRadius: '6px 6px 0 0', display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative', }, body: { padding: '10px', }, label: { fontSize: '18px', color: color.getContrastingColor(hex), position: 'relative', }, triangle: { width: '0px', height: '0px', borderStyle: 'solid', borderWidth: '0 10px 10px 10px', borderColor: `transparent transparent ${ hex } transparent`, position: 'absolute', top: '-10px', left: '50%', marginLeft: '-10px', }, input: { width: '100%', fontSize: '12px', color: '#666', border: '0px', outline: 'none', height: '22px', boxShadow: 'inset 0 0 0 1px #ddd', borderRadius: '4px', padding: '0 7px', boxSizing: 'border-box', }, }, 'hide-triangle': { triangle: { display: 'none', }, }, }, passedStyles), { 'hide-triangle': triangle === 'hide' }) return (
{ transparent && ( ) }
{ hex }
) } Block.propTypes = { width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), colors: PropTypes.arrayOf(PropTypes.string), triangle: PropTypes.oneOf(['top', 'hide']), styles: PropTypes.object, } Block.defaultProps = { width: 170, colors: ['#D9E3F0', '#F47373', '#697689', '#37D67A', '#2CCCE4', '#555555', '#dce775', '#ff8a65', '#ba68c8'], triangle: 'top', styles: {}, } export default ColorWrap(Block) ================================================ FILE: src/components/block/BlockSwatches.js ================================================ import React from 'react' import reactCSS from 'reactcss' import map from 'lodash/map' import { Swatch } from '../common' export const BlockSwatches = ({ colors, onClick, onSwatchHover }) => { const styles = reactCSS({ 'default': { swatches: { marginRight: '-10px', }, swatch: { width: '22px', height: '22px', float: 'left', marginRight: '10px', marginBottom: '10px', borderRadius: '4px', }, clear: { clear: 'both', }, }, }) return (
{ map(colors, c => ( )) }
) } export default BlockSwatches ================================================ FILE: src/components/block/__snapshots__/spec.js.snap ================================================ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Block \`triangle="hide"\` 1`] = `
#22194d
`; exports[`Block renders correctly 1`] = `
#22194d
`; exports[`BlockSwatches renders correctly 1`] = `
`; ================================================ FILE: src/components/block/spec.js ================================================ /* global test, jest, expect */ import React from 'react' import renderer from 'react-test-renderer' import { mount } from 'enzyme' import Block from './Block' import BlockSwatches from './BlockSwatches' import { Swatch } from '../common' import* as color from '../../helpers/color' test('Block renders correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) test('Block onChange events correctly', () => { const changeSpy = jest.fn((data) => { expect(color.simpleCheckForValidColor(data)).toBeTruthy() }) const tree = mount( , ) expect(changeSpy).toHaveBeenCalledTimes(0) const swatches = tree.find(Swatch) swatches.at(0).childAt(0).simulate('click') expect(changeSpy).toHaveBeenCalled() }) test('Block with onSwatchHover events correctly', () => { const hoverSpy = jest.fn((data) => { expect(color.simpleCheckForValidColor(data)).toBeTruthy() }) const tree = mount( , ) expect(hoverSpy).toHaveBeenCalledTimes(0) const swatches = tree.find(Swatch) swatches.at(0).childAt(0).simulate('mouseOver') expect(hoverSpy).toHaveBeenCalled() }) test('Block `triangle="hide"`', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) test('BlockSwatches renders correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) test('Block renders custom styles correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree.props.style.boxShadow).toBe('none') }) ================================================ FILE: src/components/block/story.js ================================================ import React from 'react' import { storiesOf } from '@storybook/react' import { renderWithKnobs } from '../../../.storybook/report' import SyncColorField from '../../../.storybook/SyncColorField' import Block from './Block' storiesOf('Pickers', module) .add('BlockPicker', () => ( { renderWithKnobs(Block, {}, null, { width: { range: true, min: 140, max: 500, step: 1 }, }) } )) ================================================ FILE: src/components/chrome/Chrome.js ================================================ import React from 'react' import PropTypes from 'prop-types' import reactCSS from 'reactcss' import merge from 'lodash/merge' import { ColorWrap, Saturation, Hue, Alpha, Checkboard } from '../common' import ChromeFields from './ChromeFields' import ChromePointer from './ChromePointer' import ChromePointerCircle from './ChromePointerCircle' export const Chrome = ({ width, onChange, disableAlpha, rgb, hsl, hsv, hex, renderers, styles: passedStyles = {}, className = '', defaultView }) => { const styles = reactCSS(merge({ 'default': { picker: { width, background: '#fff', borderRadius: '2px', boxShadow: '0 0 2px rgba(0,0,0,.3), 0 4px 8px rgba(0,0,0,.3)', boxSizing: 'initial', fontFamily: 'Menlo', }, saturation: { width: '100%', paddingBottom: '55%', position: 'relative', borderRadius: '2px 2px 0 0', overflow: 'hidden', }, Saturation: { radius: '2px 2px 0 0', }, body: { padding: '16px 16px 12px', }, controls: { display: 'flex', }, color: { width: '32px', }, swatch: { marginTop: '6px', width: '16px', height: '16px', borderRadius: '8px', position: 'relative', overflow: 'hidden', }, active: { absolute: '0px 0px 0px 0px', borderRadius: '8px', boxShadow: 'inset 0 0 0 1px rgba(0,0,0,.1)', background: `rgba(${ rgb.r }, ${ rgb.g }, ${ rgb.b }, ${ rgb.a })`, zIndex: '2', }, toggles: { flex: '1', }, hue: { height: '10px', position: 'relative', marginBottom: '8px', }, Hue: { radius: '2px', }, alpha: { height: '10px', position: 'relative', }, Alpha: { radius: '2px', }, }, 'disableAlpha': { color: { width: '22px', }, alpha: { display: 'none', }, hue: { marginBottom: '0px', }, swatch: { width: '10px', height: '10px', marginTop: '0px', }, }, }, passedStyles), { disableAlpha }) return (
) } Chrome.propTypes = { width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), disableAlpha: PropTypes.bool, styles: PropTypes.object, defaultView: PropTypes.oneOf([ "hex", "rgb", "hsl", ]), } Chrome.defaultProps = { width: 225, disableAlpha: false, styles: {}, } export default ColorWrap(Chrome) ================================================ FILE: src/components/chrome/ChromeFields.js ================================================ /* eslint-disable react/no-did-mount-set-state, no-param-reassign */ import React from 'react' import reactCSS from 'reactcss' import * as color from '../../helpers/color' import isUndefined from 'lodash/isUndefined' import { EditableInput } from '../common' import UnfoldMoreHorizontalIcon from '@icons/material/UnfoldMoreHorizontalIcon' export class ChromeFields extends React.Component { constructor(props) { super() if (props.hsl.a !== 1 && props.view === "hex") { this.state = { view: "rgb" }; } else { this.state = { view: props.view, } } } static getDerivedStateFromProps(nextProps, state) { if (nextProps.hsl.a !== 1 && state.view === 'hex') { return { view: 'rgb' } } return null } toggleViews = () => { if (this.state.view === 'hex') { this.setState({ view: 'rgb' }) } else if (this.state.view === 'rgb') { this.setState({ view: 'hsl' }) } else if (this.state.view === 'hsl') { if (this.props.hsl.a === 1) { this.setState({ view: 'hex' }) } else { this.setState({ view: 'rgb' }) } } } handleChange = (data, e) => { if (data.hex) { color.isValidHex(data.hex) && this.props.onChange({ hex: data.hex, source: 'hex', }, e) } else if (data.r || data.g || data.b) { this.props.onChange({ r: data.r || this.props.rgb.r, g: data.g || this.props.rgb.g, b: data.b || this.props.rgb.b, source: 'rgb', }, e) } else if (data.a) { if (data.a < 0) { data.a = 0 } else if (data.a > 1) { data.a = 1 } this.props.onChange({ h: this.props.hsl.h, s: this.props.hsl.s, l: this.props.hsl.l, a: Math.round(data.a * 100) / 100, source: 'rgb', }, e) } else if (data.h || data.s || data.l) { // Remove any occurances of '%'. if (typeof(data.s) === 'string' && data.s.includes('%')) { data.s = data.s.replace('%', '') } if (typeof(data.l) === 'string' && data.l.includes('%')) { data.l = data.l.replace('%', '') } // We store HSL as a unit interval so we need to override the 1 input to 0.01 if (data.s == 1) { data.s = 0.01 } else if (data.l == 1) { data.l = 0.01 } this.props.onChange({ h: data.h || this.props.hsl.h, s: Number(!isUndefined(data.s) ? data.s : this.props.hsl.s), l: Number(!isUndefined(data.l) ? data.l : this.props.hsl.l), source: 'hsl', }, e) } } showHighlight = (e) => { e.currentTarget.style.background = '#eee' } hideHighlight = (e) => { e.currentTarget.style.background = 'transparent' } render() { const styles = reactCSS({ 'default': { wrap: { paddingTop: '16px', display: 'flex', }, fields: { flex: '1', display: 'flex', marginLeft: '-6px', }, field: { paddingLeft: '6px', width: '100%', }, alpha: { paddingLeft: '6px', width: '100%', }, toggle: { width: '32px', textAlign: 'right', position: 'relative', }, icon: { marginRight: '-4px', marginTop: '12px', cursor: 'pointer', position: 'relative', }, iconHighlight: { position: 'absolute', width: '24px', height: '28px', background: '#eee', borderRadius: '4px', top: '10px', left: '12px', display: 'none', }, input: { fontSize: '11px', color: '#333', width: '100%', borderRadius: '2px', border: 'none', boxShadow: 'inset 0 0 0 1px #dadada', height: '21px', textAlign: 'center', }, label: { textTransform: 'uppercase', fontSize: '11px', lineHeight: '11px', color: '#969696', textAlign: 'center', display: 'block', marginTop: '12px', }, svg: { fill: '#333', width: '24px', height: '24px', border: '1px transparent solid', borderRadius: '5px', }, }, 'disableAlpha': { alpha: { display: 'none', }, }, }, this.props, this.state) let fields if (this.state.view === 'hex') { fields = (
) } else if (this.state.view === 'rgb') { fields = (
) } else if (this.state.view === 'hsl') { fields = (
) } return (
{ fields }
this.icon = icon }>
) } } ChromeFields.defaultProps = { view: "hex", } export default ChromeFields ================================================ FILE: src/components/chrome/ChromePointer.js ================================================ import React from 'react' import reactCSS from 'reactcss' export const ChromePointer = () => { const styles = reactCSS({ 'default': { picker: { width: '12px', height: '12px', borderRadius: '6px', transform: 'translate(-6px, -1px)', backgroundColor: 'rgb(248, 248, 248)', boxShadow: '0 1px 4px 0 rgba(0, 0, 0, 0.37)', }, }, }) return (
) } export default ChromePointer ================================================ FILE: src/components/chrome/ChromePointerCircle.js ================================================ import React from 'react' import reactCSS from 'reactcss' export const ChromePointerCircle = () => { const styles = reactCSS({ 'default': { picker: { width: '12px', height: '12px', borderRadius: '6px', boxShadow: 'inset 0 0 0 1px #fff', transform: 'translate(-6px, -6px)', }, }, }) return (
) } export default ChromePointerCircle ================================================ FILE: src/components/chrome/__snapshots__/spec.js.snap ================================================ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Chrome renders correctly 1`] = `
`; exports[`ChromeFields renders correctly 1`] = `
`; exports[`ChromePointer renders correctly 1`] = `
`; exports[`ChromePointerCircle renders correctly 1`] = `
`; ================================================ FILE: src/components/chrome/spec.js ================================================ /* global test, jest, expect */ import React from 'react' import renderer from 'react-test-renderer' import * as color from '../../helpers/color' import { mount } from 'enzyme' import Chrome from './Chrome' import ChromeFields from './ChromeFields' import ChromePointer from './ChromePointer' import ChromePointerCircle from './ChromePointerCircle' import { Alpha } from '../common' test('Chrome renders correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) test('Chrome onChange events correctly', () => { const changeSpy = jest.fn((data) => { expect(color.simpleCheckForValidColor(data)).toBeTruthy() }) const tree = mount( , ) expect(changeSpy).toHaveBeenCalledTimes(0) // check the Alpha component const alphaCommon = tree.find(Alpha) alphaCommon.at(0).childAt(2).simulate('mouseDown', { pageX: 100, pageY: 10, }) expect(changeSpy).toHaveBeenCalledTimes(1) // TODO: check the Hue component // TODO: check the ChromeFields // TODO: check Saturation }) // test('Chrome renders on server correctly', () => { // const tree = renderer.create( // // ).toJSON() // expect(tree).toMatchSnapshot() // }) test('ChromeFields renders correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) test('ChromePointer renders correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) test('ChromePointerCircle renders correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) test('Chrome renders custom styles correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree.props.style.boxShadow).toBe('none') }) test('Chrome renders correctly with width', () => { const tree = renderer.create( , ).toJSON() expect(tree.props.style.width).toBe(300) }); ================================================ FILE: src/components/chrome/story.js ================================================ import React from 'react' import { storiesOf } from '@storybook/react' import { renderWithKnobs } from '../../../.storybook/report' import SyncColorField from '../../../.storybook/SyncColorField' import Chrome from './Chrome' storiesOf('Pickers', module) .add('ChromePicker', () => ( { renderWithKnobs(Chrome, {}, null) } )) ================================================ FILE: src/components/circle/Circle.js ================================================ import React from 'react' import PropTypes from 'prop-types' import reactCSS from 'reactcss' import map from 'lodash/map' import merge from 'lodash/merge' import * as material from 'material-colors' import { ColorWrap } from '../common' import CircleSwatch from './CircleSwatch' export const Circle = ({ width, onChange, onSwatchHover, colors, hex, circleSize, styles: passedStyles = {}, circleSpacing, className = '' }) => { const styles = reactCSS(merge({ 'default': { card: { width, display: 'flex', flexWrap: 'wrap', marginRight: -circleSpacing, marginBottom: -circleSpacing, }, }, }, passedStyles)) const handleChange = (hexCode, e) => onChange({ hex: hexCode, source: 'hex' }, e) return (
{ map(colors, c => ( )) }
) } Circle.propTypes = { width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), circleSize: PropTypes.number, circleSpacing: PropTypes.number, styles: PropTypes.object, } Circle.defaultProps = { width: 252, circleSize: 28, circleSpacing: 14, colors: [material.red['500'], material.pink['500'], material.purple['500'], material.deepPurple['500'], material.indigo['500'], material.blue['500'], material.lightBlue['500'], material.cyan['500'], material.teal['500'], material.green['500'], material.lightGreen['500'], material.lime['500'], material.yellow['500'], material.amber['500'], material.orange['500'], material.deepOrange['500'], material.brown['500'], material.blueGrey['500']], styles: {}, } export default ColorWrap(Circle) ================================================ FILE: src/components/circle/CircleSwatch.js ================================================ import React from 'react' import reactCSS, { handleHover } from 'reactcss' import { Swatch } from '../common' export const CircleSwatch = ({ color, onClick, onSwatchHover, hover, active, circleSize, circleSpacing }) => { const styles = reactCSS({ 'default': { swatch: { width: circleSize, height: circleSize, marginRight: circleSpacing, marginBottom: circleSpacing, transform: 'scale(1)', transition: '100ms transform ease', }, Swatch: { borderRadius: '50%', background: 'transparent', boxShadow: `inset 0 0 0 ${ (circleSize / 2) + 1 }px ${ color }`, transition: '100ms box-shadow ease', }, }, 'hover': { swatch: { transform: 'scale(1.2)', }, }, 'active': { Swatch: { boxShadow: `inset 0 0 0 3px ${ color }`, }, }, }, { hover, active }) return (
) } CircleSwatch.defaultProps = { circleSize: 28, circleSpacing: 14, } export default handleHover(CircleSwatch) ================================================ FILE: src/components/circle/__snapshots__/spec.js.snap ================================================ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Circle renders correctly 1`] = `
`; exports[`CircleSwatch renders correctly 1`] = `
`; exports[`CircleSwatch renders with sizing and spacing 1`] = `
`; ================================================ FILE: src/components/circle/spec.js ================================================ /* global test, jest, expect */ import React from 'react' import renderer from 'react-test-renderer' import { mount } from 'enzyme' import Circle from './Circle' import CircleSwatch from './CircleSwatch' import { Swatch } from '../common' import * as color from '../../helpers/color' test('Circle renders correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) test('Circle onChange events correctly', () => { const changeSpy = jest.fn((data) => { expect(color.simpleCheckForValidColor(data)).toBeTruthy() }) const tree = mount( , ) expect(changeSpy).toHaveBeenCalledTimes(0) const swatches = tree.find(Swatch) swatches.at(0).childAt(0).simulate('click') expect(changeSpy).toHaveBeenCalled() }) test('Circle with onSwatchHover events correctly', () => { const hoverSpy = jest.fn((data) => { expect(color.simpleCheckForValidColor(data)).toBeTruthy() }) const tree = mount( , ) expect(hoverSpy).toHaveBeenCalledTimes(0) const swatches = tree.find(Swatch) swatches.at(0).childAt(0).simulate('mouseOver') expect(hoverSpy).toHaveBeenCalled() }) test('Circle renders custom styles correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree.props.style.boxShadow).toBe('none') }) test('CircleSwatch renders correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) test('CircleSwatch renders with sizing and spacing', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) ================================================ FILE: src/components/circle/story.js ================================================ import React from 'react' import { storiesOf } from '@storybook/react' import { renderWithKnobs } from '../../../.storybook/report' import SyncColorField from '../../../.storybook/SyncColorField' import Circle from './Circle' storiesOf('Pickers', module) .add('CirclePicker', () => ( { renderWithKnobs(Circle, {}, null, { width: { range: true, min: 140, max: 500, step: 1 }, circleSize: { range: true, min: 8, max: 72, step: 4 }, circleSpacing: { range: true, min: 7, max: 42, step: 7 }, }) } )) ================================================ FILE: src/components/common/Alpha.js ================================================ import React, { Component, PureComponent } from 'react' import reactCSS from 'reactcss' import * as alpha from '../../helpers/alpha' import Checkboard from './Checkboard' export class Alpha extends (PureComponent || Component) { componentWillUnmount() { this.unbindEventListeners() } handleChange = (e) => { const change = alpha.calculateChange(e, this.props.hsl, this.props.direction, this.props.a, this.container) change && typeof this.props.onChange === 'function' && this.props.onChange(change, e) } handleMouseDown = (e) => { this.handleChange(e) window.addEventListener('mousemove', this.handleChange) window.addEventListener('mouseup', this.handleMouseUp) } handleMouseUp = () => { this.unbindEventListeners() } unbindEventListeners = () => { window.removeEventListener('mousemove', this.handleChange) window.removeEventListener('mouseup', this.handleMouseUp) } render() { const rgb = this.props.rgb const styles = reactCSS({ 'default': { alpha: { absolute: '0px 0px 0px 0px', borderRadius: this.props.radius, }, checkboard: { absolute: '0px 0px 0px 0px', overflow: 'hidden', borderRadius: this.props.radius, }, gradient: { absolute: '0px 0px 0px 0px', background: `linear-gradient(to right, rgba(${ rgb.r },${ rgb.g },${ rgb.b }, 0) 0%, rgba(${ rgb.r },${ rgb.g },${ rgb.b }, 1) 100%)`, boxShadow: this.props.shadow, borderRadius: this.props.radius, }, container: { position: 'relative', height: '100%', margin: '0 3px', }, pointer: { position: 'absolute', left: `${ rgb.a * 100 }%`, }, slider: { width: '4px', borderRadius: '1px', height: '8px', boxShadow: '0 0 2px rgba(0, 0, 0, .6)', background: '#fff', marginTop: '1px', transform: 'translateX(-2px)', }, }, 'vertical': { gradient: { background: `linear-gradient(to bottom, rgba(${ rgb.r },${ rgb.g },${ rgb.b }, 0) 0%, rgba(${ rgb.r },${ rgb.g },${ rgb.b }, 1) 100%)`, }, pointer: { left: 0, top: `${ rgb.a * 100 }%`, }, }, 'overwrite': { ...this.props.style, }, }, { vertical: this.props.direction === 'vertical', overwrite: true, }) return (
this.container = container } onMouseDown={ this.handleMouseDown } onTouchMove={ this.handleChange } onTouchStart={ this.handleChange } >
{ this.props.pointer ? ( ) : (
) }
) } } export default Alpha ================================================ FILE: src/components/common/Checkboard.js ================================================ import React, { isValidElement } from 'react' import reactCSS from 'reactcss' import * as checkboard from '../../helpers/checkboard' export const Checkboard = ({ white, grey, size, renderers, borderRadius, boxShadow, children }) => { const styles = reactCSS({ 'default': { grid: { borderRadius, boxShadow, absolute: '0px 0px 0px 0px', background: `url(${ checkboard.get(white, grey, size, renderers.canvas) }) center left`, }, }, }) return isValidElement(children)?React.cloneElement(children, { ...children.props, style: {...children.props.style,...styles.grid}}):
; } Checkboard.defaultProps = { size: 8, white: 'transparent', grey: 'rgba(0,0,0,.08)', renderers: {}, } export default Checkboard ================================================ FILE: src/components/common/ColorWrap.js ================================================ import React, { Component, PureComponent } from 'react' import debounce from 'lodash/debounce' import * as color from '../../helpers/color' export const ColorWrap = (Picker) => { class ColorPicker extends (PureComponent || Component) { constructor(props) { super() this.state = { ...color.toState(props.color, 0), } this.debounce = debounce((fn, data, event) => { fn(data, event) }, 100) } static getDerivedStateFromProps(nextProps, state) { return { ...color.toState(nextProps.color, state.oldHue), } } handleChange = (data, event) => { const isValidColor = color.simpleCheckForValidColor(data) if (isValidColor) { const colors = color.toState(data, data.h || this.state.oldHue) this.setState(colors) this.props.onChangeComplete && this.debounce(this.props.onChangeComplete, colors, event) this.props.onChange && this.props.onChange(colors, event) } } handleSwatchHover = (data, event) => { const isValidColor = color.simpleCheckForValidColor(data) if (isValidColor) { const colors = color.toState(data, data.h || this.state.oldHue) this.props.onSwatchHover && this.props.onSwatchHover(colors, event) } } render() { const optionalEvents = {} if (this.props.onSwatchHover) { optionalEvents.onSwatchHover = this.handleSwatchHover } return ( ) } } ColorPicker.propTypes = { ...Picker.propTypes, } ColorPicker.defaultProps = { ...Picker.defaultProps, color: { h: 250, s: 0.50, l: 0.20, a: 1, }, } return ColorPicker } export default ColorWrap ================================================ FILE: src/components/common/EditableInput.js ================================================ import React, { Component, PureComponent } from 'react' import reactCSS from 'reactcss' const DEFAULT_ARROW_OFFSET = 1 const UP_KEY_CODE = 38 const DOWN_KEY_CODE = 40 const VALID_KEY_CODES = [ UP_KEY_CODE, DOWN_KEY_CODE ] const isValidKeyCode = keyCode => VALID_KEY_CODES.indexOf(keyCode) > -1 const getNumberValue = value => Number(String(value).replace(/%/g, '')) let idCounter = 1 export class EditableInput extends (PureComponent || Component) { constructor(props) { super() this.state = { value: String(props.value).toUpperCase(), blurValue: String(props.value).toUpperCase(), } this.inputId = `rc-editable-input-${idCounter++}` } componentDidUpdate(prevProps, prevState) { if ( this.props.value !== this.state.value && (prevProps.value !== this.props.value || prevState.value !== this.state.value) ) { if (this.input === document.activeElement) { this.setState({ blurValue: String(this.props.value).toUpperCase() }) } else { this.setState({ value: String(this.props.value).toUpperCase(), blurValue: !this.state.blurValue && String(this.props.value).toUpperCase() }) } } } componentWillUnmount() { this.unbindEventListeners() } getValueObjectWithLabel(value) { return { [this.props.label]: value } } handleBlur = () => { if (this.state.blurValue) { this.setState({ value: this.state.blurValue, blurValue: null }) } } handleChange = (e) => { this.setUpdatedValue(e.target.value, e) } getArrowOffset() { return this.props.arrowOffset || DEFAULT_ARROW_OFFSET } handleKeyDown = (e) => { // In case `e.target.value` is a percentage remove the `%` character // and update accordingly with a percentage // https://github.com/casesandberg/react-color/issues/383 const value = getNumberValue(e.target.value) if (!isNaN(value) && isValidKeyCode(e.keyCode)) { const offset = this.getArrowOffset() const updatedValue = e.keyCode === UP_KEY_CODE ? value + offset : value - offset this.setUpdatedValue(updatedValue, e) } } setUpdatedValue(value, e) { const onChangeValue = this.props.label ? this.getValueObjectWithLabel(value) : value this.props.onChange && this.props.onChange(onChangeValue, e) this.setState({ value }) } handleDrag = (e) => { if (this.props.dragLabel) { const newValue = Math.round(this.props.value + e.movementX) if (newValue >= 0 && newValue <= this.props.dragMax) { this.props.onChange && this.props.onChange(this.getValueObjectWithLabel(newValue), e) } } } handleMouseDown = (e) => { if (this.props.dragLabel) { e.preventDefault() this.handleDrag(e) window.addEventListener('mousemove', this.handleDrag) window.addEventListener('mouseup', this.handleMouseUp) } } handleMouseUp = () => { this.unbindEventListeners() } unbindEventListeners = () => { window.removeEventListener('mousemove', this.handleDrag) window.removeEventListener('mouseup', this.handleMouseUp) } render() { const styles = reactCSS({ 'default': { wrap: { position: 'relative', }, }, 'user-override': { wrap: this.props.style && this.props.style.wrap ? this.props.style.wrap : {}, input: this.props.style && this.props.style.input ? this.props.style.input : {}, label: this.props.style && this.props.style.label ? this.props.style.label : {}, }, 'dragLabel-true': { label: { cursor: 'ew-resize', }, }, }, { 'user-override': true, }, this.props) return (
this.input = input } value={ this.state.value } onKeyDown={ this.handleKeyDown } onChange={ this.handleChange } onBlur={ this.handleBlur } placeholder={ this.props.placeholder } spellCheck="false" /> { this.props.label && !this.props.hideLabel ? ( ) : null }
) } } export default EditableInput ================================================ FILE: src/components/common/Hue.js ================================================ import React, { Component, PureComponent } from 'react' import reactCSS from 'reactcss' import * as hue from '../../helpers/hue' export class Hue extends (PureComponent || Component) { componentWillUnmount() { this.unbindEventListeners() } handleChange = (e) => { const change = hue.calculateChange(e, this.props.direction, this.props.hsl, this.container) change && typeof this.props.onChange === 'function' && this.props.onChange(change, e) } handleMouseDown = (e) => { this.handleChange(e) window.addEventListener('mousemove', this.handleChange) window.addEventListener('mouseup', this.handleMouseUp) } handleMouseUp = () => { this.unbindEventListeners() } unbindEventListeners() { window.removeEventListener('mousemove', this.handleChange) window.removeEventListener('mouseup', this.handleMouseUp) } render() { const { direction = 'horizontal' } = this.props const styles = reactCSS({ 'default': { hue: { absolute: '0px 0px 0px 0px', borderRadius: this.props.radius, boxShadow: this.props.shadow, }, container: { padding: '0 2px', position: 'relative', height: '100%', borderRadius: this.props.radius, }, pointer: { position: 'absolute', left: `${ (this.props.hsl.h * 100) / 360 }%`, }, slider: { marginTop: '1px', width: '4px', borderRadius: '1px', height: '8px', boxShadow: '0 0 2px rgba(0, 0, 0, .6)', background: '#fff', transform: 'translateX(-2px)', }, }, 'vertical': { pointer: { left: '0px', top: `${ -((this.props.hsl.h * 100) / 360) + 100 }%`, }, }, }, { vertical: direction === 'vertical' }) return (
this.container = container } onMouseDown={ this.handleMouseDown } onTouchMove={ this.handleChange } onTouchStart={ this.handleChange } >
{ this.props.pointer ? ( ) : (
) }
) } } export default Hue ================================================ FILE: src/components/common/Raised.js ================================================ import React from 'react' import PropTypes from 'prop-types' import reactCSS from 'reactcss' import merge from 'lodash/merge' export const Raised = ({ zDepth, radius, background, children, styles: passedStyles = {} }) => { const styles = reactCSS(merge({ 'default': { wrap: { position: 'relative', display: 'inline-block', }, content: { position: 'relative', }, bg: { absolute: '0px 0px 0px 0px', boxShadow: `0 ${ zDepth }px ${ zDepth * 4 }px rgba(0,0,0,.24)`, borderRadius: radius, background, }, }, 'zDepth-0': { bg: { boxShadow: 'none', }, }, 'zDepth-1': { bg: { boxShadow: '0 2px 10px rgba(0,0,0,.12), 0 2px 5px rgba(0,0,0,.16)', }, }, 'zDepth-2': { bg: { boxShadow: '0 6px 20px rgba(0,0,0,.19), 0 8px 17px rgba(0,0,0,.2)', }, }, 'zDepth-3': { bg: { boxShadow: '0 17px 50px rgba(0,0,0,.19), 0 12px 15px rgba(0,0,0,.24)', }, }, 'zDepth-4': { bg: { boxShadow: '0 25px 55px rgba(0,0,0,.21), 0 16px 28px rgba(0,0,0,.22)', }, }, 'zDepth-5': { bg: { boxShadow: '0 40px 77px rgba(0,0,0,.22), 0 27px 24px rgba(0,0,0,.2)', }, }, 'square': { bg: { borderRadius: '0', }, }, 'circle': { bg: { borderRadius: '50%', }, }, }, passedStyles), { 'zDepth-1': zDepth === 1 }) return (
{ children }
) } Raised.propTypes = { background: PropTypes.string, zDepth: PropTypes.oneOf([0, 1, 2, 3, 4, 5]), radius: PropTypes.number, styles: PropTypes.object, } Raised.defaultProps = { background: '#fff', zDepth: 1, radius: 2, styles: {}, } export default Raised ================================================ FILE: src/components/common/Saturation.js ================================================ import React, { Component, PureComponent } from 'react' import reactCSS from 'reactcss' import throttle from 'lodash/throttle' import * as saturation from '../../helpers/saturation' export class Saturation extends (PureComponent || Component) { constructor(props) { super(props) this.throttle = throttle((fn, data, e) => { fn(data, e) }, 50) } componentWillUnmount() { this.throttle.cancel() this.unbindEventListeners() } getContainerRenderWindow() { const { container } = this let renderWindow = window while (!renderWindow.document.contains(container) && renderWindow.parent !== renderWindow) { renderWindow = renderWindow.parent } return renderWindow } handleChange = (e) => { typeof this.props.onChange === 'function' && this.throttle( this.props.onChange, saturation.calculateChange(e, this.props.hsl, this.container), e, ) } handleMouseDown = (e) => { this.handleChange(e) const renderWindow = this.getContainerRenderWindow() renderWindow.addEventListener('mousemove', this.handleChange) renderWindow.addEventListener('mouseup', this.handleMouseUp) } handleMouseUp = () => { this.unbindEventListeners() } unbindEventListeners() { const renderWindow = this.getContainerRenderWindow() renderWindow.removeEventListener('mousemove', this.handleChange) renderWindow.removeEventListener('mouseup', this.handleMouseUp) } render() { const { color, white, black, pointer, circle } = this.props.style || {} const styles = reactCSS({ 'default': { color: { absolute: '0px 0px 0px 0px', background: `hsl(${ this.props.hsl.h },100%, 50%)`, borderRadius: this.props.radius, }, white: { absolute: '0px 0px 0px 0px', borderRadius: this.props.radius, }, black: { absolute: '0px 0px 0px 0px', boxShadow: this.props.shadow, borderRadius: this.props.radius, }, pointer: { position: 'absolute', top: `${ -(this.props.hsv.v * 100) + 100 }%`, left: `${ this.props.hsv.s * 100 }%`, cursor: 'default', }, circle: { width: '4px', height: '4px', boxShadow: `0 0 0 1.5px #fff, inset 0 0 1px 1px rgba(0,0,0,.3), 0 0 1px 2px rgba(0,0,0,.4)`, borderRadius: '50%', cursor: 'hand', transform: 'translate(-2px, -2px)', }, }, 'custom': { color, white, black, pointer, circle, }, }, { 'custom': !!this.props.style }) return (
this.container = container } onMouseDown={ this.handleMouseDown } onTouchMove={ this.handleChange } onTouchStart={ this.handleChange } >
{ this.props.pointer ? ( ) : (
) }
) } } export default Saturation ================================================ FILE: src/components/common/Swatch.js ================================================ import React from 'react' import reactCSS from 'reactcss' import { handleFocus } from '../../helpers/interaction' import Checkboard from './Checkboard' const ENTER = 13 export const Swatch = ({ color, style, onClick = () => {}, onHover, title = color, children, focus, focusStyle = {} }) => { const transparent = color === 'transparent' const styles = reactCSS({ default: { swatch: { background: color, height: '100%', width: '100%', cursor: 'pointer', position: 'relative', outline: 'none', ...style, ...(focus ? focusStyle : {}), }, }, }) const handleClick = e => onClick(color, e) const handleKeyDown = e => e.keyCode === ENTER && onClick(color, e) const handleHover = e => onHover(color, e) const optionalEvents = {} if (onHover) { optionalEvents.onMouseOver = handleHover } return (
{ children } { transparent && ( ) }
) } export default handleFocus(Swatch) ================================================ FILE: src/components/common/__snapshots__/spec.js.snap ================================================ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Alpha renders correctly 1`] = `
`; exports[`Checkboard renders children correctly 1`] = ` `; exports[`Checkboard renders correctly 1`] = `
`; exports[`EditableInput renders correctly 1`] = `
`; exports[`Hue renders correctly 1`] = `
`; exports[`Saturation renders correctly 1`] = `
`; exports[`Swatch renders correctly 1`] = `
`; exports[`Swatch renders custom title correctly 1`] = `
`; exports[`Swatch renders with an onMouseOver handler correctly 1`] = `
`; ================================================ FILE: src/components/common/index.js ================================================ export { default as Alpha } from './Alpha' export { default as Checkboard } from './Checkboard' export { default as EditableInput } from './EditableInput' export { default as Hue } from './Hue' export { default as Raised } from './Raised' export { default as Saturation } from './Saturation' export { default as ColorWrap } from './ColorWrap' export { default as Swatch } from './Swatch' ================================================ FILE: src/components/common/spec.js ================================================ /* global test, jest, expect */ import React from 'react' import renderer from 'react-test-renderer' import { red } from '../../helpers/color' // import canvas from 'canvas' import Alpha from './Alpha' import Checkboard from './Checkboard' import EditableInput from './EditableInput' import Hue from './Hue' import Saturation from './Saturation' import Swatch from './Swatch' test('Alpha renders correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) // test('Alpha renders on server correctly', () => { // const tree = renderer.create( // // ).toJSON() // expect(tree).toMatchSnapshot() // }) test('Checkboard renders correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) test('Checkboard renders children correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) // test('Checkboard renders on server correctly', () => { // const tree = renderer.create( // // ).toJSON() // expect(tree).toMatchSnapshot() // }) test('EditableInput renders correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) test('Hue renders correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) test('Saturation renders correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) test('Swatch renders correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) test('Swatch renders custom title correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) test('Swatch renders with an onMouseOver handler correctly', () => { const tree = renderer.create( {} } />, ).toJSON() expect(tree).toMatchSnapshot() }) ================================================ FILE: src/components/compact/Compact.js ================================================ import React from 'react' import PropTypes from 'prop-types' import reactCSS from 'reactcss' import map from 'lodash/map' import merge from 'lodash/merge' import * as color from '../../helpers/color' import { ColorWrap, Raised } from '../common' import CompactColor from './CompactColor' import CompactFields from './CompactFields' export const Compact = ({ onChange, onSwatchHover, colors, hex, rgb, styles: passedStyles = {}, className = '' }) => { const styles = reactCSS(merge({ 'default': { Compact: { background: '#f6f6f6', radius: '4px', }, compact: { paddingTop: '5px', paddingLeft: '5px', boxSizing: 'initial', width: '240px', }, clear: { clear: 'both', }, }, }, passedStyles)) const handleChange = (data, e) => { if (data.hex) { color.isValidHex(data.hex) && onChange({ hex: data.hex, source: 'hex', }, e) } else { onChange(data, e) } } return (
{ map(colors, (c) => ( )) }
) } Compact.propTypes = { colors: PropTypes.arrayOf(PropTypes.string), styles: PropTypes.object, } Compact.defaultProps = { colors: ['#4D4D4D', '#999999', '#FFFFFF', '#F44E3B', '#FE9200', '#FCDC00', '#DBDF00', '#A4DD00', '#68CCCA', '#73D8FF', '#AEA1FF', '#FDA1FF', '#333333', '#808080', '#cccccc', '#D33115', '#E27300', '#FCC400', '#B0BC00', '#68BC00', '#16A5A5', '#009CE0', '#7B64FF', '#FA28FF', '#000000', '#666666', '#B3B3B3', '#9F0500', '#C45100', '#FB9E00', '#808900', '#194D33', '#0C797D', '#0062B1', '#653294', '#AB149E', ], styles: {}, } export default ColorWrap(Compact) ================================================ FILE: src/components/compact/CompactColor.js ================================================ import React from 'react' import reactCSS from 'reactcss' import * as colorUtils from '../../helpers/color' import { Swatch } from '../common' export const CompactColor = ({ color, onClick = () => {}, onSwatchHover, active }) => { const styles = reactCSS({ 'default': { color: { background: color, width: '15px', height: '15px', float: 'left', marginRight: '5px', marginBottom: '5px', position: 'relative', cursor: 'pointer', }, dot: { absolute: '5px 5px 5px 5px', background: colorUtils.getContrastingColor(color), borderRadius: '50%', opacity: '0', }, }, 'active': { dot: { opacity: '1', }, }, 'color-#FFFFFF': { color: { boxShadow: 'inset 0 0 0 1px #ddd', }, dot: { background: '#000', }, }, 'transparent': { dot: { background: '#000', }, }, }, { active, 'color-#FFFFFF': color === '#FFFFFF', 'transparent': color === 'transparent' }) return (
) } export default CompactColor ================================================ FILE: src/components/compact/CompactFields.js ================================================ import React from 'react' import reactCSS from 'reactcss' import { EditableInput } from '../common' export const CompactFields = ({ hex, rgb, onChange }) => { const styles = reactCSS({ 'default': { fields: { display: 'flex', paddingBottom: '6px', paddingRight: '5px', position: 'relative', }, active: { position: 'absolute', top: '6px', left: '5px', height: '9px', width: '9px', background: hex, }, HEXwrap: { flex: '6', position: 'relative', }, HEXinput: { width: '80%', padding: '0px', paddingLeft: '20%', border: 'none', outline: 'none', background: 'none', fontSize: '12px', color: '#333', height: '16px', }, HEXlabel: { display: 'none', }, RGBwrap: { flex: '3', position: 'relative', }, RGBinput: { width: '70%', padding: '0px', paddingLeft: '30%', border: 'none', outline: 'none', background: 'none', fontSize: '12px', color: '#333', height: '16px', }, RGBlabel: { position: 'absolute', top: '3px', left: '0px', lineHeight: '16px', textTransform: 'uppercase', fontSize: '12px', color: '#999', }, }, }) const handleChange = (data, e) => { if (data.r || data.g || data.b) { onChange({ r: data.r || rgb.r, g: data.g || rgb.g, b: data.b || rgb.b, source: 'rgb', }, e) } else { onChange({ hex: data.hex, source: 'hex', }, e) } } return (
) } export default CompactFields ================================================ FILE: src/components/compact/__snapshots__/spec.js.snap ================================================ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Compact renders correctly 1`] = `
`; exports[`Compact with onSwatchHover renders correctly 1`] = `
`; exports[`CompactColor renders correctly 1`] = `
`; exports[`CompactFields renders correctly 1`] = `
`; ================================================ FILE: src/components/compact/spec.js ================================================ /* global test, jest, expect */ import React from 'react' import renderer from 'react-test-renderer' import { mount } from 'enzyme' import * as color from '../../helpers/color' import Compact from './Compact' import CompactColor from './CompactColor' import CompactFields from './CompactFields' import { Swatch } from '../common' test('Compact renders correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) test('Compact with onSwatchHover renders correctly', () => { const tree = renderer.create( {} } />, ).toJSON() expect(tree).toMatchSnapshot() }) test('Compact onChange events correctly', () => { const changeSpy = jest.fn((data) => { expect(color.simpleCheckForValidColor(data)).toBeTruthy() }) const tree = mount( , ) expect(changeSpy).toHaveBeenCalledTimes(0) const swatches = tree.find(Swatch) swatches.at(0).childAt(0).simulate('click') expect(changeSpy).toHaveBeenCalled() }) test('Compact with onSwatchHover events correctly', () => { const hoverSpy = jest.fn((data) => { expect(color.simpleCheckForValidColor(data)).toBeTruthy() }) const tree = mount( , ) expect(hoverSpy).toHaveBeenCalledTimes(0) const swatches = tree.find(Swatch) swatches.at(0).childAt(0).simulate('mouseOver') expect(hoverSpy).toHaveBeenCalled() }) test('CompactColor renders correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) test('CompactFields renders correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) test('Compact renders custom styles correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree.props.style.boxShadow).toBe('0 0 10px red') }) ================================================ FILE: src/components/compact/story.js ================================================ import React from 'react' import { storiesOf } from '@storybook/react' import { renderWithKnobs } from '../../../.storybook/report' import SyncColorField from '../../../.storybook/SyncColorField' import Compact from './Compact' storiesOf('Pickers', module) .add('CompactPicker', () => ( { renderWithKnobs(Compact, {}, null, { width: { range: true, min: 140, max: 500, step: 1 }, circleSize: { range: true, min: 8, max: 72, step: 4 }, circleSpacing: { range: true, min: 7, max: 42, step: 7 }, }) } )) ================================================ FILE: src/components/github/Github.js ================================================ import React from 'react' import PropTypes from 'prop-types' import reactCSS from 'reactcss' import map from 'lodash/map' import merge from 'lodash/merge' import { ColorWrap } from '../common' import GithubSwatch from './GithubSwatch' export const Github = ({ width, colors, onChange, onSwatchHover, triangle, styles: passedStyles = {}, className = '' }) => { const styles = reactCSS(merge({ 'default': { card: { width, background: '#fff', border: '1px solid rgba(0,0,0,0.2)', boxShadow: '0 3px 12px rgba(0,0,0,0.15)', borderRadius: '4px', position: 'relative', padding: '5px', display: 'flex', flexWrap: 'wrap', }, triangle: { position: 'absolute', border: '7px solid transparent', borderBottomColor: '#fff', }, triangleShadow: { position: 'absolute', border: '8px solid transparent', borderBottomColor: 'rgba(0,0,0,0.15)', }, }, 'hide-triangle': { triangle: { display: 'none', }, triangleShadow: { display: 'none', }, }, 'top-left-triangle': { triangle: { top: '-14px', left: '10px', }, triangleShadow: { top: '-16px', left: '9px', }, }, 'top-right-triangle': { triangle: { top: '-14px', right: '10px', }, triangleShadow: { top: '-16px', right: '9px', }, }, 'bottom-left-triangle': { triangle: { top: '35px', left: '10px', transform: 'rotate(180deg)', }, triangleShadow: { top: '37px', left: '9px', transform: 'rotate(180deg)', }, }, 'bottom-right-triangle': { triangle: { top: '35px', right: '10px', transform: 'rotate(180deg)', }, triangleShadow: { top: '37px', right: '9px', transform: 'rotate(180deg)', }, }, }, passedStyles), { 'hide-triangle': triangle === 'hide', 'top-left-triangle': triangle === 'top-left', 'top-right-triangle': triangle === 'top-right', 'bottom-left-triangle': triangle === 'bottom-left', 'bottom-right-triangle': triangle === 'bottom-right', }) const handleChange = (hex, e) => onChange({ hex, source: 'hex' }, e) return (
{ map(colors, c => ( )) }
) } Github.propTypes = { width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), colors: PropTypes.arrayOf(PropTypes.string), triangle: PropTypes.oneOf(['hide', 'top-left', 'top-right', 'bottom-left', 'bottom-right']), styles: PropTypes.object, } Github.defaultProps = { width: 200, colors: ['#B80000', '#DB3E00', '#FCCB00', '#008B02', '#006B76', '#1273DE', '#004DCF', '#5300EB', '#EB9694', '#FAD0C3', '#FEF3BD', '#C1E1C5', '#BEDADC', '#C4DEF6', '#BED3F3', '#D4C4FB'], triangle: 'top-left', styles: {}, } export default ColorWrap(Github) ================================================ FILE: src/components/github/GithubSwatch.js ================================================ import React from 'react' import reactCSS, { handleHover } from 'reactcss' import { Swatch } from '../common' export const GithubSwatch = ({ hover, color, onClick, onSwatchHover }) => { const hoverSwatch = { position: 'relative', zIndex: '2', outline: '2px solid #fff', boxShadow: '0 0 5px 2px rgba(0,0,0,0.25)', } const styles = reactCSS({ 'default': { swatch: { width: '25px', height: '25px', fontSize: '0', }, }, 'hover': { swatch: hoverSwatch, }, }, { hover }) return (
) } export default handleHover(GithubSwatch) ================================================ FILE: src/components/github/__snapshots__/spec.js.snap ================================================ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Github \`triangle="hide"\` 1`] = `
`; exports[`Github \`triangle="top-right"\` 1`] = `
`; exports[`Github renders correctly 1`] = `
`; exports[`GithubSwatch renders correctly 1`] = `
`; ================================================ FILE: src/components/github/spec.js ================================================ /* global test, jest, expect */ import React from 'react' import renderer from 'react-test-renderer' import { mount } from 'enzyme' import * as color from '../../helpers/color' import Github from './Github' import GithubSwatch from './GithubSwatch' import { Swatch } from '../common' test('Github renders correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) test('Github onChange events correctly', () => { const changeSpy = jest.fn((data) => { expect(color.simpleCheckForValidColor(data)).toBeTruthy() }) const tree = mount( , ) expect(changeSpy).toHaveBeenCalledTimes(0) const swatches = tree.find(Swatch) swatches.at(0).childAt(0).simulate('click') expect(changeSpy).toHaveBeenCalled() }) test('Github with onSwatchHover events correctly', () => { const hoverSpy = jest.fn((data) => { expect(color.simpleCheckForValidColor(data)).toBeTruthy() }) const tree = mount( , ) expect(hoverSpy).toHaveBeenCalledTimes(0) const swatches = tree.find(Swatch) swatches.at(0).childAt(0).simulate('mouseOver') expect(hoverSpy).toHaveBeenCalled() }) test('Github `triangle="hide"`', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) test('Github `triangle="top-right"`', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) test('Github renders custom styles correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree.props.style.boxShadow).toBe('0 0 10px red') }) test('GithubSwatch renders correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) ================================================ FILE: src/components/github/story.js ================================================ import React from 'react' import { storiesOf } from '@storybook/react' import { renderWithKnobs } from '../../../.storybook/report' import SyncColorField from '../../../.storybook/SyncColorField' import Github from './Github' storiesOf('Pickers', module) .add('GithubPicker', () => ( { renderWithKnobs(Github, {}, null, { width: { range: true, min: 140, max: 500, step: 1 }, }) } )) ================================================ FILE: src/components/google/Google.js ================================================ import React from 'react' import PropTypes from 'prop-types' import reactCSS from 'reactcss' import merge from 'lodash/merge' import { ColorWrap, Saturation, Hue } from '../common' import GooglePointerCircle from './GooglePointerCircle' import GooglePointer from './GooglePointer' import GoogleFields from './GoogleFields' export const Google = ({ width, onChange, rgb, hsl, hsv, hex, header, styles: passedStyles = {}, className = '' }) => { const styles = reactCSS(merge({ 'default': { picker: { width, background: '#fff', border: '1px solid #dfe1e5', boxSizing: 'initial', display: 'flex', flexWrap: 'wrap', borderRadius: '8px 8px 0px 0px', }, head: { height: '57px', width: '100%', paddingTop: '16px', paddingBottom: '16px', paddingLeft: '16px', fontSize: '20px', boxSizing: 'border-box', fontFamily: 'Roboto-Regular,HelveticaNeue,Arial,sans-serif', }, saturation: { width: '70%', padding: '0px', position: 'relative', overflow: 'hidden', }, swatch: { width: '30%', height: '228px', padding: '0px', background: `rgba(${ rgb.r }, ${ rgb.g }, ${ rgb.b }, 1)`, position: 'relative', overflow: 'hidden', }, body: { margin: 'auto', width: '95%', }, controls: { display: 'flex', boxSizing: 'border-box', height: '52px', paddingTop: '22px', }, color: { width: '32px', }, hue: { height: '8px', position: 'relative', margin: '0px 16px 0px 16px', width: '100%', }, Hue: { radius: '2px', }, }, }, passedStyles)) return (
{ header }
) } Google.propTypes = { width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), styles: PropTypes.object, header: PropTypes.string, } Google.defaultProps = { width: 652, styles: {}, header: 'Color picker', } export default ColorWrap(Google) ================================================ FILE: src/components/google/GoogleFields.js ================================================ import React from 'react' import reactCSS from 'reactcss' import * as color from '../../helpers/color' import { EditableInput } from '../common' export const GoogleFields = ({ onChange, rgb, hsl, hex, hsv }) => { const handleChange = (data, e) => { if (data.hex) { color.isValidHex(data.hex) && onChange({ hex: data.hex, source: 'hex', }, e) } else if (data.rgb) { const values = data.rgb.split(',') color.isvalidColorString(data.rgb, 'rgb') && onChange({ r: values[0], g: values[1], b: values[2], a: 1, source: 'rgb', }, e) } else if (data.hsv){ const values = data.hsv.split(',') if (color.isvalidColorString(data.hsv, 'hsv')){ values[2] = values[2].replace('%', '') values[1] = values[1].replace('%', '') values[0] = values[0].replace('°', '') if (values[1] == 1) { values[1] = 0.01 } else if (values[2] == 1) { values[2] = 0.01 } onChange({ h: Number(values[0]), s: Number(values[1]), v: Number(values[2]), source: 'hsv', }, e) } } else if (data.hsl) { const values = data.hsl.split(',') if (color.isvalidColorString(data.hsl, 'hsl')){ values[2] = values[2].replace('%', '') values[1] = values[1].replace('%', '') values[0] = values[0].replace('°', '') if (hsvValue[1] == 1) { hsvValue[1] = 0.01 } else if (hsvValue[2] == 1) { hsvValue[2] = 0.01 } onChange({ h: Number(values[0]), s: Number(values[1]), v: Number(values[2]), source: 'hsl', }, e) } } } const styles = reactCSS({ 'default': { wrap: { display: 'flex', height: '100px', marginTop: '4px', }, fields: { width: '100%', }, column: { paddingTop: '10px', display: 'flex', justifyContent: 'space-between', }, double: { padding: '0px 4.4px', boxSizing: 'border-box', }, input: { width: '100%', height: '38px', boxSizing: 'border-box', padding: '4px 10% 3px', textAlign: 'center', border: '1px solid #dadce0', fontSize: '11px', textTransform: 'lowercase', borderRadius: '5px', outline: 'none', fontFamily: 'Roboto,Arial,sans-serif', }, input2: { height: '38px', width: '100%', border: '1px solid #dadce0', boxSizing: 'border-box', fontSize: '11px', textTransform: 'lowercase', borderRadius: '5px', outline: 'none', paddingLeft: '10px', fontFamily: 'Roboto,Arial,sans-serif', }, label: { textAlign: 'center', fontSize: '12px', background: '#fff', position: 'absolute', textTransform: 'uppercase', color: '#3c4043', width: '35px', top: '-6px', left: '0', right: '0', marginLeft: 'auto', marginRight: 'auto', fontFamily: 'Roboto,Arial,sans-serif', }, label2: { left: '10px', textAlign: 'center', fontSize: '12px', background: '#fff', position: 'absolute', textTransform: 'uppercase', color: '#3c4043', width: '32px', top: '-6px', fontFamily: 'Roboto,Arial,sans-serif', }, single: { flexGrow: '1', margin: '0px 4.4px', }, }, }) const rgbValue = `${ rgb.r }, ${ rgb.g }, ${ rgb.b }` const hslValue = `${ Math.round(hsl.h) }°, ${ Math.round(hsl.s * 100) }%, ${ Math.round(hsl.l * 100) }%` const hsvValue = `${ Math.round(hsv.h) }°, ${ Math.round(hsv.s * 100) }%, ${ Math.round(hsv.v * 100) }%` return (
) } export default GoogleFields ================================================ FILE: src/components/google/GooglePointer.js ================================================ import React from 'react' import reactCSS from 'reactcss' import PropTypes from 'prop-types' export const GooglePointer = (props) => { const styles = reactCSS({ 'default': { picker: { width: '20px', height: '20px', borderRadius: '22px', transform: 'translate(-10px, -7px)', background: `hsl(${ Math.round(props.hsl.h) }, 100%, 50%)`, border: '2px white solid', }, }, }) return (
) } GooglePointer.propTypes = { hsl: PropTypes.shape({ h: PropTypes.number, s: PropTypes.number, l: PropTypes.number, a: PropTypes.number, }), } GooglePointer.defaultProps = { hsl: { a: 1, h: 249.94, l: 0.2, s: 0.50 }, } export default GooglePointer ================================================ FILE: src/components/google/GooglePointerCircle.js ================================================ import React from 'react' import reactCSS from 'reactcss' import PropTypes from 'prop-types' export const GooglePointerCircle = (props) => { const styles = reactCSS({ 'default': { picker: { width: '20px', height: '20px', borderRadius: '22px', border: '2px #fff solid', transform: 'translate(-12px, -13px)', background: `hsl(${ Math.round(props.hsl.h) }, ${ Math.round(props.hsl.s * 100 ) }%, ${ Math.round(props.hsl.l * 100) }%)`, }, }, }) return (
) } GooglePointerCircle.propTypes = { hsl: PropTypes.shape({ h: PropTypes.number, s: PropTypes.number, l: PropTypes.number, a: PropTypes.number, }), } GooglePointerCircle.defaultProps = { hsl: { a: 1, h: 249.94, l: 0.2, s: 0.50 }, } export default GooglePointerCircle ================================================ FILE: src/components/google/__snapshots__/spec.js.snap ================================================ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Google renders correctly 1`] = `
Color picker
`; exports[`GoogleFields renders correctly 1`] = `
`; exports[`GooglePointer renders correctly 1`] = `
`; exports[`GooglePointerCircle renders correctly 1`] = `
`; ================================================ FILE: src/components/google/spec.js ================================================ import React from 'react' import renderer from 'react-test-renderer' import * as color from '../../helpers/color' import { mount } from 'enzyme' import Google from './Google' import GoogleFields from './GoogleFields' import GooglePointer from './GooglePointer' import GooglePointerCircle from './GooglePointerCircle' test('Google renders correctly', () => { const tree = renderer.create().toJSON() expect(tree).toMatchSnapshot() }) test('Google onChange events correctly', () => { const changeSpy = jest.fn((data) => { expect(color.simpleCheckForValidColor(data)).toBeTruthy() }) const tree = mount( , ) expect(changeSpy).toHaveBeenCalledTimes(0) }) test('GoogleFields renders correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) test('GooglePointer renders correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) test('GooglePointerCircle renders correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) test('Google renders custom styles correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree.props.style.width).toBe('200px') }) test('Google renders correctly with width', () => { const tree = renderer.create( , ).toJSON() expect(tree.props.style.width).toBe(200) }) test('Google custom header correctly', () => { const tree = mount( , ) expect(tree.instance().props.header).toBe('Change the color!!!') }) ================================================ FILE: src/components/google/story.js ================================================ import React from 'react' import { storiesOf } from '@storybook/react' import { renderWithKnobs } from '../../../.storybook/report' import SyncColorField from '../../../.storybook/SyncColorField' import Google from './Google' storiesOf('Pickers', module) .add('GooglePicker', () => ( { renderWithKnobs(Google, {}, null) } )) ================================================ FILE: src/components/hue/Hue.js ================================================ import React from 'react' import PropTypes from 'prop-types' import reactCSS from 'reactcss' import merge from 'lodash/merge' import { ColorWrap, Hue } from '../common' import HuePointer from './HuePointer' export const HuePicker = ({ width, height, onChange, hsl, direction, pointer, styles: passedStyles = {}, className = '' }) => { const styles = reactCSS(merge({ 'default': { picker: { position: 'relative', width, height, }, hue: { radius: '2px', }, }, }, passedStyles)) // Overwrite to provide pure hue color const handleChange = data => onChange({ a: 1, h: data.h, l: 0.5, s: 1 }) return (
) } HuePicker.propTypes = { styles: PropTypes.object, } HuePicker.defaultProps = { width: '316px', height: '16px', direction: 'horizontal', pointer: HuePointer, styles: {}, } export default ColorWrap(HuePicker) ================================================ FILE: src/components/hue/HuePointer.js ================================================ import React from 'react' import reactCSS from 'reactcss' export const SliderPointer = ({ direction }) => { const styles = reactCSS({ 'default': { picker: { width: '18px', height: '18px', borderRadius: '50%', transform: 'translate(-9px, -1px)', backgroundColor: 'rgb(248, 248, 248)', boxShadow: '0 1px 4px 0 rgba(0, 0, 0, 0.37)', }, }, 'vertical': { picker: { transform: 'translate(-3px, -9px)', }, }, }, { vertical: direction === 'vertical' }) return (
) } export default SliderPointer ================================================ FILE: src/components/hue/__snapshots__/spec.js.snap ================================================ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Hue renders correctly 1`] = `
`; exports[`Hue renders vertically 1`] = `
`; exports[`HuePointer renders correctly 1`] = `
`; ================================================ FILE: src/components/hue/spec.js ================================================ /* global test, expect */ import React from 'react' import renderer from 'react-test-renderer' import { red } from '../../helpers/color' import Hue from './Hue' import HuePointer from './HuePointer' test('Hue renders correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) test('Hue renders vertically', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) test('Hue renders custom styles correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree.props.style.boxShadow).toBe('0 0 10px red') }) test('HuePointer renders correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) ================================================ FILE: src/components/material/Material.js ================================================ import React from 'react' import reactCSS from 'reactcss' import merge from 'lodash/merge' import * as color from '../../helpers/color' import { ColorWrap, EditableInput, Raised } from '../common' export const Material = ({ onChange, hex, rgb, styles: passedStyles = {}, className = '' }) => { const styles = reactCSS(merge({ 'default': { material: { width: '98px', height: '98px', padding: '16px', fontFamily: 'Roboto', }, HEXwrap: { position: 'relative', }, HEXinput: { width: '100%', marginTop: '12px', fontSize: '15px', color: '#333', padding: '0px', border: '0px', borderBottom: `2px solid ${ hex }`, outline: 'none', height: '30px', }, HEXlabel: { position: 'absolute', top: '0px', left: '0px', fontSize: '11px', color: '#999999', textTransform: 'capitalize', }, Hex: { style: { }, }, RGBwrap: { position: 'relative', }, RGBinput: { width: '100%', marginTop: '12px', fontSize: '15px', color: '#333', padding: '0px', border: '0px', borderBottom: '1px solid #eee', outline: 'none', height: '30px', }, RGBlabel: { position: 'absolute', top: '0px', left: '0px', fontSize: '11px', color: '#999999', textTransform: 'capitalize', }, split: { display: 'flex', marginRight: '-10px', paddingTop: '11px', }, third: { flex: '1', paddingRight: '10px', }, }, }, passedStyles)) const handleChange = (data, e) => { if (data.hex) { color.isValidHex(data.hex) && onChange({ hex: data.hex, source: 'hex', }, e) } else if (data.r || data.g || data.b) { onChange({ r: data.r || rgb.r, g: data.g || rgb.g, b: data.b || rgb.b, source: 'rgb', }, e) } } return (
) } export default ColorWrap(Material) ================================================ FILE: src/components/material/__snapshots__/spec.js.snap ================================================ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Material renders correctly 1`] = `
`; ================================================ FILE: src/components/material/spec.js ================================================ /* global test, test, expect */ import React from 'react' import renderer from 'react-test-renderer' import { red } from '../../helpers/color' import Material from './Material' test('Material renders correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) test('Material renders custom styles correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree.props.style.boxShadow).toBe('0 0 10px red') }) ================================================ FILE: src/components/material/story.js ================================================ import React from 'react' import { storiesOf } from '@storybook/react' import { renderWithKnobs } from '../../../.storybook/report' import SyncColorField from '../../../.storybook/SyncColorField' import Material from './Material' storiesOf('Pickers', module) .add('MaterialPicker', () => ( { renderWithKnobs(Material) } )) ================================================ FILE: src/components/photoshop/Photoshop.js ================================================ import React from 'react' import PropTypes from 'prop-types' import reactCSS from 'reactcss' import merge from 'lodash/merge' import { ColorWrap, Saturation, Hue } from '../common' import PhotoshopFields from './PhotoshopFields' import PhotoshopPointerCircle from './PhotoshopPointerCircle' import PhotoshopPointer from './PhotoshopPointer' import PhotoshopButton from './PhotoshopButton' import PhotoshopPreviews from './PhotoshopPreviews' export class Photoshop extends React.Component { constructor(props) { super() this.state = { currentColor: props.hex, } } render() { const { styles: passedStyles = {}, className = '', } = this.props const styles = reactCSS(merge({ 'default': { picker: { background: '#DCDCDC', borderRadius: '4px', boxShadow: '0 0 0 1px rgba(0,0,0,.25), 0 8px 16px rgba(0,0,0,.15)', boxSizing: 'initial', width: '513px', }, head: { backgroundImage: 'linear-gradient(-180deg, #F0F0F0 0%, #D4D4D4 100%)', borderBottom: '1px solid #B1B1B1', boxShadow: 'inset 0 1px 0 0 rgba(255,255,255,.2), inset 0 -1px 0 0 rgba(0,0,0,.02)', height: '23px', lineHeight: '24px', borderRadius: '4px 4px 0 0', fontSize: '13px', color: '#4D4D4D', textAlign: 'center', }, body: { padding: '15px 15px 0', display: 'flex', }, saturation: { width: '256px', height: '256px', position: 'relative', border: '2px solid #B3B3B3', borderBottom: '2px solid #F0F0F0', overflow: 'hidden', }, hue: { position: 'relative', height: '256px', width: '19px', marginLeft: '10px', border: '2px solid #B3B3B3', borderBottom: '2px solid #F0F0F0', }, controls: { width: '180px', marginLeft: '10px', }, top: { display: 'flex', }, previews: { width: '60px', }, actions: { flex: '1', marginLeft: '20px', }, }, }, passedStyles)) return (
{ this.props.header }
) } } Photoshop.propTypes = { header: PropTypes.string, styles: PropTypes.object, } Photoshop.defaultProps = { header: 'Color Picker', styles: {}, } export default ColorWrap(Photoshop) ================================================ FILE: src/components/photoshop/PhotoshopButton.js ================================================ import React from 'react' import reactCSS from 'reactcss' export const PhotoshopButton = ({ onClick, label, children, active }) => { const styles = reactCSS({ 'default': { button: { backgroundImage: 'linear-gradient(-180deg, #FFFFFF 0%, #E6E6E6 100%)', border: '1px solid #878787', borderRadius: '2px', height: '20px', boxShadow: '0 1px 0 0 #EAEAEA', fontSize: '14px', color: '#000', lineHeight: '20px', textAlign: 'center', marginBottom: '10px', cursor: 'pointer', }, }, 'active': { button: { boxShadow: '0 0 0 1px #878787', }, }, }, { active }) return (
{ label || children }
) } export default PhotoshopButton ================================================ FILE: src/components/photoshop/PhotoshopFields.js ================================================ import React from 'react' import reactCSS from 'reactcss' import * as color from '../../helpers/color' import { EditableInput } from '../common' export const PhotoshopPicker = ({ onChange, rgb, hsv, hex }) => { const styles = reactCSS({ 'default': { fields: { paddingTop: '5px', paddingBottom: '9px', width: '80px', position: 'relative', }, divider: { height: '5px', }, RGBwrap: { position: 'relative', }, RGBinput: { marginLeft: '40%', width: '40%', height: '18px', border: '1px solid #888888', boxShadow: 'inset 0 1px 1px rgba(0,0,0,.1), 0 1px 0 0 #ECECEC', marginBottom: '5px', fontSize: '13px', paddingLeft: '3px', marginRight: '10px', }, RGBlabel: { left: '0px', top: '0px', width: '34px', textTransform: 'uppercase', fontSize: '13px', height: '18px', lineHeight: '22px', position: 'absolute', }, HEXwrap: { position: 'relative', }, HEXinput: { marginLeft: '20%', width: '80%', height: '18px', border: '1px solid #888888', boxShadow: 'inset 0 1px 1px rgba(0,0,0,.1), 0 1px 0 0 #ECECEC', marginBottom: '6px', fontSize: '13px', paddingLeft: '3px', }, HEXlabel: { position: 'absolute', top: '0px', left: '0px', width: '14px', textTransform: 'uppercase', fontSize: '13px', height: '18px', lineHeight: '22px', }, fieldSymbols: { position: 'absolute', top: '5px', right: '-7px', fontSize: '13px', }, symbol: { height: '20px', lineHeight: '22px', paddingBottom: '7px', }, }, }) const handleChange = (data, e) => { if (data['#']) { color.isValidHex(data['#']) && onChange({ hex: data['#'], source: 'hex', }, e) } else if (data.r || data.g || data.b) { onChange({ r: data.r || rgb.r, g: data.g || rgb.g, b: data.b || rgb.b, source: 'rgb', }, e) } else if (data.h || data.s || data.v) { onChange({ h: data.h || hsv.h, s: data.s || hsv.s, v: data.v || hsv.v, source: 'hsv', }, e) } } return (
°
%
%
) } export default PhotoshopPicker ================================================ FILE: src/components/photoshop/PhotoshopPointer.js ================================================ import React from 'react' import reactCSS from 'reactcss' export const PhotoshopPointerCircle = () => { const styles = reactCSS({ 'default': { triangle: { width: 0, height: 0, borderStyle: 'solid', borderWidth: '4px 0 4px 6px', borderColor: 'transparent transparent transparent #fff', position: 'absolute', top: '1px', left: '1px', }, triangleBorder: { width: 0, height: 0, borderStyle: 'solid', borderWidth: '5px 0 5px 8px', borderColor: 'transparent transparent transparent #555', }, left: { Extend: 'triangleBorder', transform: 'translate(-13px, -4px)', }, leftInside: { Extend: 'triangle', transform: 'translate(-8px, -5px)', }, right: { Extend: 'triangleBorder', transform: 'translate(20px, -14px) rotate(180deg)', }, rightInside: { Extend: 'triangle', transform: 'translate(-8px, -5px)', }, }, }) return (
) } export default PhotoshopPointerCircle ================================================ FILE: src/components/photoshop/PhotoshopPointerCircle.js ================================================ import React from 'react' import reactCSS from 'reactcss' export const PhotoshopPointerCircle = ({ hsl }) => { const styles = reactCSS({ 'default': { picker: { width: '12px', height: '12px', borderRadius: '6px', boxShadow: 'inset 0 0 0 1px #fff', transform: 'translate(-6px, -6px)', }, }, 'black-outline': { picker: { boxShadow: 'inset 0 0 0 1px #000', }, }, }, { 'black-outline': hsl.l > 0.5 }) return (
) } export default PhotoshopPointerCircle ================================================ FILE: src/components/photoshop/PhotoshopPreviews.js ================================================ import React from 'react' import reactCSS from 'reactcss' export const PhotoshopPreviews = ({ rgb, currentColor }) => { const styles = reactCSS({ 'default': { swatches: { border: '1px solid #B3B3B3', borderBottom: '1px solid #F0F0F0', marginBottom: '2px', marginTop: '1px', }, new: { height: '34px', background: `rgb(${ rgb.r },${ rgb.g }, ${ rgb.b })`, boxShadow: 'inset 1px 0 0 #000, inset -1px 0 0 #000, inset 0 1px 0 #000', }, current: { height: '34px', background: currentColor, boxShadow: 'inset 1px 0 0 #000, inset -1px 0 0 #000, inset 0 -1px 0 #000', }, label: { fontSize: '14px', color: '#000', textAlign: 'center', }, }, }) return (
new
current
) } export default PhotoshopPreviews ================================================ FILE: src/components/photoshop/__snapshots__/spec.js.snap ================================================ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Photoshop renders correctly 1`] = `
Color Picker
new
current
OK
Cancel
°
%
%
`; exports[`PhotoshopButton renders correctly 1`] = `
accept
`; exports[`PhotoshopFields renders correctly 1`] = `
°
%
%
`; exports[`PhotoshopPointer renders correctly 1`] = `
`; exports[`PhotoshopPointerCircle renders correctly 1`] = `
`; exports[`PhotoshopPreviews renders correctly 1`] = `
new
current
`; ================================================ FILE: src/components/photoshop/spec.js ================================================ /* global test, jest, expect */ import React from 'react' import renderer from 'react-test-renderer' import { red } from '../../helpers/color' import Photoshop from './Photoshop' import PhotoshopButton from './PhotoshopButton' import PhotoshopFields from './PhotoshopFields' import PhotoshopPointer from './PhotoshopPointer' import PhotoshopPointerCircle from './PhotoshopPointerCircle' import PhotoshopPreviews from './PhotoshopPreviews' test('Photoshop renders correctly', () => { const tree = renderer.create( {} } onCancel={ () => {} } />, ).toJSON() expect(tree).toMatchSnapshot() }) test('Photoshop renders custom styles correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree.props.style.boxShadow).toBe('0 0 10px red') }) test('PhotoshopButton renders correctly', () => { const tree = renderer.create( {} } />, ).toJSON() expect(tree).toMatchSnapshot() }) test('PhotoshopFields renders correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) test('PhotoshopPointer renders correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) test('PhotoshopPointerCircle renders correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) test('PhotoshopPreviews renders correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) ================================================ FILE: src/components/photoshop/story.js ================================================ import React from 'react' import { storiesOf } from '@storybook/react' import { renderWithKnobs } from '../../../.storybook/report' import SyncColorField from '../../../.storybook/SyncColorField' import Photoshop from './Photoshop' storiesOf('Pickers', module) .add('PhotoshopPicker', () => ( { renderWithKnobs(Photoshop) } )) ================================================ FILE: src/components/sketch/Sketch.js ================================================ import React from 'react' import PropTypes from 'prop-types' import reactCSS from 'reactcss' import merge from 'lodash/merge' import { ColorWrap, Saturation, Hue, Alpha, Checkboard } from '../common' import SketchFields from './SketchFields' import SketchPresetColors from './SketchPresetColors' export const Sketch = ({ width, rgb, hex, hsv, hsl, onChange, onSwatchHover, disableAlpha, presetColors, renderers, styles: passedStyles = {}, className = '' }) => { const styles = reactCSS(merge({ 'default': { picker: { width, padding: '10px 10px 0', boxSizing: 'initial', background: '#fff', borderRadius: '4px', boxShadow: '0 0 0 1px rgba(0,0,0,.15), 0 8px 16px rgba(0,0,0,.15)', }, saturation: { width: '100%', paddingBottom: '75%', position: 'relative', overflow: 'hidden', }, Saturation: { radius: '3px', shadow: 'inset 0 0 0 1px rgba(0,0,0,.15), inset 0 0 4px rgba(0,0,0,.25)', }, controls: { display: 'flex', }, sliders: { padding: '4px 0', flex: '1', }, color: { width: '24px', height: '24px', position: 'relative', marginTop: '4px', marginLeft: '4px', borderRadius: '3px', }, activeColor: { absolute: '0px 0px 0px 0px', borderRadius: '2px', background: `rgba(${ rgb.r },${ rgb.g },${ rgb.b },${ rgb.a })`, boxShadow: 'inset 0 0 0 1px rgba(0,0,0,.15), inset 0 0 4px rgba(0,0,0,.25)', }, hue: { position: 'relative', height: '10px', overflow: 'hidden', }, Hue: { radius: '2px', shadow: 'inset 0 0 0 1px rgba(0,0,0,.15), inset 0 0 4px rgba(0,0,0,.25)', }, alpha: { position: 'relative', height: '10px', marginTop: '4px', overflow: 'hidden', }, Alpha: { radius: '2px', shadow: 'inset 0 0 0 1px rgba(0,0,0,.15), inset 0 0 4px rgba(0,0,0,.25)', }, ...passedStyles, }, 'disableAlpha': { color: { height: '10px', }, hue: { height: '10px', }, alpha: { display: 'none', }, }, }, passedStyles), { disableAlpha }) return (
) } Sketch.propTypes = { disableAlpha: PropTypes.bool, width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), styles: PropTypes.object, } Sketch.defaultProps = { disableAlpha: false, width: 200, styles: {}, presetColors: ['#D0021B', '#F5A623', '#F8E71C', '#8B572A', '#7ED321', '#417505', '#BD10E0', '#9013FE', '#4A90E2', '#50E3C2', '#B8E986', '#000000', '#4A4A4A', '#9B9B9B', '#FFFFFF'], } export default ColorWrap(Sketch) ================================================ FILE: src/components/sketch/SketchFields.js ================================================ /* eslint-disable no-param-reassign */ import React from 'react' import reactCSS from 'reactcss' import * as color from '../../helpers/color' import { EditableInput } from '../common' export const SketchFields = ({ onChange, rgb, hsl, hex, disableAlpha }) => { const styles = reactCSS({ 'default': { fields: { display: 'flex', paddingTop: '4px', }, single: { flex: '1', paddingLeft: '6px', }, alpha: { flex: '1', paddingLeft: '6px', }, double: { flex: '2', }, input: { width: '80%', padding: '4px 10% 3px', border: 'none', boxShadow: 'inset 0 0 0 1px #ccc', fontSize: '11px', }, label: { display: 'block', textAlign: 'center', fontSize: '11px', color: '#222', paddingTop: '3px', paddingBottom: '4px', textTransform: 'capitalize', }, }, 'disableAlpha': { alpha: { display: 'none', }, }, }, { disableAlpha }) const handleChange = (data, e) => { if (data.hex) { color.isValidHex(data.hex) && onChange({ hex: data.hex, source: 'hex', }, e) } else if (data.r || data.g || data.b) { onChange({ r: data.r || rgb.r, g: data.g || rgb.g, b: data.b || rgb.b, a: rgb.a, source: 'rgb', }, e) } else if (data.a) { if (data.a < 0) { data.a = 0 } else if (data.a > 100) { data.a = 100 } data.a /= 100 onChange({ h: hsl.h, s: hsl.s, l: hsl.l, a: data.a, source: 'rgb', }, e) } } return (
) } export default SketchFields ================================================ FILE: src/components/sketch/SketchPresetColors.js ================================================ import React from 'react' import PropTypes from 'prop-types' import reactCSS from 'reactcss' import { Swatch } from '../common' export const SketchPresetColors = ({ colors, onClick = () => {}, onSwatchHover }) => { const styles = reactCSS({ 'default': { colors: { margin: '0 -10px', padding: '10px 0 0 10px', borderTop: '1px solid #eee', display: 'flex', flexWrap: 'wrap', position: 'relative', }, swatchWrap: { width: '16px', height: '16px', margin: '0 10px 10px 0', }, swatch: { borderRadius: '3px', boxShadow: 'inset 0 0 0 1px rgba(0,0,0,.15)', }, }, 'no-presets': { colors: { display: 'none', }, }, }, { 'no-presets': !colors || !colors.length, }) const handleClick = (hex, e) => { onClick({ hex, source: 'hex', }, e) } return (
{ colors.map((colorObjOrString) => { const c = typeof colorObjOrString === 'string' ? { color: colorObjOrString } : colorObjOrString const key = `${c.color}${c.title || ''}` return (
) }) }
) } SketchPresetColors.propTypes = { colors: PropTypes.arrayOf(PropTypes.oneOfType([ PropTypes.string, PropTypes.shape({ color: PropTypes.string, title: PropTypes.string, })], )).isRequired, } export default SketchPresetColors ================================================ FILE: src/components/sketch/__snapshots__/spec.js.snap ================================================ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Sketch renders correctly 1`] = `
`; exports[`SketchFields renders correctly 1`] = `
`; exports[`SketchPresetColors renders correctly 1`] = `
`; exports[`SketchPresetColors with custom titles renders correctly 1`] = `
`; ================================================ FILE: src/components/sketch/spec.js ================================================ /* global test, jest, expect */ import React from 'react' import renderer from 'react-test-renderer' import { mount } from 'enzyme' import * as color from '../../helpers/color' // import canvas from 'canvas' import Sketch from './Sketch' import SketchFields from './SketchFields' import SketchPresetColors from './SketchPresetColors' import { Swatch } from '../common' test('Sketch renders correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) // test('Sketch renders on server correctly', () => { // const tree = renderer.create( // // ).toJSON() // expect(tree).toMatchSnapshot() // }) test('Sketch onChange events correctly', () => { const changeSpy = jest.fn((data) => { expect(color.simpleCheckForValidColor(data)).toBeTruthy() }) const tree = mount( , ) expect(changeSpy).toHaveBeenCalledTimes(0) const swatches = tree.find(Swatch) swatches.at(0).childAt(0).simulate('click') expect(changeSpy).toHaveBeenCalled() }) test('Sketch with onSwatchHover events correctly', () => { const hoverSpy = jest.fn((data) => { expect(color.simpleCheckForValidColor(data)).toBeTruthy() }) const tree = mount( , ) expect(hoverSpy).toHaveBeenCalledTimes(0) const swatches = tree.find(Swatch) swatches.at(0).childAt(0).simulate('mouseOver') expect(hoverSpy).toHaveBeenCalled() }) test('Sketch renders custom styles correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree.props.style.boxShadow).toBe('none') }) test('SketchFields renders correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) test('SketchPresetColors renders correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) test('SketchPresetColors with custom titles renders correctly', () => { const colors = [ { color: '#fff', title: 'white', }, { color: '#999', title: 'gray', }, { color: '#000', }, '#f00', ] const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) ================================================ FILE: src/components/sketch/story.js ================================================ import React from 'react' import { storiesOf } from '@storybook/react' import { renderWithKnobs } from '../../../.storybook/report' import SyncColorField from '../../../.storybook/SyncColorField' import Sketch from './Sketch' storiesOf('Pickers', module) .add('SketchPicker', () => ( { renderWithKnobs(Sketch, {}, null, { width: { range: true, min: 140, max: 500, step: 1 }, }) } )) .add('SketchPicker Custom Styles', () => ( { renderWithKnobs(Sketch, { styles: { default: { picker: { boxShadow: 'none', }, } } }, null, { width: { range: true, min: 140, max: 500, step: 1 }, }) } )) ================================================ FILE: src/components/slider/Slider.js ================================================ import React from 'react' import PropTypes from 'prop-types' import reactCSS from 'reactcss' import merge from 'lodash/merge' import { ColorWrap, Hue } from '../common' import SliderSwatches from './SliderSwatches' import SliderPointer from './SliderPointer' export const Slider = ({ hsl, onChange, pointer, styles: passedStyles = {}, className = '' }) => { const styles = reactCSS(merge({ 'default': { hue: { height: '12px', position: 'relative', }, Hue: { radius: '2px', }, }, }, passedStyles)) return (
) } Slider.propTypes = { styles: PropTypes.object, } Slider.defaultProps = { pointer: SliderPointer, styles: {}, } export default ColorWrap(Slider) ================================================ FILE: src/components/slider/SliderPointer.js ================================================ import React from 'react' import reactCSS from 'reactcss' export const SliderPointer = () => { const styles = reactCSS({ 'default': { picker: { width: '14px', height: '14px', borderRadius: '6px', transform: 'translate(-7px, -1px)', backgroundColor: 'rgb(248, 248, 248)', boxShadow: '0 1px 4px 0 rgba(0, 0, 0, 0.37)', }, }, }) return (
) } export default SliderPointer ================================================ FILE: src/components/slider/SliderSwatch.js ================================================ import React from 'react' import reactCSS from 'reactcss' export const SliderSwatch = ({ hsl, offset, onClick = () => {}, active, first, last }) => { const styles = reactCSS({ 'default': { swatch: { height: '12px', background: `hsl(${ hsl.h }, 50%, ${ (offset * 100) }%)`, cursor: 'pointer', }, }, 'first': { swatch: { borderRadius: '2px 0 0 2px', }, }, 'last': { swatch: { borderRadius: '0 2px 2px 0', }, }, 'active': { swatch: { transform: 'scaleY(1.8)', borderRadius: '3.6px/2px', }, }, }, { active, first, last }) const handleClick = e => onClick({ h: hsl.h, s: 0.5, l: offset, source: 'hsl', }, e) return (
) } export default SliderSwatch ================================================ FILE: src/components/slider/SliderSwatches.js ================================================ import React from 'react' import reactCSS from 'reactcss' import SliderSwatch from './SliderSwatch' export const SliderSwatches = ({ onClick, hsl }) => { const styles = reactCSS({ 'default': { swatches: { marginTop: '20px', }, swatch: { boxSizing: 'border-box', width: '20%', paddingRight: '1px', float: 'left', }, clear: { clear: 'both', }, }, }) // Acceptible difference in floating point equality const epsilon = 0.1 return (
) } export default SliderSwatches ================================================ FILE: src/components/slider/__snapshots__/spec.js.snap ================================================ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Slider renders correctly 1`] = `
`; exports[`SliderPointer renders correctly 1`] = `
`; exports[`SliderSwatch renders correctly 1`] = `
`; exports[`SliderSwatches renders correctly 1`] = `
`; ================================================ FILE: src/components/slider/spec.js ================================================ /* global test, expect */ import React from 'react' import renderer from 'react-test-renderer' import { red } from '../../helpers/color' import Slider from './Slider' import SliderPointer from './SliderPointer' import SliderSwatch from './SliderSwatch' import SliderSwatches from './SliderSwatches' test('Slider renders correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) test('Slider renders custom styles correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree.props.style.boxShadow).toBe('none') }) test('SliderPointer renders correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) test('SliderSwatch renders correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) test('SliderSwatches renders correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) ================================================ FILE: src/components/swatches/Swatches.js ================================================ import React from 'react' import PropTypes from 'prop-types' import reactCSS from 'reactcss' import map from 'lodash/map' import merge from 'lodash/merge' import * as material from 'material-colors' import { ColorWrap, Raised } from '../common' import SwatchesGroup from './SwatchesGroup' export const Swatches = ({ width, height, onChange, onSwatchHover, colors, hex, styles: passedStyles = {}, className = '' }) => { const styles = reactCSS(merge({ 'default': { picker: { width, height, }, overflow: { height, overflowY: 'scroll', }, body: { padding: '16px 0 6px 16px', }, clear: { clear: 'both', }, }, }, passedStyles)) const handleChange = (data, e) => onChange({ hex: data, source: 'hex' }, e) return (
{ map(colors, group => ( )) }
) } Swatches.propTypes = { width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), colors: PropTypes.arrayOf(PropTypes.arrayOf(PropTypes.string)), styles: PropTypes.object, } /* eslint-disable max-len */ Swatches.defaultProps = { width: 320, height: 240, colors: [ [material.red['900'], material.red['700'], material.red['500'], material.red['300'], material.red['100']], [material.pink['900'], material.pink['700'], material.pink['500'], material.pink['300'], material.pink['100']], [material.purple['900'], material.purple['700'], material.purple['500'], material.purple['300'], material.purple['100']], [material.deepPurple['900'], material.deepPurple['700'], material.deepPurple['500'], material.deepPurple['300'], material.deepPurple['100']], [material.indigo['900'], material.indigo['700'], material.indigo['500'], material.indigo['300'], material.indigo['100']], [material.blue['900'], material.blue['700'], material.blue['500'], material.blue['300'], material.blue['100']], [material.lightBlue['900'], material.lightBlue['700'], material.lightBlue['500'], material.lightBlue['300'], material.lightBlue['100']], [material.cyan['900'], material.cyan['700'], material.cyan['500'], material.cyan['300'], material.cyan['100']], [material.teal['900'], material.teal['700'], material.teal['500'], material.teal['300'], material.teal['100']], ['#194D33', material.green['700'], material.green['500'], material.green['300'], material.green['100']], [material.lightGreen['900'], material.lightGreen['700'], material.lightGreen['500'], material.lightGreen['300'], material.lightGreen['100']], [material.lime['900'], material.lime['700'], material.lime['500'], material.lime['300'], material.lime['100']], [material.yellow['900'], material.yellow['700'], material.yellow['500'], material.yellow['300'], material.yellow['100']], [material.amber['900'], material.amber['700'], material.amber['500'], material.amber['300'], material.amber['100']], [material.orange['900'], material.orange['700'], material.orange['500'], material.orange['300'], material.orange['100']], [material.deepOrange['900'], material.deepOrange['700'], material.deepOrange['500'], material.deepOrange['300'], material.deepOrange['100']], [material.brown['900'], material.brown['700'], material.brown['500'], material.brown['300'], material.brown['100']], [material.blueGrey['900'], material.blueGrey['700'], material.blueGrey['500'], material.blueGrey['300'], material.blueGrey['100']], ['#000000', '#525252', '#969696', '#D9D9D9', '#FFFFFF'], ], styles: {}, } export default ColorWrap(Swatches) ================================================ FILE: src/components/swatches/SwatchesColor.js ================================================ import React from 'react' import reactCSS from 'reactcss' import * as colorUtils from '../../helpers/color' import { Swatch } from '../common' import CheckIcon from '@icons/material/CheckIcon' export const SwatchesColor = ({ color, onClick = () => {}, onSwatchHover, first, last, active }) => { const styles = reactCSS({ 'default': { color: { width: '40px', height: '24px', cursor: 'pointer', background: color, marginBottom: '1px', }, check: { color: colorUtils.getContrastingColor(color), marginLeft: '8px', display: 'none', }, }, 'first': { color: { overflow: 'hidden', borderRadius: '2px 2px 0 0', }, }, 'last': { color: { overflow: 'hidden', borderRadius: '0 0 2px 2px', }, }, 'active': { check: { display: 'block', }, }, 'color-#FFFFFF': { color: { boxShadow: 'inset 0 0 0 1px #ddd', }, check: { color: '#333', }, }, 'transparent': { check: { color: '#333', }, }, }, { first, last, active, 'color-#FFFFFF': color === '#FFFFFF', 'transparent': color === 'transparent', }) return (
) } export default SwatchesColor ================================================ FILE: src/components/swatches/SwatchesGroup.js ================================================ import React from 'react' import reactCSS from 'reactcss' import map from 'lodash/map' import SwatchesColor from './SwatchesColor' export const SwatchesGroup = ({ onClick, onSwatchHover, group, active }) => { const styles = reactCSS({ 'default': { group: { paddingBottom: '10px', width: '40px', float: 'left', marginRight: '10px', }, }, }) return (
{ map(group, (color, i) => ( )) }
) } export default SwatchesGroup ================================================ FILE: src/components/swatches/__snapshots__/spec.js.snap ================================================ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Swatches renders correctly 1`] = `
`; exports[`SwatchesColor renders correctly 1`] = `
`; exports[`SwatchesColor renders with props 1`] = `
`; exports[`SwatchesGroup renders correctly 1`] = `
`; ================================================ FILE: src/components/swatches/spec.js ================================================ /* global test, jest, expect */ import React from 'react' import renderer from 'react-test-renderer' import { mount } from 'enzyme' import * as color from '../../helpers/color' import Swatches from './Swatches' import SwatchesColor from './SwatchesColor' import SwatchesGroup from './SwatchesGroup' import { Swatch } from '../common' test('Swatches renders correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) test('Swatches renders custom styles correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree.props.style.boxShadow).toBe('0 0 10px red') }) test('Swatches onChange events correctly', () => { const changeSpy = jest.fn((data) => { expect(color.simpleCheckForValidColor(data)).toBeTruthy() }) const tree = mount( , ) expect(changeSpy).toHaveBeenCalledTimes(0) const swatches = tree.find(Swatch) swatches.at(0).childAt(0).simulate('click') expect(changeSpy).toHaveBeenCalled() }) test('Swatches with onSwatchHover events correctly', () => { const hoverSpy = jest.fn((data) => { expect(color.simpleCheckForValidColor(data)).toBeTruthy() }) const tree = mount( , ) expect(hoverSpy).toHaveBeenCalledTimes(0) const swatches = tree.find(Swatch) swatches.at(0).childAt(0).simulate('mouseOver') expect(hoverSpy).toHaveBeenCalled() }) test('SwatchesColor renders correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) test('SwatchesColor renders with props', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) test('SwatchesGroup renders correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) ================================================ FILE: src/components/swatches/story.js ================================================ import React from 'react' import { storiesOf } from '@storybook/react' import { renderWithKnobs } from '../../../.storybook/report' import SyncColorField from '../../../.storybook/SyncColorField' import Swatches from './Swatches' storiesOf('Pickers', module) .add('SwatchesPicker', () => ( { renderWithKnobs(Swatches, {}, null, { width: { range: true, min: 140, max: 500, step: 1 }, height: { range: true, min: 140, max: 500, step: 1 }, }) } )) ================================================ FILE: src/components/twitter/Twitter.js ================================================ import React from 'react' import PropTypes from 'prop-types' import reactCSS from 'reactcss' import map from 'lodash/map' import merge from 'lodash/merge' import * as color from '../../helpers/color' import { ColorWrap, EditableInput, Swatch } from '../common' export const Twitter = ({ onChange, onSwatchHover, hex, colors, width, triangle, styles: passedStyles = {}, className = '' }) => { const styles = reactCSS(merge({ 'default': { card: { width, background: '#fff', border: '0 solid rgba(0,0,0,0.25)', boxShadow: '0 1px 4px rgba(0,0,0,0.25)', borderRadius: '4px', position: 'relative', }, body: { padding: '15px 9px 9px 15px', }, label: { fontSize: '18px', color: '#fff', }, triangle: { width: '0px', height: '0px', borderStyle: 'solid', borderWidth: '0 9px 10px 9px', borderColor: 'transparent transparent #fff transparent', position: 'absolute', }, triangleShadow: { width: '0px', height: '0px', borderStyle: 'solid', borderWidth: '0 9px 10px 9px', borderColor: 'transparent transparent rgba(0,0,0,.1) transparent', position: 'absolute', }, hash: { background: '#F0F0F0', height: '30px', width: '30px', borderRadius: '4px 0 0 4px', float: 'left', color: '#98A1A4', display: 'flex', alignItems: 'center', justifyContent: 'center', }, input: { width: '100px', fontSize: '14px', color: '#666', border: '0px', outline: 'none', height: '28px', boxShadow: 'inset 0 0 0 1px #F0F0F0', boxSizing: 'content-box', borderRadius: '0 4px 4px 0', float: 'left', paddingLeft: '8px', }, swatch: { width: '30px', height: '30px', float: 'left', borderRadius: '4px', margin: '0 6px 6px 0', }, clear: { clear: 'both', }, }, 'hide-triangle': { triangle: { display: 'none', }, triangleShadow: { display: 'none', }, }, 'top-left-triangle': { triangle: { top: '-10px', left: '12px', }, triangleShadow: { top: '-11px', left: '12px', }, }, 'top-right-triangle': { triangle: { top: '-10px', right: '12px', }, triangleShadow: { top: '-11px', right: '12px', }, }, }, passedStyles), { 'hide-triangle': triangle === 'hide', 'top-left-triangle': triangle === 'top-left', 'top-right-triangle': triangle === 'top-right', }) const handleChange = (hexcode, e) => { color.isValidHex(hexcode) && onChange({ hex: hexcode, source: 'hex', }, e) } return (
{ map(colors, (c, i) => { return ( ) }) }
#
) } Twitter.propTypes = { width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), triangle: PropTypes.oneOf(['hide', 'top-left', 'top-right']), colors: PropTypes.arrayOf(PropTypes.string), styles: PropTypes.object, } Twitter.defaultProps = { width: 276, colors: ['#FF6900', '#FCB900', '#7BDCB5', '#00D084', '#8ED1FC', '#0693E3', '#ABB8C3', '#EB144C', '#F78DA7', '#9900EF'], triangle: 'top-left', styles: {}, } export default ColorWrap(Twitter) ================================================ FILE: src/components/twitter/__snapshots__/spec.js.snap ================================================ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Twitter \`triangle="hide"\` 1`] = `
#
`; exports[`Twitter \`triangle="top-right"\` 1`] = `
#
`; exports[`Twitter renders correctly 1`] = `
#
`; ================================================ FILE: src/components/twitter/spec.js ================================================ /* global test, jest, expect */ import React from 'react' import renderer from 'react-test-renderer' import { mount } from 'enzyme' import * as color from '../../helpers/color' import Twitter from './Twitter' import { Swatch } from '../common' test('Twitter renders correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) test('Material renders custom styles correctly', () => { const tree = renderer.create( , ).toJSON() expect(tree.props.style.boxShadow).toBe('0 0 10px red') }) test('Twitter `triangle="hide"`', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) test('Twitter `triangle="top-right"`', () => { const tree = renderer.create( , ).toJSON() expect(tree).toMatchSnapshot() }) test('Twitter onChange events correctly', () => { const changeSpy = jest.fn((data) => { expect(color.simpleCheckForValidColor(data)).toBeTruthy() }) const tree = mount( , ) expect(changeSpy).toHaveBeenCalledTimes(0) const swatches = tree.find(Swatch) swatches.at(0).childAt(0).simulate('click') expect(changeSpy).toHaveBeenCalled() }) test('Twitter with onSwatchHover events correctly', () => { const hoverSpy = jest.fn((data) => { expect(color.simpleCheckForValidColor(data)).toBeTruthy() }) const tree = mount( , ) expect(hoverSpy).toHaveBeenCalledTimes(0) const swatches = tree.find(Swatch) swatches.at(0).childAt(0).simulate('mouseOver') expect(hoverSpy).toHaveBeenCalled() }) ================================================ FILE: src/components/twitter/story.js ================================================ import React from 'react' import { storiesOf } from '@storybook/react' import { renderWithKnobs } from '../../../.storybook/report' import SyncColorField from '../../../.storybook/SyncColorField' import Twitter from './Twitter' storiesOf('Pickers', module) .add('TwitterPicker', () => ( { renderWithKnobs(Twitter, {}, null, { width: { range: true, min: 140, max: 500, step: 1 }, }) } )) ================================================ FILE: src/helpers/alpha.js ================================================ export const calculateChange = (e, hsl, direction, initialA, container) => { const containerWidth = container.clientWidth const containerHeight = container.clientHeight const x = typeof e.pageX === 'number' ? e.pageX : e.touches[0].pageX const y = typeof e.pageY === 'number' ? e.pageY : e.touches[0].pageY const left = x - (container.getBoundingClientRect().left + window.pageXOffset) const top = y - (container.getBoundingClientRect().top + window.pageYOffset) if (direction === 'vertical') { let a if (top < 0) { a = 0 } else if (top > containerHeight) { a = 1 } else { a = Math.round((top * 100) / containerHeight) / 100 } if (hsl.a !== a) { return { h: hsl.h, s: hsl.s, l: hsl.l, a, source: 'rgb', } } } else { let a if (left < 0) { a = 0 } else if (left > containerWidth) { a = 1 } else { a = Math.round((left * 100) / containerWidth) / 100 } if (initialA !== a) { return { h: hsl.h, s: hsl.s, l: hsl.l, a, source: 'rgb', } } } return null } ================================================ FILE: src/helpers/checkboard.js ================================================ const checkboardCache = {} export const render = (c1, c2, size, serverCanvas) => { if (typeof document === 'undefined' && !serverCanvas) { return null } const canvas = serverCanvas ? new serverCanvas() : document.createElement('canvas') canvas.width = size * 2 canvas.height = size * 2 const ctx = canvas.getContext('2d') if (!ctx) { return null } // If no context can be found, return early. ctx.fillStyle = c1 ctx.fillRect(0, 0, canvas.width, canvas.height) ctx.fillStyle = c2 ctx.fillRect(0, 0, size, size) ctx.translate(size, size) ctx.fillRect(0, 0, size, size) return canvas.toDataURL() } export const get = (c1, c2, size, serverCanvas) => { const key = `${ c1 }-${ c2 }-${ size }${ serverCanvas ? '-server' : '' }` if (checkboardCache[key]) { return checkboardCache[key] } const checkboard = render(c1, c2, size, serverCanvas) checkboardCache[key] = checkboard return checkboard } ================================================ FILE: src/helpers/color.js ================================================ import each from 'lodash/each' import tinycolor from 'tinycolor2' export const simpleCheckForValidColor = (data) => { const keysToCheck = ['r', 'g', 'b', 'a', 'h', 's', 'l', 'v'] let checked = 0 let passed = 0 each(keysToCheck, (letter) => { if (data[letter]) { checked += 1 if (!isNaN(data[letter])) { passed += 1 } if (letter === 's' || letter === 'l') { const percentPatt = /^\d+%$/ if (percentPatt.test(data[letter])) { passed += 1 } } } }) return (checked === passed) ? data : false } export const toState = (data, oldHue) => { const color = data.hex ? tinycolor(data.hex) : tinycolor(data) const hsl = color.toHsl() const hsv = color.toHsv() const rgb = color.toRgb() const hex = color.toHex() if (hsl.s === 0) { hsl.h = oldHue || 0 hsv.h = oldHue || 0 } const transparent = hex === '000000' && rgb.a === 0 return { hsl, hex: transparent ? 'transparent' : `#${ hex }`, rgb, hsv, oldHue: data.h || oldHue || hsl.h, source: data.source, } } export const isValidHex = (hex) => { if (hex === 'transparent') { return true } // disable hex4 and hex8 const lh = (String(hex).charAt(0) === '#') ? 1 : 0 return hex.length !== (4 + lh) && hex.length < (7 + lh) && tinycolor(hex).isValid() } export const getContrastingColor = (data) => { if (!data) { return '#fff' } const col = toState(data) if (col.hex === 'transparent') { return 'rgba(0,0,0,0.4)' } const yiq = ((col.rgb.r * 299) + (col.rgb.g * 587) + (col.rgb.b * 114)) / 1000 return (yiq >= 128) ? '#000' : '#fff' } export const red = { hsl: { a: 1, h: 0, l: 0.5, s: 1 }, hex: '#ff0000', rgb: { r: 255, g: 0, b: 0, a: 1 }, hsv: { h: 0, s: 1, v: 1, a: 1 }, } export const isvalidColorString = (string, type) => { const stringWithoutDegree = string.replace('°', '') return tinycolor(`${ type } (${ stringWithoutDegree })`)._ok } ================================================ FILE: src/helpers/hue.js ================================================ export const calculateChange = (e, direction, hsl, container) => { const containerWidth = container.clientWidth const containerHeight = container.clientHeight const x = typeof e.pageX === 'number' ? e.pageX : e.touches[0].pageX const y = typeof e.pageY === 'number' ? e.pageY : e.touches[0].pageY const left = x - (container.getBoundingClientRect().left + window.pageXOffset) const top = y - (container.getBoundingClientRect().top + window.pageYOffset) if (direction === 'vertical') { let h if (top < 0) { h = 359 } else if (top > containerHeight) { h = 0 } else { const percent = -((top * 100) / containerHeight) + 100 h = ((360 * percent) / 100) } if (hsl.h !== h) { return { h, s: hsl.s, l: hsl.l, a: hsl.a, source: 'hsl', } } } else { let h if (left < 0) { h = 0 } else if (left > containerWidth) { h = 359 } else { const percent = (left * 100) / containerWidth h = ((360 * percent) / 100) } if (hsl.h !== h) { return { h, s: hsl.s, l: hsl.l, a: hsl.a, source: 'hsl', } } } return null } ================================================ FILE: src/helpers/index.js ================================================ export * from './checkboard' export * from './color' ================================================ FILE: src/helpers/interaction.js ================================================ /* eslint-disable no-invalid-this */ import React from 'react' export const handleFocus = (Component, Span = 'span') => class Focus extends React.Component { state = { focus: false } handleFocus = () => this.setState({ focus: true }) handleBlur = () => this.setState({ focus: false }) render() { return ( ) } } ================================================ FILE: src/helpers/saturation.js ================================================ export const calculateChange = (e, hsl, container) => { const { width: containerWidth, height: containerHeight } = container.getBoundingClientRect() const x = typeof e.pageX === 'number' ? e.pageX : e.touches[0].pageX const y = typeof e.pageY === 'number' ? e.pageY : e.touches[0].pageY let left = x - (container.getBoundingClientRect().left + window.pageXOffset) let top = y - (container.getBoundingClientRect().top + window.pageYOffset) if (left < 0) { left = 0 } else if (left > containerWidth) { left = containerWidth } if (top < 0) { top = 0 } else if (top > containerHeight) { top = containerHeight } const saturation = left / containerWidth const bright = 1 - (top / containerHeight) return { h: hsl.h, s: saturation, v: bright, a: hsl.a, source: 'hsv', } } ================================================ FILE: src/helpers/spec.js ================================================ /* global test, expect, describe */ import * as color from './color' describe('helpers/color', () => { describe('simpleCheckForValidColor', () => { test('throws on null', () => { const data = null expect(() => color.simpleCheckForValidColor(data)).toThrowError(TypeError) }) test('throws on undefined', () => { const data = undefined expect(() => color.simpleCheckForValidColor(data)).toThrowError(TypeError) }) test('no-op on number', () => { const data = 255 expect(color.simpleCheckForValidColor(data)).toEqual(data) }) test('no-op on NaN', () => { const data = NaN expect(isNaN(color.simpleCheckForValidColor(data))).toBeTruthy() }) test('no-op on string', () => { const data = 'ffffff' expect(color.simpleCheckForValidColor(data)).toEqual(data) }) test('no-op on array', () => { const data = [] expect(color.simpleCheckForValidColor(data)).toEqual(data) }) test('no-op on rgb objects with numeric keys', () => { const data = { r: 0, g: 0, b: 0 } expect(color.simpleCheckForValidColor(data)).toEqual(data) }) test('no-op on an object with an r g b a h s v key mapped to a NaN value', () => { const data = { r: NaN } expect(color.simpleCheckForValidColor(data)).toEqual(data) }) test('no-op on hsl "s" percentage', () => { const data = { s: '15%' } expect(color.simpleCheckForValidColor(data)).toEqual(data) }) test('no-op on hsl "l" percentage', () => { const data = { l: '100%' } expect(color.simpleCheckForValidColor(data)).toEqual(data) }) test('should return false for invalid percentage', () => { const data = { l: '100%2' } expect(color.simpleCheckForValidColor(data)).toBe(false) }) }) describe('toState', () => { test('returns an object giving a color in all formats', () => { expect(color.toState('red')).toEqual({ hsl: { a: 1, h: 0, l: 0.5, s: 1 }, hex: '#ff0000', rgb: { r: 255, g: 0, b: 0, a: 1 }, hsv: { h: 0, s: 1, v: 1, a: 1 }, oldHue: 0, source: undefined, }) }) test('gives hex color with leading hash', () => { expect(color.toState('blue').hex).toEqual('#0000ff') }) test('doesn\'t mutate hsl color object', () => { const originalData = { h: 0, s: 0, l: 0, a: 1 } const data = Object.assign({}, originalData) color.toState(data) expect(data).toEqual(originalData) }) test('doesn\'t mutate hsv color object', () => { const originalData = { h: 0, s: 0, v: 0, a: 1 } const data = Object.assign({}, originalData) color.toState(data) expect(data).toEqual(originalData) }) }) describe('isValidHex', () => { test('allows strings of length 3 or 6', () => { expect(color.isValidHex('f')).toBeFalsy() expect(color.isValidHex('ff')).toBeFalsy() expect(color.isValidHex('fff')).toBeTruthy() expect(color.isValidHex('ffff')).toBeFalsy() expect(color.isValidHex('fffff')).toBeFalsy() expect(color.isValidHex('ffffff')).toBeTruthy() expect(color.isValidHex('fffffff')).toBeFalsy() expect(color.isValidHex('ffffffff')).toBeFalsy() expect(color.isValidHex('fffffffff')).toBeFalsy() expect(color.isValidHex('ffffffffff')).toBeFalsy() expect(color.isValidHex('fffffffffff')).toBeFalsy() expect(color.isValidHex('ffffffffffff')).toBeFalsy() }) test('allows strings without leading hash', () => { // Check a sample of possible colors - doing all takes too long. for (let i = 0; i <= 0xffffff; i += 0x010101) { const hex = (`000000${ i.toString(16) }`).slice(-6) expect(color.isValidHex(hex)).toBeTruthy() } }) test('allows strings with leading hash', () => { // Check a sample of possible colors - doing all takes too long. for (let i = 0; i <= 0xffffff; i += 0x010101) { const hex = (`000000${ i.toString(16) }`).slice(-6) expect(color.isValidHex(`#${ hex }`)).toBeTruthy() } }) test('is case-insensitive', () => { expect(color.isValidHex('ffffff')).toBeTruthy() expect(color.isValidHex('FfFffF')).toBeTruthy() expect(color.isValidHex('FFFFFF')).toBeTruthy() }) test('allow transparent color', () => { expect(color.isValidHex('transparent')).toBeTruthy() }) test('does not allow non-hex characters', () => { expect(color.isValidHex('gggggg')).toBeFalsy() }) test('does not allow numbers', () => { expect(color.isValidHex(0xffffff)).toBeFalsy() }) }) describe('getContrastingColor', () => { test('returns a light color for a giving dark color', () => { expect(color.getContrastingColor('red')).toEqual('#fff') }) test('returns a dark color for a giving light color', () => { expect(color.getContrastingColor('white')).toEqual('#000') }) test('returns a predefined color for Transparent', () => { expect(color.getContrastingColor('transparent')).toEqual('rgba(0,0,0,0.4)') }) test('returns a light color as default for undefined', () => { expect(color.getContrastingColor(undefined)).toEqual('#fff') }) }) }) describe('validColorString', () => { test('checks for valid RGB string', () => { expect(color.isvalidColorString('23, 32, 3', 'rgb')).toBeTruthy() expect(color.isvalidColorString('290, 302, 3', 'rgb')).toBeTruthy() expect(color.isvalidColorString('23', 'rgb')).toBeFalsy() expect(color.isvalidColorString('230, 32', 'rgb')).toBeFalsy() }) test('checks for valid HSL string', () => { expect(color.isvalidColorString('200, 12, 93', 'hsl')).toBeTruthy() expect(color.isvalidColorString('200, 12%, 93%', 'hsl')).toBeTruthy() expect(color.isvalidColorString('200, 120, 93%', 'hsl')).toBeTruthy() expect(color.isvalidColorString('335°, 64%, 99%', 'hsl')).toBeTruthy() expect(color.isvalidColorString('100', 'hsl')).toBeFalsy() expect(color.isvalidColorString('20, 32', 'hsl')).toBeFalsy() }) test('checks for valid HSV string', () => { expect(color.isvalidColorString('200, 12, 93', 'hsv')).toBeTruthy() expect(color.isvalidColorString('200, 120, 93%', 'hsv')).toBeTruthy() expect(color.isvalidColorString('200°, 6%, 100%', 'hsv')).toBeTruthy() expect(color.isvalidColorString('1', 'hsv')).toBeFalsy() expect(color.isvalidColorString('20, 32', 'hsv')).toBeFalsy() expect(color.isvalidColorString('200°, ee3, 100%', 'hsv')).toBeFalsy() }) }) ================================================ FILE: src/index.js ================================================ export { default as AlphaPicker } from './components/alpha/Alpha' export { default as BlockPicker } from './components/block/Block' export { default as CirclePicker } from './components/circle/Circle' export default, { default as ChromePicker } from './components/chrome/Chrome' export { default as CompactPicker } from './components/compact/Compact' export { default as GithubPicker } from './components/github/Github' export { default as HuePicker } from './components/hue/Hue' export { default as MaterialPicker } from './components/material/Material' export { default as PhotoshopPicker } from './components/photoshop/Photoshop' export { default as SketchPicker } from './components/sketch/Sketch' export { default as SliderPicker } from './components/slider/Slider' export { default as SwatchesPicker } from './components/swatches/Swatches' export { default as TwitterPicker } from './components/twitter/Twitter' export { default as GooglePicker } from './components/google/Google' export { default as CustomPicker } from './components/common/ColorWrap' export { default as Alpha } from './components/common/Alpha' export { default as Checkboard } from './components/common/Checkboard' export { default as EditableInput } from './components/common/EditableInput' export { default as Hue } from './components/common/Hue' export { default as Raised } from './components/common/Raised' export { default as Saturation } from './components/common/Saturation' export { default as Swatch } from './components/common/Swatch' ================================================ FILE: webpack.config.js ================================================ const path = require('path') const webpack = require('webpack') module.exports = { entry: ['./docs/index.js'], output: { path: path.join(__dirname, 'docs/build'), filename: 'bundle.js', publicPath: 'docs/build/', }, module: { loaders: [ { test: /\.js$/, include: /react-context/, loaders: ['babel-loader'], }, { test: /\.js$/, exclude: [/node_modules/, /modules/], loaders: ['babel-loader'], }, { test: /\.jsx$/, exclude: [/node_modules/, /modules/], loaders: ['jsx-loader', 'babel-loader'], }, { test: /\.css$/, loaders: ['style-loader', 'css-loader'], }, { test: /\.md$/, loaders: ['html-loader'], }, ], }, resolve: { extensions: ['', '.js', '.jsx'], }, plugins: [ new webpack.HotModuleReplacementPlugin({ quiet: true }), new webpack.NoErrorsPlugin(), ], quiet: true, }